Marlin_main.cpp 504 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * About Marlin
  24. *
  25. * This firmware is a mashup between Sprinter and grbl.
  26. * - https://github.com/kliment/Sprinter
  27. * - https://github.com/grbl/grbl
  28. */
  29. /**
  30. * -----------------
  31. * G-Codes in Marlin
  32. * -----------------
  33. *
  34. * Helpful G-code references:
  35. * - http://linuxcnc.org/handbook/gcode/g-code.html
  36. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  37. *
  38. * Help to document Marlin's G-codes online:
  39. * - http://reprap.org/wiki/G-code
  40. * - https://github.com/MarlinFirmware/MarlinDocumentation
  41. *
  42. * -----------------
  43. *
  44. * "G" Codes
  45. *
  46. * G0 -> G1
  47. * G1 - Coordinated Movement X Y Z E
  48. * G2 - CW ARC
  49. * G3 - CCW ARC
  50. * G4 - Dwell S<seconds> or P<milliseconds>
  51. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  52. * G6 - Direct stepper move (Requires UNREGISTERED_MOVE_SUPPORT). Hangprinter defaults to relative moves. Others default to absolute moves.
  53. * G10 - Retract filament according to settings of M207 (Requires FWRETRACT)
  54. * G11 - Retract recover filament according to settings of M208 (Requires FWRETRACT)
  55. * G12 - Clean tool (Requires NOZZLE_CLEAN_FEATURE)
  56. * G17 - Select Plane XY (Requires CNC_WORKSPACE_PLANES)
  57. * G18 - Select Plane ZX (Requires CNC_WORKSPACE_PLANES)
  58. * G19 - Select Plane YZ (Requires CNC_WORKSPACE_PLANES)
  59. * G20 - Set input units to inches (Requires INCH_MODE_SUPPORT)
  60. * G21 - Set input units to millimeters (Requires INCH_MODE_SUPPORT)
  61. * G26 - Mesh Validation Pattern (Requires G26_MESH_VALIDATION)
  62. * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE)
  63. * G28 - Home one or more axes
  64. * G29 - Start or continue the bed leveling probe procedure (Requires bed leveling)
  65. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  66. * G31 - Dock sled (Z_PROBE_SLED only)
  67. * G32 - Undock sled (Z_PROBE_SLED only)
  68. * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION)
  69. * G38 - Probe in any direction using the Z_MIN_PROBE (Requires G38_PROBE_TARGET)
  70. * G42 - Coordinated move to a mesh point (Requires MESH_BED_LEVELING, AUTO_BED_LEVELING_BLINEAR, or AUTO_BED_LEVELING_UBL)
  71. * G90 - Use Absolute Coordinates
  72. * G91 - Use Relative Coordinates
  73. * G92 - Set current position to coordinates given
  74. * G95 - Set torque mode (Requires MECHADUINO_I2C_COMMANDS enabled)
  75. * G96 - Set encoder reference point (Requires MECHADUINO_I2C_COMMANDS enabled)
  76. *
  77. * "M" Codes
  78. *
  79. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  80. * M1 -> M0
  81. * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise
  82. * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise
  83. * M5 - Turn laser/spindle off
  84. * M17 - Enable/Power all stepper motors
  85. * M18 - Disable all stepper motors; same as M84
  86. * M20 - List SD card. (Requires SDSUPPORT)
  87. * M21 - Init SD card. (Requires SDSUPPORT)
  88. * M22 - Release SD card. (Requires SDSUPPORT)
  89. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  90. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  91. * M25 - Pause SD print. (Requires SDSUPPORT)
  92. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  93. * M27 - Report SD print status. (Requires SDSUPPORT)
  94. * OR, with 'S<seconds>' set the SD status auto-report interval. (Requires AUTO_REPORT_SD_STATUS)
  95. * OR, with 'C' get the current filename.
  96. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  97. * M29 - Stop SD write. (Requires SDSUPPORT)
  98. * M30 - Delete file from SD: "M30 /path/file.gco"
  99. * M31 - Report time since last M109 or SD card start to serial.
  100. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  101. * Use P to run other files as sub-programs: "M32 P !filename#"
  102. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  103. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  104. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  105. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  106. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
  107. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs> S<chizoid>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  108. * M75 - Start the print job timer.
  109. * M76 - Pause the print job timer.
  110. * M77 - Stop the print job timer.
  111. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  112. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0)
  113. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0)
  114. * M82 - Set E codes absolute (default).
  115. * M83 - Set E codes relative while in Absolute (G90) mode.
  116. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  117. * duration after which steppers should turn off. S0 disables the timeout.
  118. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  119. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  120. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER)
  121. * M104 - Set extruder target temp.
  122. * M105 - Report current temperatures.
  123. * M106 - Set print fan speed.
  124. * M107 - Print fan off.
  125. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  126. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  127. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  128. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  129. * M110 - Set the current line number. (Used by host printing)
  130. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  131. * M112 - Emergency stop.
  132. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  133. * M114 - Report current position.
  134. * - S1 Compute length traveled since last G96 using encoder position data (Requires MECHADUINO_I2C_COMMANDS, only kinematic axes)
  135. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  136. * M117 - Display a message on the controller screen. (Requires an LCD)
  137. * M118 - Display a message in the host console.
  138. * M119 - Report endstops status.
  139. * M120 - Enable endstops detection.
  140. * M121 - Disable endstops detection.
  141. * M122 - Debug stepper (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  142. * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE)
  143. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  144. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  145. * M128 - EtoP Open. (Requires BARICUDA)
  146. * M129 - EtoP Closed. (Requires BARICUDA)
  147. * M140 - Set bed target temp. S<temp>
  148. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  149. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  150. * M150 - Set Status LED Color as R<red> U<green> B<blue> P<bright>. Values 0-255. (Requires BLINKM, RGB_LED, RGBW_LED, NEOPIXEL_LED, or PCA9632).
  151. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  152. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  153. * M164 - Commit the mix (Req. MIXING_EXTRUDER) and optionally save as a virtual tool (Req. MIXING_VIRTUAL_TOOLS > 1)
  154. * M165 - Set the mix for a mixing extruder wuth parameters ABCDHI. (Requires MIXING_EXTRUDER and DIRECT_MIXING_IN_G1)
  155. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  156. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  157. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  158. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  159. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  160. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  161. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  162. * M205 - Set advanced settings. Current units apply:
  163. S<print> T<travel> minimum speeds
  164. Q<minimum segment time>
  165. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  166. * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  167. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  168. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  169. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  170. Every normal extrude-only move will be classified as retract depending on the direction.
  171. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS)
  172. * M218 - Set/get a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  173. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  174. * M221 - Set Flow Percentage: "M221 S<percent>"
  175. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  176. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  177. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  178. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  179. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  180. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  181. * M290 - Babystepping (Requires BABYSTEPPING)
  182. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  183. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  184. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  185. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  186. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  187. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  188. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  189. * M355 - Set Case Light on/off and set brightness. (Requires CASE_LIGHT_PIN)
  190. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  191. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  192. * M400 - Finish all moves.
  193. * M401 - Deploy and activate Z probe. (Requires a probe)
  194. * M402 - Deactivate and stow Z probe. (Requires a probe)
  195. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  196. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  197. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  198. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  199. * M410 - Quickstop. Abort all planned moves.
  200. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  201. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING, AUTO_BED_LEVELING_BILINEAR, or AUTO_BED_LEVELING_UBL)
  202. * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  203. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  204. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  205. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  206. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  207. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  208. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE)
  209. * M603 - Configure filament change: "M603 T<tool> U<unload_length> L<load_length>". (Requires ADVANCED_PAUSE_FEATURE)
  210. * M605 - Set Dual X-Carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  211. * M665 - Set Delta configurations: "M665 H<delta height> L<diagonal rod> R<delta radius> S<segments/s> B<calibration radius> X<Alpha angle trim> Y<Beta angle trim> Z<Gamma angle trim> (Requires DELTA)
  212. * M665 - Set Hangprinter configurations: "M665 W<Ay> E<Az> R<Bx> T<By> Y<Bz> U<Cx> I<Cy> O<Cz> P<Dz> S<segments/s>" (Requires HANGPRINTER)
  213. * M666 - Set/get endstop offsets for delta (Requires DELTA) or dual endstops (Requires [XYZ]_DUAL_ENDSTOPS).
  214. * M701 - Load filament (requires FILAMENT_LOAD_UNLOAD_GCODES)
  215. * M702 - Unload filament (requires FILAMENT_LOAD_UNLOAD_GCODES)
  216. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  217. * M852 - Set skew factors: "M852 [I<xy>] [J<xz>] [K<yz>]". (Requires SKEW_CORRECTION_GCODE, and SKEW_CORRECTION_FOR_Z for IJ)
  218. * M860 - Report the position of position encoder modules.
  219. * M861 - Report the status of position encoder modules.
  220. * M862 - Perform an axis continuity test for position encoder modules.
  221. * M863 - Perform steps-per-mm calibration for position encoder modules.
  222. * M864 - Change position encoder module I2C address.
  223. * M865 - Check position encoder module firmware version.
  224. * M866 - Report or reset position encoder module error count.
  225. * M867 - Enable/disable or toggle error correction for position encoder modules.
  226. * M868 - Report or set position encoder module error correction threshold.
  227. * M869 - Report position encoder module error.
  228. * M900 - Get or Set Linear Advance K-factor. (Requires LIN_ADVANCE)
  229. * M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  230. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  231. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  232. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  233. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  234. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  235. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  236. * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD)
  237. * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING)
  238. *
  239. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  240. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  241. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  242. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  243. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  244. *
  245. * ************ Custom codes - This can change to suit future G-code regulations
  246. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  247. * M999 - Restart after being stopped by error
  248. *
  249. * "T" Codes
  250. *
  251. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  252. *
  253. */
  254. #include "Marlin.h"
  255. #include "ultralcd.h"
  256. #include "planner.h"
  257. #include "stepper.h"
  258. #include "endstops.h"
  259. #include "temperature.h"
  260. #include "cardreader.h"
  261. #include "configuration_store.h"
  262. #include "language.h"
  263. #include "pins_arduino.h"
  264. #include "math.h"
  265. #include "nozzle.h"
  266. #include "printcounter.h"
  267. #include "duration_t.h"
  268. #include "types.h"
  269. #include "parser.h"
  270. #if ENABLED(AUTO_POWER_CONTROL)
  271. #include "power.h"
  272. #endif
  273. #if ABL_PLANAR
  274. #include "vector_3.h"
  275. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  276. #include "least_squares_fit.h"
  277. #endif
  278. #elif ENABLED(MESH_BED_LEVELING)
  279. #include "mesh_bed_leveling.h"
  280. #endif
  281. #if ENABLED(BEZIER_CURVE_SUPPORT)
  282. #include "planner_bezier.h"
  283. #endif
  284. #if ENABLED(FWRETRACT)
  285. #include "fwretract.h"
  286. #endif
  287. #if ENABLED(POWER_LOSS_RECOVERY)
  288. #include "power_loss_recovery.h"
  289. #endif
  290. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  291. #include "runout.h"
  292. #endif
  293. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  294. #include "buzzer.h"
  295. #endif
  296. #if ENABLED(USE_WATCHDOG)
  297. #include "watchdog.h"
  298. #endif
  299. #if ENABLED(MAX7219_DEBUG)
  300. #include "Max7219_Debug_LEDs.h"
  301. #endif
  302. #if HAS_COLOR_LEDS
  303. #include "leds.h"
  304. #endif
  305. #if HAS_SERVOS
  306. #include "servo.h"
  307. #endif
  308. #if HAS_DIGIPOTSS
  309. #include <SPI.h>
  310. #endif
  311. #if HAS_TRINAMIC
  312. #include "tmc_util.h"
  313. #endif
  314. #if ENABLED(DAC_STEPPER_CURRENT)
  315. #include "stepper_dac.h"
  316. #endif
  317. #if ENABLED(EXPERIMENTAL_I2CBUS)
  318. #include "twibus.h"
  319. #endif
  320. #if ENABLED(I2C_POSITION_ENCODERS)
  321. #include "I2CPositionEncoder.h"
  322. #endif
  323. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  324. void gcode_M100();
  325. void M100_dump_routine(const char * const title, const char *start, const char *end);
  326. #endif
  327. #if ENABLED(G26_MESH_VALIDATION)
  328. bool g26_debug_flag; // =false
  329. void gcode_G26();
  330. #endif
  331. #if ENABLED(SDSUPPORT)
  332. CardReader card;
  333. #endif
  334. #if ENABLED(EXPERIMENTAL_I2CBUS)
  335. TWIBus i2c;
  336. #endif
  337. #if ENABLED(G38_PROBE_TARGET)
  338. bool G38_move = false,
  339. G38_endstop_hit = false;
  340. #endif
  341. #if ENABLED(AUTO_BED_LEVELING_UBL)
  342. #include "ubl.h"
  343. #endif
  344. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  345. int8_t active_coordinate_system = -1; // machine space
  346. float coordinate_system[MAX_COORDINATE_SYSTEMS][XYZ];
  347. #endif
  348. bool Running = true;
  349. uint8_t marlin_debug_flags = DEBUG_NONE;
  350. /**
  351. * Cartesian Current Position
  352. * Used to track the native machine position as moves are queued.
  353. * Used by 'buffer_line_to_current_position' to do a move after changing it.
  354. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  355. */
  356. float current_position[XYZE] = { 0 };
  357. /**
  358. * Cartesian Destination
  359. * The destination for a move, filled in by G-code movement commands,
  360. * and expected by functions like 'prepare_move_to_destination'.
  361. * Set with 'gcode_get_destination' or 'set_destination_from_current'.
  362. */
  363. float destination[XYZE] = { 0 };
  364. /**
  365. * axis_homed
  366. * Flags that each linear axis was homed.
  367. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  368. *
  369. * axis_known_position
  370. * Flags that the position is known in each linear axis. Set when homed.
  371. * Cleared whenever a stepper powers off, potentially losing its position.
  372. */
  373. uint8_t axis_homed, axis_known_position; // = 0
  374. /**
  375. * GCode line number handling. Hosts may opt to include line numbers when
  376. * sending commands to Marlin, and lines will be checked for sequentiality.
  377. * M110 N<int> sets the current line number.
  378. */
  379. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  380. /**
  381. * GCode Command Queue
  382. * A simple ring buffer of BUFSIZE command strings.
  383. *
  384. * Commands are copied into this buffer by the command injectors
  385. * (immediate, serial, sd card) and they are processed sequentially by
  386. * the main loop. The process_next_command function parses the next
  387. * command and hands off execution to individual handler functions.
  388. */
  389. uint8_t commands_in_queue = 0, // Count of commands in the queue
  390. cmd_queue_index_r = 0, // Ring buffer read (out) position
  391. cmd_queue_index_w = 0; // Ring buffer write (in) position
  392. char command_queue[BUFSIZE][MAX_CMD_SIZE];
  393. /**
  394. * Next Injected Command pointer. NULL if no commands are being injected.
  395. * Used by Marlin internally to ensure that commands initiated from within
  396. * are enqueued ahead of any pending serial or sd card commands.
  397. */
  398. static const char *injected_commands_P = NULL;
  399. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  400. TempUnit input_temp_units = TEMPUNIT_C;
  401. #endif
  402. /**
  403. * Feed rates are often configured with mm/m
  404. * but the planner and stepper like mm/s units.
  405. */
  406. static const float homing_feedrate_mm_s[] PROGMEM = {
  407. #if ENABLED(HANGPRINTER)
  408. MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE),
  409. MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), 0
  410. #else
  411. #if ENABLED(DELTA)
  412. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  413. #else
  414. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  415. #endif
  416. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  417. #endif
  418. };
  419. FORCE_INLINE float homing_feedrate(const AxisEnum a) { return pgm_read_float(&homing_feedrate_mm_s[a]); }
  420. float feedrate_mm_s = MMM_TO_MMS(1500.0f);
  421. static float saved_feedrate_mm_s;
  422. int16_t feedrate_percentage = 100, saved_feedrate_percentage;
  423. // Initialized by settings.load()
  424. bool axis_relative_modes[XYZE] = AXIS_RELATIVE_MODES;
  425. #if HAS_WORKSPACE_OFFSET
  426. #if HAS_POSITION_SHIFT
  427. // The distance that XYZ has been offset by G92. Reset by G28.
  428. float position_shift[XYZ] = { 0 };
  429. #endif
  430. #if HAS_HOME_OFFSET
  431. // This offset is added to the configured home position.
  432. // Set by M206, M428, or menu item. Saved to EEPROM.
  433. float home_offset[XYZ] = { 0 };
  434. #endif
  435. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  436. // The above two are combined to save on computes
  437. float workspace_offset[XYZ] = { 0 };
  438. #endif
  439. #endif
  440. // Software Endstops are based on the configured limits.
  441. float soft_endstop_min[XYZ] = { X_MIN_BED, Y_MIN_BED, Z_MIN_POS },
  442. soft_endstop_max[XYZ] = { X_MAX_BED, Y_MAX_BED, Z_MAX_POS };
  443. #if HAS_SOFTWARE_ENDSTOPS
  444. bool soft_endstops_enabled = true;
  445. #if IS_KINEMATIC
  446. float soft_endstop_radius, soft_endstop_radius_2;
  447. #endif
  448. #endif
  449. #if FAN_COUNT > 0
  450. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  451. #if ENABLED(EXTRA_FAN_SPEED)
  452. int16_t old_fanSpeeds[FAN_COUNT],
  453. new_fanSpeeds[FAN_COUNT];
  454. #endif
  455. #if ENABLED(PROBING_FANS_OFF)
  456. bool fans_paused; // = false;
  457. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  458. #endif
  459. #endif
  460. #if ENABLED(USE_CONTROLLER_FAN)
  461. int controllerFanSpeed; // = 0;
  462. #endif
  463. // The active extruder (tool). Set with T<extruder> command.
  464. uint8_t active_extruder; // = 0;
  465. // Relative Mode. Enable with G91, disable with G90.
  466. static bool relative_mode; // = false;
  467. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  468. volatile bool wait_for_heatup = true;
  469. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  470. #if HAS_RESUME_CONTINUE
  471. volatile bool wait_for_user; // = false;
  472. #endif
  473. #if HAS_AUTO_REPORTING || ENABLED(HOST_KEEPALIVE_FEATURE)
  474. bool suspend_auto_report; // = false
  475. #endif
  476. const char axis_codes[XYZE] = { 'X', 'Y', 'Z', 'E' };
  477. #if ENABLED(HANGPRINTER)
  478. const char axis_codes_hangprinter[ABCDE] = { 'A', 'B', 'C', 'D', 'E' };
  479. #define RAW_AXIS_CODES(I) axis_codes_hangprinter[I]
  480. #else
  481. #define RAW_AXIS_CODES(I) axis_codes[I]
  482. #endif
  483. // Number of characters read in the current line of serial input
  484. static int serial_count; // = 0;
  485. // Inactivity shutdown
  486. millis_t previous_move_ms; // = 0;
  487. static millis_t max_inactive_time; // = 0;
  488. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  489. // Buzzer - I2C on the LCD or a BEEPER_PIN
  490. #if ENABLED(LCD_USE_I2C_BUZZER)
  491. #define BUZZ(d,f) lcd_buzz(d, f)
  492. #elif PIN_EXISTS(BEEPER)
  493. Buzzer buzzer;
  494. #define BUZZ(d,f) buzzer.tone(d, f)
  495. #else
  496. #define BUZZ(d,f) NOOP
  497. #endif
  498. uint8_t target_extruder;
  499. #if HAS_BED_PROBE
  500. float zprobe_zoffset; // Initialized by settings.load()
  501. #endif
  502. #if HAS_ABL
  503. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  504. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  505. #elif defined(XY_PROBE_SPEED)
  506. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  507. #else
  508. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  509. #endif
  510. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  511. #if ENABLED(DELTA)
  512. #define ADJUST_DELTA(V) \
  513. if (planner.leveling_active) { \
  514. const float zadj = bilinear_z_offset(V); \
  515. delta[A_AXIS] += zadj; \
  516. delta[B_AXIS] += zadj; \
  517. delta[C_AXIS] += zadj; \
  518. }
  519. #else
  520. #define ADJUST_DELTA(V) if (planner.leveling_active) { delta[Z_AXIS] += bilinear_z_offset(V); }
  521. #endif
  522. #elif IS_KINEMATIC
  523. #define ADJUST_DELTA(V) NOOP
  524. #endif
  525. #if HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  526. const static char msg_wait_for_bed_heating[] PROGMEM = "Wait for bed heating...\n";
  527. #endif
  528. // Extruder offsets
  529. #if HOTENDS > 1
  530. float hotend_offset[XYZ][HOTENDS]; // Initialized by settings.load()
  531. #endif
  532. #if HAS_Z_SERVO_PROBE
  533. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  534. #endif
  535. #if ENABLED(BARICUDA)
  536. uint8_t baricuda_valve_pressure = 0,
  537. baricuda_e_to_p_pressure = 0;
  538. #endif
  539. #if HAS_POWER_SWITCH
  540. bool powersupply_on = (
  541. #if ENABLED(PS_DEFAULT_OFF)
  542. false
  543. #else
  544. true
  545. #endif
  546. );
  547. #if ENABLED(AUTO_POWER_CONTROL)
  548. #define PSU_ON() powerManager.power_on()
  549. #define PSU_OFF() powerManager.power_off()
  550. #else
  551. #define PSU_ON() PSU_PIN_ON()
  552. #define PSU_OFF() PSU_PIN_OFF()
  553. #endif
  554. #endif
  555. #if ENABLED(DELTA)
  556. float delta[ABC];
  557. // Initialized by settings.load()
  558. float delta_height,
  559. delta_endstop_adj[ABC] = { 0 },
  560. delta_radius,
  561. delta_tower_angle_trim[ABC],
  562. delta_tower[ABC][2],
  563. delta_diagonal_rod,
  564. delta_calibration_radius,
  565. delta_diagonal_rod_2_tower[ABC],
  566. delta_segments_per_second,
  567. delta_clip_start_height = Z_MAX_POS;
  568. float delta_safe_distance_from_top();
  569. #elif ENABLED(HANGPRINTER)
  570. float anchor_A_y,
  571. anchor_A_z,
  572. anchor_B_x,
  573. anchor_B_y,
  574. anchor_B_z,
  575. anchor_C_x,
  576. anchor_C_y,
  577. anchor_C_z,
  578. anchor_D_z,
  579. line_lengths[ABCD],
  580. line_lengths_origin[ABCD],
  581. delta_segments_per_second;
  582. #endif
  583. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  584. int bilinear_grid_spacing[2], bilinear_start[2];
  585. float bilinear_grid_factor[2],
  586. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  587. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  588. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  589. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  590. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  591. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  592. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  593. #else
  594. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  595. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  596. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  597. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  598. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  599. #endif
  600. #endif
  601. #if IS_SCARA
  602. // Float constants for SCARA calculations
  603. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  604. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  605. L2_2 = sq(float(L2));
  606. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  607. delta[ABC];
  608. #endif
  609. float cartes[XYZ] = { 0 };
  610. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  611. bool filament_sensor; // = false; // M405 turns on filament sensor control. M406 turns it off.
  612. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  613. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  614. uint8_t meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting
  615. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1], // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  616. filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  617. #endif
  618. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  619. AdvancedPauseMenuResponse advanced_pause_menu_response;
  620. float filament_change_unload_length[EXTRUDERS],
  621. filament_change_load_length[EXTRUDERS];
  622. #endif
  623. #if ENABLED(MIXING_EXTRUDER)
  624. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  625. #if MIXING_VIRTUAL_TOOLS > 1
  626. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  627. #endif
  628. #endif
  629. static bool send_ok[BUFSIZE];
  630. #if HAS_SERVOS
  631. Servo servo[NUM_SERVOS];
  632. #define MOVE_SERVO(I, P) servo[I].move(P)
  633. #if HAS_Z_SERVO_PROBE
  634. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[0])
  635. #define STOW_Z_SERVO() MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[1])
  636. #endif
  637. #endif
  638. #ifdef CHDK
  639. millis_t chdkHigh = 0;
  640. bool chdkActive = false;
  641. #endif
  642. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  643. MarlinBusyState busy_state = NOT_BUSY;
  644. static millis_t next_busy_signal_ms = 0;
  645. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  646. #else
  647. #define host_keepalive() NOOP
  648. #endif
  649. #if ENABLED(I2C_POSITION_ENCODERS)
  650. I2CPositionEncodersMgr I2CPEM;
  651. #endif
  652. #if ENABLED(CNC_WORKSPACE_PLANES)
  653. static WorkspacePlane workspace_plane = PLANE_XY;
  654. #endif
  655. FORCE_INLINE float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  656. FORCE_INLINE signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  657. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  658. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  659. static inline type array(const AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  660. typedef void __void_##CONFIG##__
  661. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  662. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  663. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  664. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  665. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  666. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  667. /**
  668. * ***************************************************************************
  669. * ******************************** FUNCTIONS ********************************
  670. * ***************************************************************************
  671. */
  672. void stop();
  673. void get_available_commands();
  674. void process_next_command();
  675. void process_parsed_command();
  676. void get_cartesian_from_steppers();
  677. void set_current_from_steppers_for_axis(const AxisEnum axis);
  678. #if ENABLED(ARC_SUPPORT)
  679. void plan_arc(const float (&cart)[XYZE], const float (&offset)[2], const bool clockwise);
  680. #endif
  681. #if ENABLED(BEZIER_CURVE_SUPPORT)
  682. void plan_cubic_move(const float (&cart)[XYZE], const float (&offset)[4]);
  683. #endif
  684. void report_current_position();
  685. void report_current_position_detail();
  686. #if ENABLED(DEBUG_LEVELING_FEATURE)
  687. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  688. serialprintPGM(prefix);
  689. SERIAL_CHAR('(');
  690. SERIAL_ECHO(x);
  691. SERIAL_ECHOPAIR(", ", y);
  692. SERIAL_ECHOPAIR(", ", z);
  693. SERIAL_CHAR(')');
  694. if (suffix) serialprintPGM(suffix); else SERIAL_EOL();
  695. }
  696. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  697. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  698. }
  699. #define DEBUG_POS(SUFFIX,VAR) do { \
  700. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); }while(0)
  701. #endif
  702. /**
  703. * sync_plan_position
  704. *
  705. * Set the planner/stepper positions directly from current_position with
  706. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  707. *
  708. * This is not possible for Hangprinter because current_position and position are different sizes
  709. */
  710. void sync_plan_position() {
  711. #if DISABLED(HANGPRINTER)
  712. #if ENABLED(DEBUG_LEVELING_FEATURE)
  713. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  714. #endif
  715. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART]);
  716. #endif
  717. }
  718. void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_CART]); }
  719. #if IS_KINEMATIC
  720. inline void sync_plan_position_kinematic() {
  721. #if ENABLED(DEBUG_LEVELING_FEATURE)
  722. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  723. #endif
  724. planner.set_position_mm_kinematic(current_position);
  725. }
  726. #endif
  727. #if ENABLED(SDSUPPORT)
  728. #include "SdFatUtil.h"
  729. int freeMemory() { return SdFatUtil::FreeRam(); }
  730. #else
  731. extern "C" {
  732. extern char __bss_end;
  733. extern char __heap_start;
  734. extern void* __brkval;
  735. int freeMemory() {
  736. int free_memory;
  737. if (int(__brkval) == 0)
  738. free_memory = (int(&free_memory)) - (int(&__bss_end));
  739. else
  740. free_memory = (int(&free_memory)) - (int(__brkval));
  741. return free_memory;
  742. }
  743. }
  744. #endif // !SDSUPPORT
  745. #if ENABLED(DIGIPOT_I2C)
  746. extern void digipot_i2c_set_current(uint8_t channel, float current);
  747. extern void digipot_i2c_init();
  748. #endif
  749. /**
  750. * Inject the next "immediate" command, when possible, onto the front of the queue.
  751. * Return true if any immediate commands remain to inject.
  752. */
  753. static bool drain_injected_commands_P() {
  754. if (injected_commands_P != NULL) {
  755. size_t i = 0;
  756. char c, cmd[30];
  757. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  758. cmd[sizeof(cmd) - 1] = '\0';
  759. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  760. cmd[i] = '\0';
  761. if (enqueue_and_echo_command(cmd)) // success?
  762. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  763. }
  764. return (injected_commands_P != NULL); // return whether any more remain
  765. }
  766. /**
  767. * Record one or many commands to run from program memory.
  768. * Aborts the current queue, if any.
  769. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  770. */
  771. void enqueue_and_echo_commands_P(const char * const pgcode) {
  772. injected_commands_P = pgcode;
  773. (void)drain_injected_commands_P(); // first command executed asap (when possible)
  774. }
  775. /**
  776. * Clear the Marlin command queue
  777. */
  778. void clear_command_queue() {
  779. cmd_queue_index_r = cmd_queue_index_w = commands_in_queue = 0;
  780. }
  781. /**
  782. * Once a new command is in the ring buffer, call this to commit it
  783. */
  784. inline void _commit_command(bool say_ok) {
  785. send_ok[cmd_queue_index_w] = say_ok;
  786. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  787. commands_in_queue++;
  788. }
  789. /**
  790. * Copy a command from RAM into the main command buffer.
  791. * Return true if the command was successfully added.
  792. * Return false for a full buffer, or if the 'command' is a comment.
  793. */
  794. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  795. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  796. strcpy(command_queue[cmd_queue_index_w], cmd);
  797. _commit_command(say_ok);
  798. return true;
  799. }
  800. /**
  801. * Enqueue with Serial Echo
  802. */
  803. bool enqueue_and_echo_command(const char* cmd) {
  804. if (_enqueuecommand(cmd)) {
  805. SERIAL_ECHO_START();
  806. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  807. SERIAL_CHAR('"');
  808. SERIAL_EOL();
  809. return true;
  810. }
  811. return false;
  812. }
  813. #if HAS_QUEUE_NOW
  814. void enqueue_and_echo_command_now(const char* cmd) {
  815. while (!enqueue_and_echo_command(cmd)) idle();
  816. }
  817. #if HAS_LCD_QUEUE_NOW
  818. void enqueue_and_echo_commands_now_P(const char * const pgcode) {
  819. enqueue_and_echo_commands_P(pgcode);
  820. while (drain_injected_commands_P()) idle();
  821. }
  822. #endif
  823. #endif
  824. void setup_killpin() {
  825. #if HAS_KILL
  826. SET_INPUT_PULLUP(KILL_PIN);
  827. #endif
  828. }
  829. void setup_powerhold() {
  830. #if HAS_SUICIDE
  831. OUT_WRITE(SUICIDE_PIN, HIGH);
  832. #endif
  833. #if HAS_POWER_SWITCH
  834. #if ENABLED(PS_DEFAULT_OFF)
  835. PSU_OFF();
  836. #else
  837. PSU_ON();
  838. #endif
  839. #endif
  840. }
  841. void suicide() {
  842. #if HAS_SUICIDE
  843. OUT_WRITE(SUICIDE_PIN, LOW);
  844. #endif
  845. }
  846. void servo_init() {
  847. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  848. servo[0].attach(SERVO0_PIN);
  849. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  850. #endif
  851. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  852. servo[1].attach(SERVO1_PIN);
  853. servo[1].detach();
  854. #endif
  855. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  856. servo[2].attach(SERVO2_PIN);
  857. servo[2].detach();
  858. #endif
  859. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  860. servo[3].attach(SERVO3_PIN);
  861. servo[3].detach();
  862. #endif
  863. #if HAS_Z_SERVO_PROBE
  864. /**
  865. * Set position of Z Servo Endstop
  866. *
  867. * The servo might be deployed and positioned too low to stow
  868. * when starting up the machine or rebooting the board.
  869. * There's no way to know where the nozzle is positioned until
  870. * homing has been done - no homing with z-probe without init!
  871. *
  872. */
  873. STOW_Z_SERVO();
  874. #endif
  875. }
  876. /**
  877. * Stepper Reset (RigidBoard, et.al.)
  878. */
  879. #if HAS_STEPPER_RESET
  880. void disableStepperDrivers() {
  881. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  882. }
  883. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  884. #endif
  885. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  886. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  887. i2c.receive(bytes);
  888. }
  889. void i2c_on_request() { // just send dummy data for now
  890. i2c.reply("Hello World!\n");
  891. }
  892. #endif
  893. void gcode_line_error(const char* err, bool doFlush = true) {
  894. SERIAL_ERROR_START();
  895. serialprintPGM(err);
  896. SERIAL_ERRORLN(gcode_LastN);
  897. //Serial.println(gcode_N);
  898. if (doFlush) flush_and_request_resend();
  899. serial_count = 0;
  900. }
  901. /**
  902. * Get all commands waiting on the serial port and queue them.
  903. * Exit when the buffer is full or when no more characters are
  904. * left on the serial port.
  905. */
  906. inline void get_serial_commands() {
  907. static char serial_line_buffer[MAX_CMD_SIZE];
  908. static bool serial_comment_mode = false;
  909. // If the command buffer is empty for too long,
  910. // send "wait" to indicate Marlin is still waiting.
  911. #if NO_TIMEOUTS > 0
  912. static millis_t last_command_time = 0;
  913. const millis_t ms = millis();
  914. if (commands_in_queue == 0 && !MYSERIAL0.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  915. SERIAL_ECHOLNPGM(MSG_WAIT);
  916. last_command_time = ms;
  917. }
  918. #endif
  919. /**
  920. * Loop while serial characters are incoming and the queue is not full
  921. */
  922. int c;
  923. while (commands_in_queue < BUFSIZE && (c = MYSERIAL0.read()) >= 0) {
  924. char serial_char = c;
  925. /**
  926. * If the character ends the line
  927. */
  928. if (serial_char == '\n' || serial_char == '\r') {
  929. serial_comment_mode = false; // end of line == end of comment
  930. // Skip empty lines and comments
  931. if (!serial_count) { thermalManager.manage_heater(); continue; }
  932. serial_line_buffer[serial_count] = 0; // Terminate string
  933. serial_count = 0; // Reset buffer
  934. char* command = serial_line_buffer;
  935. while (*command == ' ') command++; // Skip leading spaces
  936. char *npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  937. if (npos) {
  938. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  939. if (M110) {
  940. char* n2pos = strchr(command + 4, 'N');
  941. if (n2pos) npos = n2pos;
  942. }
  943. gcode_N = strtol(npos + 1, NULL, 10);
  944. if (gcode_N != gcode_LastN + 1 && !M110)
  945. return gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  946. char *apos = strrchr(command, '*');
  947. if (apos) {
  948. uint8_t checksum = 0, count = uint8_t(apos - command);
  949. while (count) checksum ^= command[--count];
  950. if (strtol(apos + 1, NULL, 10) != checksum)
  951. return gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  952. }
  953. else
  954. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  955. gcode_LastN = gcode_N;
  956. }
  957. #if ENABLED(SDSUPPORT)
  958. else if (card.saving && strcmp(command, "M29") != 0) // No line number with M29 in Pronterface
  959. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  960. #endif
  961. // Movement commands alert when stopped
  962. if (IsStopped()) {
  963. char* gpos = strchr(command, 'G');
  964. if (gpos) {
  965. switch (strtol(gpos + 1, NULL, 10)) {
  966. case 0:
  967. case 1:
  968. #if ENABLED(ARC_SUPPORT)
  969. case 2:
  970. case 3:
  971. #endif
  972. #if ENABLED(BEZIER_CURVE_SUPPORT)
  973. case 5:
  974. #endif
  975. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  976. LCD_MESSAGEPGM(MSG_STOPPED);
  977. break;
  978. }
  979. }
  980. }
  981. #if DISABLED(EMERGENCY_PARSER)
  982. // Process critical commands early
  983. if (strcmp(command, "M108") == 0) {
  984. wait_for_heatup = false;
  985. #if ENABLED(NEWPANEL)
  986. wait_for_user = false;
  987. #endif
  988. }
  989. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  990. if (strcmp(command, "M410") == 0) quickstop_stepper();
  991. #endif
  992. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  993. last_command_time = ms;
  994. #endif
  995. // Add the command to the queue
  996. _enqueuecommand(serial_line_buffer, true);
  997. }
  998. else if (serial_count >= MAX_CMD_SIZE - 1) {
  999. // Keep fetching, but ignore normal characters beyond the max length
  1000. // The command will be injected when EOL is reached
  1001. }
  1002. else if (serial_char == '\\') { // Handle escapes
  1003. if ((c = MYSERIAL0.read()) >= 0 && !serial_comment_mode) // if we have one more character, copy it over
  1004. serial_line_buffer[serial_count++] = (char)c;
  1005. // otherwise do nothing
  1006. }
  1007. else { // it's not a newline, carriage return or escape char
  1008. if (serial_char == ';') serial_comment_mode = true;
  1009. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1010. }
  1011. } // queue has space, serial has data
  1012. }
  1013. #if ENABLED(SDSUPPORT)
  1014. #if ENABLED(PRINTER_EVENT_LEDS) && HAS_RESUME_CONTINUE
  1015. static bool lights_off_after_print; // = false
  1016. #endif
  1017. /**
  1018. * Get commands from the SD Card until the command buffer is full
  1019. * or until the end of the file is reached. The special character '#'
  1020. * can also interrupt buffering.
  1021. */
  1022. inline void get_sdcard_commands() {
  1023. static bool stop_buffering = false,
  1024. sd_comment_mode = false;
  1025. if (!card.sdprinting) return;
  1026. /**
  1027. * '#' stops reading from SD to the buffer prematurely, so procedural
  1028. * macro calls are possible. If it occurs, stop_buffering is triggered
  1029. * and the buffer is run dry; this character _can_ occur in serial com
  1030. * due to checksums, however, no checksums are used in SD printing.
  1031. */
  1032. if (commands_in_queue == 0) stop_buffering = false;
  1033. uint16_t sd_count = 0;
  1034. bool card_eof = card.eof();
  1035. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1036. const int16_t n = card.get();
  1037. char sd_char = (char)n;
  1038. card_eof = card.eof();
  1039. if (card_eof || n == -1
  1040. || sd_char == '\n' || sd_char == '\r'
  1041. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1042. ) {
  1043. if (card_eof) {
  1044. card.printingHasFinished();
  1045. if (card.sdprinting)
  1046. sd_count = 0; // If a sub-file was printing, continue from call point
  1047. else {
  1048. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1049. #if ENABLED(PRINTER_EVENT_LEDS)
  1050. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1051. leds.set_green();
  1052. #if HAS_RESUME_CONTINUE
  1053. lights_off_after_print = true;
  1054. enqueue_and_echo_commands_P(PSTR("M0 S"
  1055. #if ENABLED(NEWPANEL)
  1056. "1800"
  1057. #else
  1058. "60"
  1059. #endif
  1060. ));
  1061. #else
  1062. safe_delay(2000);
  1063. leds.set_off();
  1064. #endif
  1065. #endif // PRINTER_EVENT_LEDS
  1066. }
  1067. }
  1068. else if (n == -1) {
  1069. SERIAL_ERROR_START();
  1070. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1071. }
  1072. if (sd_char == '#') stop_buffering = true;
  1073. sd_comment_mode = false; // for new command
  1074. // Skip empty lines and comments
  1075. if (!sd_count) { thermalManager.manage_heater(); continue; }
  1076. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1077. sd_count = 0; // clear sd line buffer
  1078. _commit_command(false);
  1079. }
  1080. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1081. /**
  1082. * Keep fetching, but ignore normal characters beyond the max length
  1083. * The command will be injected when EOL is reached
  1084. */
  1085. }
  1086. else {
  1087. if (sd_char == ';') sd_comment_mode = true;
  1088. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1089. }
  1090. }
  1091. }
  1092. #if ENABLED(POWER_LOSS_RECOVERY)
  1093. inline bool drain_job_recovery_commands() {
  1094. static uint8_t job_recovery_commands_index = 0; // Resets on reboot
  1095. if (job_recovery_commands_count) {
  1096. if (_enqueuecommand(job_recovery_commands[job_recovery_commands_index])) {
  1097. ++job_recovery_commands_index;
  1098. if (!--job_recovery_commands_count) job_recovery_phase = JOB_RECOVERY_DONE;
  1099. }
  1100. return true;
  1101. }
  1102. return false;
  1103. }
  1104. #endif
  1105. #endif // SDSUPPORT
  1106. /**
  1107. * Add to the circular command queue the next command from:
  1108. * - The command-injection queue (injected_commands_P)
  1109. * - The active serial input (usually USB)
  1110. * - Commands left in the queue after power-loss
  1111. * - The SD card file being actively printed
  1112. */
  1113. void get_available_commands() {
  1114. // Immediate commands block the other queues
  1115. if (drain_injected_commands_P()) return;
  1116. get_serial_commands();
  1117. #if ENABLED(POWER_LOSS_RECOVERY)
  1118. // Commands for power-loss recovery take precedence
  1119. if (job_recovery_phase == JOB_RECOVERY_YES && drain_job_recovery_commands()) return;
  1120. #endif
  1121. #if ENABLED(SDSUPPORT)
  1122. get_sdcard_commands();
  1123. #endif
  1124. }
  1125. /**
  1126. * Set target_extruder from the T parameter or the active_extruder
  1127. *
  1128. * Returns TRUE if the target is invalid
  1129. */
  1130. bool get_target_extruder_from_command(const uint16_t code) {
  1131. if (parser.seenval('T')) {
  1132. const int8_t e = parser.value_byte();
  1133. if (e >= EXTRUDERS) {
  1134. SERIAL_ECHO_START();
  1135. SERIAL_CHAR('M');
  1136. SERIAL_ECHO(code);
  1137. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", e);
  1138. return true;
  1139. }
  1140. target_extruder = e;
  1141. }
  1142. else
  1143. target_extruder = active_extruder;
  1144. return false;
  1145. }
  1146. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1147. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1148. #endif
  1149. #if ENABLED(DUAL_X_CARRIAGE)
  1150. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1151. static float x_home_pos(const int extruder) {
  1152. if (extruder == 0)
  1153. return base_home_pos(X_AXIS);
  1154. else
  1155. /**
  1156. * In dual carriage mode the extruder offset provides an override of the
  1157. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1158. * This allows soft recalibration of the second extruder home position
  1159. * without firmware reflash (through the M218 command).
  1160. */
  1161. return hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS;
  1162. }
  1163. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1164. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1165. static bool active_extruder_parked = false; // used in mode 1 & 2
  1166. static float raised_parked_position[XYZE]; // used in mode 1
  1167. static millis_t delayed_move_time = 0; // used in mode 1
  1168. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1169. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1170. #endif // DUAL_X_CARRIAGE
  1171. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE) || ENABLED(DELTA)
  1172. /**
  1173. * Software endstops can be used to monitor the open end of
  1174. * an axis that has a hardware endstop on the other end. Or
  1175. * they can prevent axes from moving past endstops and grinding.
  1176. *
  1177. * To keep doing their job as the coordinate system changes,
  1178. * the software endstop positions must be refreshed to remain
  1179. * at the same positions relative to the machine.
  1180. */
  1181. void update_software_endstops(const AxisEnum axis) {
  1182. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1183. workspace_offset[axis] = home_offset[axis] + position_shift[axis];
  1184. #endif
  1185. #if ENABLED(DUAL_X_CARRIAGE)
  1186. if (axis == X_AXIS) {
  1187. // In Dual X mode hotend_offset[X] is T1's home position
  1188. const float dual_max_x = MAX(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1189. if (active_extruder != 0) {
  1190. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1191. soft_endstop_min[X_AXIS] = X2_MIN_POS;
  1192. soft_endstop_max[X_AXIS] = dual_max_x;
  1193. }
  1194. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1195. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1196. // but not so far to the right that T1 would move past the end
  1197. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS);
  1198. soft_endstop_max[X_AXIS] = MIN(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset);
  1199. }
  1200. else {
  1201. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1202. soft_endstop_min[axis] = base_min_pos(axis);
  1203. soft_endstop_max[axis] = base_max_pos(axis);
  1204. }
  1205. }
  1206. #elif ENABLED(DELTA)
  1207. soft_endstop_min[axis] = base_min_pos(axis);
  1208. soft_endstop_max[axis] = axis == Z_AXIS ? delta_height : base_max_pos(axis);
  1209. #else
  1210. soft_endstop_min[axis] = base_min_pos(axis);
  1211. soft_endstop_max[axis] = base_max_pos(axis);
  1212. #endif
  1213. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1214. if (DEBUGGING(LEVELING)) {
  1215. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1216. #if HAS_HOME_OFFSET
  1217. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1218. #endif
  1219. #if HAS_POSITION_SHIFT
  1220. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1221. #endif
  1222. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1223. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1224. }
  1225. #endif
  1226. #if ENABLED(DELTA)
  1227. switch (axis) {
  1228. #if HAS_SOFTWARE_ENDSTOPS
  1229. case X_AXIS:
  1230. case Y_AXIS:
  1231. // Get a minimum radius for clamping
  1232. soft_endstop_radius = MIN3(ABS(MAX(soft_endstop_min[X_AXIS], soft_endstop_min[Y_AXIS])), soft_endstop_max[X_AXIS], soft_endstop_max[Y_AXIS]);
  1233. soft_endstop_radius_2 = sq(soft_endstop_radius);
  1234. break;
  1235. #endif
  1236. case Z_AXIS:
  1237. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1238. default: break;
  1239. }
  1240. #endif
  1241. }
  1242. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE || DELTA
  1243. #if HAS_M206_COMMAND
  1244. /**
  1245. * Change the home offset for an axis.
  1246. * Also refreshes the workspace offset.
  1247. */
  1248. static void set_home_offset(const AxisEnum axis, const float v) {
  1249. home_offset[axis] = v;
  1250. update_software_endstops(axis);
  1251. }
  1252. #endif // HAS_M206_COMMAND
  1253. /**
  1254. * Set an axis' current position to its home position (after homing).
  1255. *
  1256. * For Core and Cartesian robots this applies one-to-one when an
  1257. * individual axis has been homed.
  1258. *
  1259. * DELTA should wait until all homing is done before setting the XYZ
  1260. * current_position to home, because homing is a single operation.
  1261. * In the case where the axis positions are already known and previously
  1262. * homed, DELTA could home to X or Y individually by moving either one
  1263. * to the center. However, homing Z always homes XY and Z.
  1264. *
  1265. * SCARA should wait until all XY homing is done before setting the XY
  1266. * current_position to home, because neither X nor Y is at home until
  1267. * both are at home. Z can however be homed individually.
  1268. *
  1269. * Callers must sync the planner position after calling this!
  1270. */
  1271. static void set_axis_is_at_home(const AxisEnum axis) {
  1272. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1273. if (DEBUGGING(LEVELING)) {
  1274. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1275. SERIAL_CHAR(')');
  1276. SERIAL_EOL();
  1277. }
  1278. #endif
  1279. SBI(axis_known_position, axis);
  1280. SBI(axis_homed, axis);
  1281. #if HAS_POSITION_SHIFT
  1282. position_shift[axis] = 0;
  1283. update_software_endstops(axis);
  1284. #endif
  1285. #if ENABLED(DUAL_X_CARRIAGE)
  1286. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1287. current_position[X_AXIS] = x_home_pos(active_extruder);
  1288. return;
  1289. }
  1290. #endif
  1291. #if ENABLED(MORGAN_SCARA)
  1292. /**
  1293. * Morgan SCARA homes XY at the same time
  1294. */
  1295. if (axis == X_AXIS || axis == Y_AXIS) {
  1296. float homeposition[XYZ] = {
  1297. base_home_pos(X_AXIS),
  1298. base_home_pos(Y_AXIS),
  1299. base_home_pos(Z_AXIS)
  1300. };
  1301. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1302. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1303. /**
  1304. * Get Home position SCARA arm angles using inverse kinematics,
  1305. * and calculate homing offset using forward kinematics
  1306. */
  1307. inverse_kinematics(homeposition);
  1308. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1309. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1310. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1311. current_position[axis] = cartes[axis];
  1312. /**
  1313. * SCARA home positions are based on configuration since the actual
  1314. * limits are determined by the inverse kinematic transform.
  1315. */
  1316. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1317. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1318. }
  1319. else
  1320. #elif ENABLED(DELTA)
  1321. if (axis == Z_AXIS)
  1322. current_position[axis] = delta_height;
  1323. else
  1324. #endif
  1325. {
  1326. current_position[axis] = base_home_pos(axis);
  1327. }
  1328. /**
  1329. * Z Probe Z Homing? Account for the probe's Z offset.
  1330. */
  1331. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1332. if (axis == Z_AXIS) {
  1333. #if HOMING_Z_WITH_PROBE
  1334. current_position[Z_AXIS] -= zprobe_zoffset;
  1335. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1336. if (DEBUGGING(LEVELING)) {
  1337. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1338. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1339. }
  1340. #endif
  1341. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1342. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1343. #endif
  1344. }
  1345. #endif
  1346. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1347. if (DEBUGGING(LEVELING)) {
  1348. #if HAS_HOME_OFFSET
  1349. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1350. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1351. #endif
  1352. DEBUG_POS("", current_position);
  1353. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1354. SERIAL_CHAR(')');
  1355. SERIAL_EOL();
  1356. }
  1357. #endif
  1358. #if ENABLED(I2C_POSITION_ENCODERS)
  1359. I2CPEM.homed(axis);
  1360. #endif
  1361. }
  1362. /**
  1363. * Homing bump feedrate (mm/s)
  1364. */
  1365. inline float get_homing_bump_feedrate(const AxisEnum axis) {
  1366. #if HOMING_Z_WITH_PROBE
  1367. if (axis == Z_AXIS) return MMM_TO_MMS(Z_PROBE_SPEED_SLOW);
  1368. #endif
  1369. static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR;
  1370. uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]);
  1371. if (hbd < 1) {
  1372. hbd = 10;
  1373. SERIAL_ECHO_START();
  1374. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1375. }
  1376. return homing_feedrate(axis) / hbd;
  1377. }
  1378. /**
  1379. * Some planner shorthand inline functions
  1380. */
  1381. /**
  1382. * Move the planner to the current position from wherever it last moved
  1383. * (or from wherever it has been told it is located).
  1384. *
  1385. * Impossible on Hangprinter because current_position and position are of different sizes
  1386. */
  1387. inline void buffer_line_to_current_position() {
  1388. #if DISABLED(HANGPRINTER) // emptying this function probably breaks do_blocking_move_to()
  1389. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], feedrate_mm_s, active_extruder);
  1390. #endif
  1391. }
  1392. /**
  1393. * Move the planner to the position stored in the destination array, which is
  1394. * used by G0/G1/G2/G3/G5 and many other functions to set a destination.
  1395. */
  1396. inline void buffer_line_to_destination(const float &fr_mm_s) {
  1397. #if ENABLED(HANGPRINTER)
  1398. UNUSED(fr_mm_s);
  1399. #else
  1400. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_CART], fr_mm_s, active_extruder);
  1401. #endif
  1402. }
  1403. #if IS_KINEMATIC
  1404. /**
  1405. * Calculate delta, start a line, and set current_position to destination
  1406. */
  1407. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0) {
  1408. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1409. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1410. #endif
  1411. #if UBL_SEGMENTED
  1412. // ubl segmented line will do z-only moves in single segment
  1413. ubl.prepare_segmented_line_to(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s));
  1414. #else
  1415. if ( current_position[X_AXIS] == destination[X_AXIS]
  1416. && current_position[Y_AXIS] == destination[Y_AXIS]
  1417. && current_position[Z_AXIS] == destination[Z_AXIS]
  1418. && current_position[E_CART] == destination[E_CART]
  1419. ) return;
  1420. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1421. #endif
  1422. set_current_from_destination();
  1423. }
  1424. #endif // IS_KINEMATIC
  1425. /**
  1426. * Plan a move to (X, Y, Z) and set the current_position.
  1427. * The final current_position may not be the one that was requested
  1428. * Caution: 'destination' is modified by this function.
  1429. */
  1430. void do_blocking_move_to(const float rx, const float ry, const float rz, const float &fr_mm_s/*=0.0*/) {
  1431. const float old_feedrate_mm_s = feedrate_mm_s;
  1432. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1433. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, LOGICAL_X_POSITION(rx), LOGICAL_Y_POSITION(ry), LOGICAL_Z_POSITION(rz));
  1434. #endif
  1435. const float z_feedrate = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1436. #if ENABLED(DELTA)
  1437. if (!position_is_reachable(rx, ry)) return;
  1438. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1439. set_destination_from_current(); // sync destination at the start
  1440. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1441. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_from_current", destination);
  1442. #endif
  1443. // when in the danger zone
  1444. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1445. if (rz > delta_clip_start_height) { // staying in the danger zone
  1446. destination[X_AXIS] = rx; // move directly (uninterpolated)
  1447. destination[Y_AXIS] = ry;
  1448. destination[Z_AXIS] = rz;
  1449. prepare_uninterpolated_move_to_destination(); // set_current_from_destination
  1450. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1451. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1452. #endif
  1453. return;
  1454. }
  1455. destination[Z_AXIS] = delta_clip_start_height;
  1456. prepare_uninterpolated_move_to_destination(); // set_current_from_destination
  1457. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1458. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1459. #endif
  1460. }
  1461. if (rz > current_position[Z_AXIS]) { // raising?
  1462. destination[Z_AXIS] = rz;
  1463. prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_from_destination
  1464. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1465. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1466. #endif
  1467. }
  1468. destination[X_AXIS] = rx;
  1469. destination[Y_AXIS] = ry;
  1470. prepare_move_to_destination(); // set_current_from_destination
  1471. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1472. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1473. #endif
  1474. if (rz < current_position[Z_AXIS]) { // lowering?
  1475. destination[Z_AXIS] = rz;
  1476. prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_from_destination
  1477. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1478. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1479. #endif
  1480. }
  1481. #elif IS_SCARA
  1482. if (!position_is_reachable(rx, ry)) return;
  1483. set_destination_from_current();
  1484. // If Z needs to raise, do it before moving XY
  1485. if (destination[Z_AXIS] < rz) {
  1486. destination[Z_AXIS] = rz;
  1487. prepare_uninterpolated_move_to_destination(z_feedrate);
  1488. }
  1489. destination[X_AXIS] = rx;
  1490. destination[Y_AXIS] = ry;
  1491. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1492. // If Z needs to lower, do it after moving XY
  1493. if (destination[Z_AXIS] > rz) {
  1494. destination[Z_AXIS] = rz;
  1495. prepare_uninterpolated_move_to_destination(z_feedrate);
  1496. }
  1497. #else
  1498. // If Z needs to raise, do it before moving XY
  1499. if (current_position[Z_AXIS] < rz) {
  1500. feedrate_mm_s = z_feedrate;
  1501. current_position[Z_AXIS] = rz;
  1502. buffer_line_to_current_position();
  1503. }
  1504. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1505. current_position[X_AXIS] = rx;
  1506. current_position[Y_AXIS] = ry;
  1507. buffer_line_to_current_position();
  1508. // If Z needs to lower, do it after moving XY
  1509. if (current_position[Z_AXIS] > rz) {
  1510. feedrate_mm_s = z_feedrate;
  1511. current_position[Z_AXIS] = rz;
  1512. buffer_line_to_current_position();
  1513. }
  1514. #endif
  1515. planner.synchronize();
  1516. feedrate_mm_s = old_feedrate_mm_s;
  1517. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1518. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1519. #endif
  1520. }
  1521. void do_blocking_move_to_x(const float &rx, const float &fr_mm_s/*=0.0*/) {
  1522. do_blocking_move_to(rx, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1523. }
  1524. void do_blocking_move_to_z(const float &rz, const float &fr_mm_s/*=0.0*/) {
  1525. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], rz, fr_mm_s);
  1526. }
  1527. void do_blocking_move_to_xy(const float &rx, const float &ry, const float &fr_mm_s/*=0.0*/) {
  1528. do_blocking_move_to(rx, ry, current_position[Z_AXIS], fr_mm_s);
  1529. }
  1530. //
  1531. // Prepare to do endstop or probe moves
  1532. // with custom feedrates.
  1533. //
  1534. // - Save current feedrates
  1535. // - Reset the rate multiplier
  1536. // - Reset the command timeout
  1537. // - Enable the endstops (for endstop moves)
  1538. //
  1539. void setup_for_endstop_or_probe_move() {
  1540. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1541. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1542. #endif
  1543. saved_feedrate_mm_s = feedrate_mm_s;
  1544. saved_feedrate_percentage = feedrate_percentage;
  1545. feedrate_percentage = 100;
  1546. }
  1547. void clean_up_after_endstop_or_probe_move() {
  1548. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1549. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1550. #endif
  1551. feedrate_mm_s = saved_feedrate_mm_s;
  1552. feedrate_percentage = saved_feedrate_percentage;
  1553. }
  1554. #if HAS_AXIS_UNHOMED_ERR
  1555. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1556. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1557. const bool xx = x && !TEST(axis_known_position, X_AXIS),
  1558. yy = y && !TEST(axis_known_position, Y_AXIS),
  1559. zz = z && !TEST(axis_known_position, Z_AXIS);
  1560. #else
  1561. const bool xx = x && !TEST(axis_homed, X_AXIS),
  1562. yy = y && !TEST(axis_homed, Y_AXIS),
  1563. zz = z && !TEST(axis_homed, Z_AXIS);
  1564. #endif
  1565. if (xx || yy || zz) {
  1566. SERIAL_ECHO_START();
  1567. SERIAL_ECHOPGM(MSG_HOME " ");
  1568. if (xx) SERIAL_ECHOPGM(MSG_X);
  1569. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1570. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1571. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1572. #if ENABLED(ULTRA_LCD)
  1573. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1574. #endif
  1575. return true;
  1576. }
  1577. return false;
  1578. }
  1579. #endif // HAS_AXIS_UNHOMED_ERR
  1580. #if ENABLED(Z_PROBE_SLED)
  1581. #ifndef SLED_DOCKING_OFFSET
  1582. #define SLED_DOCKING_OFFSET 0
  1583. #endif
  1584. /**
  1585. * Method to dock/undock a sled designed by Charles Bell.
  1586. *
  1587. * stow[in] If false, move to MAX_X and engage the solenoid
  1588. * If true, move to MAX_X and release the solenoid
  1589. */
  1590. static void dock_sled(bool stow) {
  1591. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1592. if (DEBUGGING(LEVELING)) {
  1593. SERIAL_ECHOPAIR("dock_sled(", stow);
  1594. SERIAL_CHAR(')');
  1595. SERIAL_EOL();
  1596. }
  1597. #endif
  1598. // Dock sled a bit closer to ensure proper capturing
  1599. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1600. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1601. WRITE(SOL1_PIN, !stow); // switch solenoid
  1602. #endif
  1603. }
  1604. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1605. FORCE_INLINE void do_blocking_move_to(const float (&raw)[XYZ], const float &fr_mm_s) {
  1606. do_blocking_move_to(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], fr_mm_s);
  1607. }
  1608. void run_deploy_moves_script() {
  1609. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Z)
  1610. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1611. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1612. #endif
  1613. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1614. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1615. #endif
  1616. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1617. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1618. #endif
  1619. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1620. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1621. #endif
  1622. const float deploy_1[] = { Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z };
  1623. do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1624. #endif
  1625. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Z)
  1626. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1627. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1628. #endif
  1629. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1630. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1631. #endif
  1632. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1633. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1634. #endif
  1635. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1636. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1637. #endif
  1638. const float deploy_2[] = { Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z };
  1639. do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1640. #endif
  1641. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Z)
  1642. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1643. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1644. #endif
  1645. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1646. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1647. #endif
  1648. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1649. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1650. #endif
  1651. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1652. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1653. #endif
  1654. const float deploy_3[] = { Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z };
  1655. do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1656. #endif
  1657. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Z)
  1658. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1659. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1660. #endif
  1661. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1662. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1663. #endif
  1664. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1665. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1666. #endif
  1667. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1668. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1669. #endif
  1670. const float deploy_4[] = { Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z };
  1671. do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1672. #endif
  1673. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Z)
  1674. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1675. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1676. #endif
  1677. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1678. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1679. #endif
  1680. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1681. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1682. #endif
  1683. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1684. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1685. #endif
  1686. const float deploy_5[] = { Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z };
  1687. do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1688. #endif
  1689. }
  1690. void run_stow_moves_script() {
  1691. #if defined(Z_PROBE_ALLEN_KEY_STOW_1_X) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Z)
  1692. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1693. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1694. #endif
  1695. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1696. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1697. #endif
  1698. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1699. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1700. #endif
  1701. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1702. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1703. #endif
  1704. const float stow_1[] = { Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z };
  1705. do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1706. #endif
  1707. #if defined(Z_PROBE_ALLEN_KEY_STOW_2_X) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Z)
  1708. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1709. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1710. #endif
  1711. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1712. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1713. #endif
  1714. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1715. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1716. #endif
  1717. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1718. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1719. #endif
  1720. const float stow_2[] = { Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z };
  1721. do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1722. #endif
  1723. #if defined(Z_PROBE_ALLEN_KEY_STOW_3_X) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Z)
  1724. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1725. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1726. #endif
  1727. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1728. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1729. #endif
  1730. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1731. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1732. #endif
  1733. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1734. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1735. #endif
  1736. const float stow_3[] = { Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z };
  1737. do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1738. #endif
  1739. #if defined(Z_PROBE_ALLEN_KEY_STOW_4_X) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Z)
  1740. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1741. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1742. #endif
  1743. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1744. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1745. #endif
  1746. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1747. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1748. #endif
  1749. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1750. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1751. #endif
  1752. const float stow_4[] = { Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z };
  1753. do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1754. #endif
  1755. #if defined(Z_PROBE_ALLEN_KEY_STOW_5_X) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Z)
  1756. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1757. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1758. #endif
  1759. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1760. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1761. #endif
  1762. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1763. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1764. #endif
  1765. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1766. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1767. #endif
  1768. const float stow_5[] = { Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z };
  1769. do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1770. #endif
  1771. }
  1772. #endif // Z_PROBE_ALLEN_KEY
  1773. #if ENABLED(PROBING_FANS_OFF)
  1774. void fans_pause(const bool p) {
  1775. if (p != fans_paused) {
  1776. fans_paused = p;
  1777. if (p)
  1778. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1779. paused_fanSpeeds[x] = fanSpeeds[x];
  1780. fanSpeeds[x] = 0;
  1781. }
  1782. else
  1783. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1784. fanSpeeds[x] = paused_fanSpeeds[x];
  1785. }
  1786. }
  1787. #endif // PROBING_FANS_OFF
  1788. #if HAS_BED_PROBE
  1789. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1790. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1791. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1792. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1793. #else
  1794. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1795. #endif
  1796. #endif
  1797. #if QUIET_PROBING
  1798. void probing_pause(const bool p) {
  1799. #if ENABLED(PROBING_HEATERS_OFF)
  1800. thermalManager.pause(p);
  1801. #endif
  1802. #if ENABLED(PROBING_FANS_OFF)
  1803. fans_pause(p);
  1804. #endif
  1805. if (p) safe_delay(
  1806. #if DELAY_BEFORE_PROBING > 25
  1807. DELAY_BEFORE_PROBING
  1808. #else
  1809. 25
  1810. #endif
  1811. );
  1812. }
  1813. #endif // QUIET_PROBING
  1814. #if ENABLED(BLTOUCH)
  1815. void bltouch_command(int angle) {
  1816. MOVE_SERVO(Z_PROBE_SERVO_NR, angle); // Give the BL-Touch the command and wait
  1817. safe_delay(BLTOUCH_DELAY);
  1818. }
  1819. bool set_bltouch_deployed(const bool deploy) {
  1820. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1821. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1822. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1823. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1824. safe_delay(1500); // Wait for internal self-test to complete.
  1825. // (Measured completion time was 0.65 seconds
  1826. // after reset, deploy, and stow sequence)
  1827. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1828. SERIAL_ERROR_START();
  1829. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1830. stop(); // punt!
  1831. return true;
  1832. }
  1833. }
  1834. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1835. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1836. if (DEBUGGING(LEVELING)) {
  1837. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1838. SERIAL_CHAR(')');
  1839. SERIAL_EOL();
  1840. }
  1841. #endif
  1842. return false;
  1843. }
  1844. #endif // BLTOUCH
  1845. /**
  1846. * Raise Z to a minimum height to make room for a probe to move
  1847. */
  1848. inline void do_probe_raise(const float z_raise) {
  1849. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1850. if (DEBUGGING(LEVELING)) {
  1851. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1852. SERIAL_CHAR(')');
  1853. SERIAL_EOL();
  1854. }
  1855. #endif
  1856. float z_dest = z_raise;
  1857. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1858. NOMORE(z_dest, Z_MAX_POS);
  1859. if (z_dest > current_position[Z_AXIS])
  1860. do_blocking_move_to_z(z_dest);
  1861. }
  1862. // returns false for ok and true for failure
  1863. bool set_probe_deployed(const bool deploy) {
  1864. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1865. if (DEBUGGING(LEVELING)) {
  1866. DEBUG_POS("set_probe_deployed", current_position);
  1867. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1868. }
  1869. #endif
  1870. if (endstops.z_probe_enabled == deploy) return false;
  1871. // Make room for probe to deploy (or stow)
  1872. // Fix-mounted probe should only raise for deploy
  1873. #if ENABLED(FIX_MOUNTED_PROBE)
  1874. const bool deploy_stow_condition = deploy;
  1875. #else
  1876. constexpr bool deploy_stow_condition = true;
  1877. #endif
  1878. // For beds that fall when Z is powered off only raise for trusted Z
  1879. #if ENABLED(UNKNOWN_Z_NO_RAISE)
  1880. const bool unknown_condition = TEST(axis_known_position, Z_AXIS);
  1881. #else
  1882. constexpr float unknown_condition = true;
  1883. #endif
  1884. if (deploy_stow_condition && unknown_condition)
  1885. do_probe_raise(MAX(Z_CLEARANCE_BETWEEN_PROBES, Z_CLEARANCE_DEPLOY_PROBE));
  1886. #if ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  1887. #if ENABLED(Z_PROBE_SLED)
  1888. #define _AUE_ARGS true, false, false
  1889. #else
  1890. #define _AUE_ARGS
  1891. #endif
  1892. if (axis_unhomed_error(_AUE_ARGS)) {
  1893. SERIAL_ERROR_START();
  1894. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1895. stop();
  1896. return true;
  1897. }
  1898. #endif
  1899. const float oldXpos = current_position[X_AXIS],
  1900. oldYpos = current_position[Y_AXIS];
  1901. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1902. // If endstop is already false, the Z probe is deployed
  1903. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1904. // Would a goto be less ugly?
  1905. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1906. // for a triggered when stowed manual probe.
  1907. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1908. // otherwise an Allen-Key probe can't be stowed.
  1909. #endif
  1910. #if ENABLED(SOLENOID_PROBE)
  1911. #if HAS_SOLENOID_1
  1912. WRITE(SOL1_PIN, deploy);
  1913. #endif
  1914. #elif ENABLED(Z_PROBE_SLED)
  1915. dock_sled(!deploy);
  1916. #elif HAS_Z_SERVO_PROBE && DISABLED(BLTOUCH)
  1917. MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[deploy ? 0 : 1]);
  1918. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1919. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1920. #endif
  1921. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1922. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1923. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1924. if (IsRunning()) {
  1925. SERIAL_ERROR_START();
  1926. SERIAL_ERRORLNPGM("Z-Probe failed");
  1927. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1928. }
  1929. stop();
  1930. return true;
  1931. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1932. #endif
  1933. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1934. endstops.enable_z_probe(deploy);
  1935. return false;
  1936. }
  1937. /**
  1938. * @brief Used by run_z_probe to do a single Z probe move.
  1939. *
  1940. * @param z Z destination
  1941. * @param fr_mm_s Feedrate in mm/s
  1942. * @return true to indicate an error
  1943. */
  1944. static bool do_probe_move(const float z, const float fr_mm_s) {
  1945. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1946. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1947. #endif
  1948. #if HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  1949. // Wait for bed to heat back up between probing points
  1950. if (thermalManager.isHeatingBed()) {
  1951. serialprintPGM(msg_wait_for_bed_heating);
  1952. LCD_MESSAGEPGM(MSG_BED_HEATING);
  1953. while (thermalManager.isHeatingBed()) safe_delay(200);
  1954. lcd_reset_status();
  1955. }
  1956. #endif
  1957. // Deploy BLTouch at the start of any probe
  1958. #if ENABLED(BLTOUCH)
  1959. if (set_bltouch_deployed(true)) return true;
  1960. #endif
  1961. #if QUIET_PROBING
  1962. probing_pause(true);
  1963. #endif
  1964. // Move down until probe triggered
  1965. do_blocking_move_to_z(z, fr_mm_s);
  1966. // Check to see if the probe was triggered
  1967. const bool probe_triggered = TEST(endstops.trigger_state(),
  1968. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  1969. Z_MIN
  1970. #else
  1971. Z_MIN_PROBE
  1972. #endif
  1973. );
  1974. #if QUIET_PROBING
  1975. probing_pause(false);
  1976. #endif
  1977. // Retract BLTouch immediately after a probe if it was triggered
  1978. #if ENABLED(BLTOUCH)
  1979. if (probe_triggered && set_bltouch_deployed(false)) return true;
  1980. #endif
  1981. endstops.hit_on_purpose();
  1982. // Get Z where the steppers were interrupted
  1983. set_current_from_steppers_for_axis(Z_AXIS);
  1984. // Tell the planner where we actually are
  1985. SYNC_PLAN_POSITION_KINEMATIC();
  1986. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1987. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1988. #endif
  1989. return !probe_triggered;
  1990. }
  1991. /**
  1992. * @details Used by probe_pt to do a single Z probe at the current position.
  1993. * Leaves current_position[Z_AXIS] at the height where the probe triggered.
  1994. *
  1995. * @return The raw Z position where the probe was triggered
  1996. */
  1997. static float run_z_probe() {
  1998. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1999. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  2000. #endif
  2001. // Stop the probe before it goes too low to prevent damage.
  2002. // If Z isn't known then probe to -10mm.
  2003. const float z_probe_low_point = TEST(axis_known_position, Z_AXIS) ? -zprobe_zoffset + Z_PROBE_LOW_POINT : -10.0;
  2004. // Double-probing does a fast probe followed by a slow probe
  2005. #if MULTIPLE_PROBING == 2
  2006. // Do a first probe at the fast speed
  2007. if (do_probe_move(z_probe_low_point, MMM_TO_MMS(Z_PROBE_SPEED_FAST))) {
  2008. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2009. if (DEBUGGING(LEVELING)) {
  2010. SERIAL_ECHOLNPGM("FAST Probe fail!");
  2011. DEBUG_POS("<<< run_z_probe", current_position);
  2012. }
  2013. #endif
  2014. return NAN;
  2015. }
  2016. float first_probe_z = current_position[Z_AXIS];
  2017. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2018. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  2019. #endif
  2020. // move up to make clearance for the probe
  2021. do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_MULTI_PROBE, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2022. #else
  2023. // If the nozzle is well over the travel height then
  2024. // move down quickly before doing the slow probe
  2025. float z = Z_CLEARANCE_DEPLOY_PROBE + 5.0;
  2026. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  2027. if (current_position[Z_AXIS] > z) {
  2028. // If we don't make it to the z position (i.e. the probe triggered), move up to make clearance for the probe
  2029. if (!do_probe_move(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST)))
  2030. do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_BETWEEN_PROBES, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2031. }
  2032. #endif
  2033. #if MULTIPLE_PROBING > 2
  2034. float probes_total = 0;
  2035. for (uint8_t p = MULTIPLE_PROBING + 1; --p;) {
  2036. #endif
  2037. // move down slowly to find bed
  2038. if (do_probe_move(z_probe_low_point, MMM_TO_MMS(Z_PROBE_SPEED_SLOW))) {
  2039. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2040. if (DEBUGGING(LEVELING)) {
  2041. SERIAL_ECHOLNPGM("SLOW Probe fail!");
  2042. DEBUG_POS("<<< run_z_probe", current_position);
  2043. }
  2044. #endif
  2045. return NAN;
  2046. }
  2047. #if MULTIPLE_PROBING > 2
  2048. probes_total += current_position[Z_AXIS];
  2049. if (p > 1) do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_MULTI_PROBE, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2050. }
  2051. #endif
  2052. #if MULTIPLE_PROBING > 2
  2053. // Return the average value of all probes
  2054. const float measured_z = probes_total * (1.0f / (MULTIPLE_PROBING));
  2055. #elif MULTIPLE_PROBING == 2
  2056. const float z2 = current_position[Z_AXIS];
  2057. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2058. if (DEBUGGING(LEVELING)) {
  2059. SERIAL_ECHOPAIR("2nd Probe Z:", z2);
  2060. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - z2);
  2061. }
  2062. #endif
  2063. // Return a weighted average of the fast and slow probes
  2064. const float measured_z = (z2 * 3.0 + first_probe_z * 2.0) * 0.2;
  2065. #else
  2066. // Return the single probe result
  2067. const float measured_z = current_position[Z_AXIS];
  2068. #endif
  2069. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2070. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  2071. #endif
  2072. return measured_z;
  2073. }
  2074. /**
  2075. * - Move to the given XY
  2076. * - Deploy the probe, if not already deployed
  2077. * - Probe the bed, get the Z position
  2078. * - Depending on the 'stow' flag
  2079. * - Stow the probe, or
  2080. * - Raise to the BETWEEN height
  2081. * - Return the probed Z position
  2082. */
  2083. float probe_pt(const float &rx, const float &ry, const ProbePtRaise raise_after/*=PROBE_PT_NONE*/, const uint8_t verbose_level/*=0*/, const bool probe_relative/*=true*/) {
  2084. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2085. if (DEBUGGING(LEVELING)) {
  2086. SERIAL_ECHOPAIR(">>> probe_pt(", LOGICAL_X_POSITION(rx));
  2087. SERIAL_ECHOPAIR(", ", LOGICAL_Y_POSITION(ry));
  2088. SERIAL_ECHOPAIR(", ", raise_after == PROBE_PT_RAISE ? "raise" : raise_after == PROBE_PT_STOW ? "stow" : "none");
  2089. SERIAL_ECHOPAIR(", ", int(verbose_level));
  2090. SERIAL_ECHOPAIR(", ", probe_relative ? "probe" : "nozzle");
  2091. SERIAL_ECHOLNPGM("_relative)");
  2092. DEBUG_POS("", current_position);
  2093. }
  2094. #endif
  2095. // TODO: Adapt for SCARA, where the offset rotates
  2096. float nx = rx, ny = ry;
  2097. if (probe_relative) {
  2098. if (!position_is_reachable_by_probe(rx, ry)) return NAN; // The given position is in terms of the probe
  2099. nx -= (X_PROBE_OFFSET_FROM_EXTRUDER); // Get the nozzle position
  2100. ny -= (Y_PROBE_OFFSET_FROM_EXTRUDER);
  2101. }
  2102. else if (!position_is_reachable(nx, ny)) return NAN; // The given position is in terms of the nozzle
  2103. const float nz =
  2104. #if ENABLED(DELTA)
  2105. // Move below clip height or xy move will be aborted by do_blocking_move_to
  2106. MIN(current_position[Z_AXIS], delta_clip_start_height)
  2107. #else
  2108. current_position[Z_AXIS]
  2109. #endif
  2110. ;
  2111. const float old_feedrate_mm_s = feedrate_mm_s;
  2112. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  2113. // Move the probe to the starting XYZ
  2114. do_blocking_move_to(nx, ny, nz);
  2115. float measured_z = NAN;
  2116. if (!DEPLOY_PROBE()) {
  2117. measured_z = run_z_probe() + zprobe_zoffset;
  2118. const bool big_raise = raise_after == PROBE_PT_BIG_RAISE;
  2119. if (big_raise || raise_after == PROBE_PT_RAISE)
  2120. do_blocking_move_to_z(current_position[Z_AXIS] + (big_raise ? 25 : Z_CLEARANCE_BETWEEN_PROBES), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2121. else if (raise_after == PROBE_PT_STOW)
  2122. if (STOW_PROBE()) measured_z = NAN;
  2123. }
  2124. if (verbose_level > 2) {
  2125. SERIAL_PROTOCOLPGM("Bed X: ");
  2126. SERIAL_PROTOCOL_F(LOGICAL_X_POSITION(rx), 3);
  2127. SERIAL_PROTOCOLPGM(" Y: ");
  2128. SERIAL_PROTOCOL_F(LOGICAL_Y_POSITION(ry), 3);
  2129. SERIAL_PROTOCOLPGM(" Z: ");
  2130. SERIAL_PROTOCOL_F(measured_z, 3);
  2131. SERIAL_EOL();
  2132. }
  2133. feedrate_mm_s = old_feedrate_mm_s;
  2134. if (isnan(measured_z)) {
  2135. LCD_MESSAGEPGM(MSG_ERR_PROBING_FAILED);
  2136. SERIAL_ERROR_START();
  2137. SERIAL_ERRORLNPGM(MSG_ERR_PROBING_FAILED);
  2138. }
  2139. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2140. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  2141. #endif
  2142. return measured_z;
  2143. }
  2144. #endif // HAS_BED_PROBE
  2145. #if HAS_LEVELING
  2146. bool leveling_is_valid() {
  2147. return
  2148. #if ENABLED(MESH_BED_LEVELING)
  2149. mbl.has_mesh()
  2150. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2151. !!bilinear_grid_spacing[X_AXIS]
  2152. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2153. ubl.mesh_is_valid()
  2154. #else // 3POINT, LINEAR
  2155. true
  2156. #endif
  2157. ;
  2158. }
  2159. /**
  2160. * Turn bed leveling on or off, fixing the current
  2161. * position as-needed.
  2162. *
  2163. * Disable: Current position = physical position
  2164. * Enable: Current position = "unleveled" physical position
  2165. */
  2166. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  2167. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2168. const bool can_change = (!enable || leveling_is_valid());
  2169. #else
  2170. constexpr bool can_change = true;
  2171. #endif
  2172. if (can_change && enable != planner.leveling_active) {
  2173. planner.synchronize();
  2174. #if ENABLED(MESH_BED_LEVELING)
  2175. if (!enable)
  2176. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2177. const bool enabling = enable && leveling_is_valid();
  2178. planner.leveling_active = enabling;
  2179. if (enabling) planner.unapply_leveling(current_position);
  2180. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2181. #if PLANNER_LEVELING
  2182. if (planner.leveling_active) { // leveling from on to off
  2183. // change unleveled current_position to physical current_position without moving steppers.
  2184. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2185. planner.leveling_active = false; // disable only AFTER calling apply_leveling
  2186. }
  2187. else { // leveling from off to on
  2188. planner.leveling_active = true; // enable BEFORE calling unapply_leveling, otherwise ignored
  2189. // change physical current_position to unleveled current_position without moving steppers.
  2190. planner.unapply_leveling(current_position);
  2191. }
  2192. #else
  2193. // UBL equivalents for apply/unapply_leveling
  2194. #if ENABLED(SKEW_CORRECTION)
  2195. float pos[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  2196. planner.skew(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS]);
  2197. #else
  2198. const float (&pos)[XYZE] = current_position;
  2199. #endif
  2200. if (planner.leveling_active) {
  2201. current_position[Z_AXIS] += ubl.get_z_correction(pos[X_AXIS], pos[Y_AXIS]);
  2202. planner.leveling_active = false;
  2203. }
  2204. else {
  2205. planner.leveling_active = true;
  2206. current_position[Z_AXIS] -= ubl.get_z_correction(pos[X_AXIS], pos[Y_AXIS]);
  2207. }
  2208. #endif
  2209. #else // ABL
  2210. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2211. // Force bilinear_z_offset to re-calculate next time
  2212. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2213. (void)bilinear_z_offset(reset);
  2214. #endif
  2215. // Enable or disable leveling compensation in the planner
  2216. planner.leveling_active = enable;
  2217. if (!enable)
  2218. // When disabling just get the current position from the steppers.
  2219. // This will yield the smallest error when first converted back to steps.
  2220. set_current_from_steppers_for_axis(
  2221. #if ABL_PLANAR
  2222. ALL_AXES
  2223. #else
  2224. Z_AXIS
  2225. #endif
  2226. );
  2227. else
  2228. // When enabling, remove compensation from the current position,
  2229. // so compensation will give the right stepper counts.
  2230. planner.unapply_leveling(current_position);
  2231. SYNC_PLAN_POSITION_KINEMATIC();
  2232. #endif // ABL
  2233. }
  2234. }
  2235. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2236. void set_z_fade_height(const float zfh, const bool do_report/*=true*/) {
  2237. if (planner.z_fade_height == zfh) return;
  2238. const bool leveling_was_active = planner.leveling_active;
  2239. set_bed_leveling_enabled(false);
  2240. planner.set_z_fade_height(zfh);
  2241. if (leveling_was_active) {
  2242. const float oldpos[] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  2243. set_bed_leveling_enabled(true);
  2244. if (do_report && memcmp(oldpos, current_position, sizeof(oldpos)))
  2245. report_current_position();
  2246. }
  2247. }
  2248. #endif // LEVELING_FADE_HEIGHT
  2249. /**
  2250. * Reset calibration results to zero.
  2251. */
  2252. void reset_bed_level() {
  2253. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2254. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2255. #endif
  2256. set_bed_leveling_enabled(false);
  2257. #if ENABLED(MESH_BED_LEVELING)
  2258. mbl.reset();
  2259. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2260. ubl.reset();
  2261. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2262. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2263. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2264. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2265. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2266. z_values[x][y] = NAN;
  2267. #elif ABL_PLANAR
  2268. planner.bed_level_matrix.set_to_identity();
  2269. #endif
  2270. }
  2271. #endif // HAS_LEVELING
  2272. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2273. /**
  2274. * Enable to produce output in JSON format suitable
  2275. * for SCAD or JavaScript mesh visualizers.
  2276. *
  2277. * Visualize meshes in OpenSCAD using the included script.
  2278. *
  2279. * buildroot/shared/scripts/MarlinMesh.scad
  2280. */
  2281. //#define SCAD_MESH_OUTPUT
  2282. /**
  2283. * Print calibration results for plotting or manual frame adjustment.
  2284. */
  2285. void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, const element_2d_fn fn) {
  2286. #ifndef SCAD_MESH_OUTPUT
  2287. for (uint8_t x = 0; x < sx; x++) {
  2288. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2289. SERIAL_PROTOCOLCHAR(' ');
  2290. SERIAL_PROTOCOL(int(x));
  2291. }
  2292. SERIAL_EOL();
  2293. #endif
  2294. #ifdef SCAD_MESH_OUTPUT
  2295. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2296. #endif
  2297. for (uint8_t y = 0; y < sy; y++) {
  2298. #ifdef SCAD_MESH_OUTPUT
  2299. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2300. #else
  2301. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2302. SERIAL_PROTOCOL(int(y));
  2303. #endif
  2304. for (uint8_t x = 0; x < sx; x++) {
  2305. SERIAL_PROTOCOLCHAR(' ');
  2306. const float offset = fn(x, y);
  2307. if (!isnan(offset)) {
  2308. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2309. SERIAL_PROTOCOL_F(offset, int(precision));
  2310. }
  2311. else {
  2312. #ifdef SCAD_MESH_OUTPUT
  2313. for (uint8_t i = 3; i < precision + 3; i++)
  2314. SERIAL_PROTOCOLCHAR(' ');
  2315. SERIAL_PROTOCOLPGM("NAN");
  2316. #else
  2317. for (uint8_t i = 0; i < precision + 3; i++)
  2318. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2319. #endif
  2320. }
  2321. #ifdef SCAD_MESH_OUTPUT
  2322. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2323. #endif
  2324. }
  2325. #ifdef SCAD_MESH_OUTPUT
  2326. SERIAL_PROTOCOLCHAR(' ');
  2327. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2328. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2329. #endif
  2330. SERIAL_EOL();
  2331. }
  2332. #ifdef SCAD_MESH_OUTPUT
  2333. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2334. #endif
  2335. SERIAL_EOL();
  2336. }
  2337. #endif
  2338. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2339. /**
  2340. * Extrapolate a single point from its neighbors
  2341. */
  2342. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2343. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2344. if (DEBUGGING(LEVELING)) {
  2345. SERIAL_ECHOPGM("Extrapolate [");
  2346. if (x < 10) SERIAL_CHAR(' ');
  2347. SERIAL_ECHO(int(x));
  2348. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2349. SERIAL_CHAR(' ');
  2350. if (y < 10) SERIAL_CHAR(' ');
  2351. SERIAL_ECHO(int(y));
  2352. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2353. SERIAL_CHAR(']');
  2354. }
  2355. #endif
  2356. if (!isnan(z_values[x][y])) {
  2357. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2358. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2359. #endif
  2360. return; // Don't overwrite good values.
  2361. }
  2362. SERIAL_EOL();
  2363. // Get X neighbors, Y neighbors, and XY neighbors
  2364. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2365. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2366. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2367. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2368. // Treat far unprobed points as zero, near as equal to far
  2369. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2370. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2371. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2372. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2373. // Take the average instead of the median
  2374. z_values[x][y] = (a + b + c) / 3.0;
  2375. // Median is robust (ignores outliers).
  2376. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2377. // : ((c < b) ? b : (a < c) ? a : c);
  2378. }
  2379. //Enable this if your SCARA uses 180° of total area
  2380. //#define EXTRAPOLATE_FROM_EDGE
  2381. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2382. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2383. #define HALF_IN_X
  2384. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2385. #define HALF_IN_Y
  2386. #endif
  2387. #endif
  2388. /**
  2389. * Fill in the unprobed points (corners of circular print surface)
  2390. * using linear extrapolation, away from the center.
  2391. */
  2392. static void extrapolate_unprobed_bed_level() {
  2393. #ifdef HALF_IN_X
  2394. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2395. #else
  2396. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2397. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2398. xlen = ctrx1;
  2399. #endif
  2400. #ifdef HALF_IN_Y
  2401. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2402. #else
  2403. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2404. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2405. ylen = ctry1;
  2406. #endif
  2407. for (uint8_t xo = 0; xo <= xlen; xo++)
  2408. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2409. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2410. #ifndef HALF_IN_X
  2411. const uint8_t x1 = ctrx1 - xo;
  2412. #endif
  2413. #ifndef HALF_IN_Y
  2414. const uint8_t y1 = ctry1 - yo;
  2415. #ifndef HALF_IN_X
  2416. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2417. #endif
  2418. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2419. #endif
  2420. #ifndef HALF_IN_X
  2421. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2422. #endif
  2423. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2424. }
  2425. }
  2426. static void print_bilinear_leveling_grid() {
  2427. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2428. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2429. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2430. );
  2431. }
  2432. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2433. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2434. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2435. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2436. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2437. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2438. int bilinear_grid_spacing_virt[2] = { 0 };
  2439. float bilinear_grid_factor_virt[2] = { 0 };
  2440. static void print_bilinear_leveling_grid_virt() {
  2441. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2442. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2443. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2444. );
  2445. }
  2446. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2447. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2448. uint8_t ep = 0, ip = 1;
  2449. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2450. if (x) {
  2451. ep = GRID_MAX_POINTS_X - 1;
  2452. ip = GRID_MAX_POINTS_X - 2;
  2453. }
  2454. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2455. return LINEAR_EXTRAPOLATION(
  2456. z_values[ep][y - 1],
  2457. z_values[ip][y - 1]
  2458. );
  2459. else
  2460. return LINEAR_EXTRAPOLATION(
  2461. bed_level_virt_coord(ep + 1, y),
  2462. bed_level_virt_coord(ip + 1, y)
  2463. );
  2464. }
  2465. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2466. if (y) {
  2467. ep = GRID_MAX_POINTS_Y - 1;
  2468. ip = GRID_MAX_POINTS_Y - 2;
  2469. }
  2470. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2471. return LINEAR_EXTRAPOLATION(
  2472. z_values[x - 1][ep],
  2473. z_values[x - 1][ip]
  2474. );
  2475. else
  2476. return LINEAR_EXTRAPOLATION(
  2477. bed_level_virt_coord(x, ep + 1),
  2478. bed_level_virt_coord(x, ip + 1)
  2479. );
  2480. }
  2481. return z_values[x - 1][y - 1];
  2482. }
  2483. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2484. return (
  2485. p[i-1] * -t * sq(1 - t)
  2486. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2487. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2488. - p[i+2] * sq(t) * (1 - t)
  2489. ) * 0.5;
  2490. }
  2491. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2492. float row[4], column[4];
  2493. for (uint8_t i = 0; i < 4; i++) {
  2494. for (uint8_t j = 0; j < 4; j++) {
  2495. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2496. }
  2497. row[i] = bed_level_virt_cmr(column, 1, ty);
  2498. }
  2499. return bed_level_virt_cmr(row, 1, tx);
  2500. }
  2501. void bed_level_virt_interpolate() {
  2502. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2503. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2504. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2505. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2506. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2507. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2508. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2509. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2510. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2511. continue;
  2512. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2513. bed_level_virt_2cmr(
  2514. x + 1,
  2515. y + 1,
  2516. (float)tx / (BILINEAR_SUBDIVISIONS),
  2517. (float)ty / (BILINEAR_SUBDIVISIONS)
  2518. );
  2519. }
  2520. }
  2521. #endif // ABL_BILINEAR_SUBDIVISION
  2522. // Refresh after other values have been updated
  2523. void refresh_bed_level() {
  2524. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2525. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2526. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2527. bed_level_virt_interpolate();
  2528. #endif
  2529. }
  2530. #endif // AUTO_BED_LEVELING_BILINEAR
  2531. #if ENABLED(SENSORLESS_HOMING)
  2532. /**
  2533. * Set sensorless homing if the axis has it, accounting for Core Kinematics.
  2534. */
  2535. void sensorless_homing_per_axis(const AxisEnum axis, const bool enable=true) {
  2536. switch (axis) {
  2537. #if X_SENSORLESS
  2538. case X_AXIS:
  2539. tmc_sensorless_homing(stepperX, enable);
  2540. #if CORE_IS_XY && Y_SENSORLESS
  2541. tmc_sensorless_homing(stepperY, enable);
  2542. #elif CORE_IS_XZ && Z_SENSORLESS
  2543. tmc_sensorless_homing(stepperZ, enable);
  2544. #endif
  2545. break;
  2546. #endif
  2547. #if Y_SENSORLESS
  2548. case Y_AXIS:
  2549. tmc_sensorless_homing(stepperY, enable);
  2550. #if CORE_IS_XY && X_SENSORLESS
  2551. tmc_sensorless_homing(stepperX, enable);
  2552. #elif CORE_IS_YZ && Z_SENSORLESS
  2553. tmc_sensorless_homing(stepperZ, enable);
  2554. #endif
  2555. break;
  2556. #endif
  2557. #if Z_SENSORLESS
  2558. case Z_AXIS:
  2559. tmc_sensorless_homing(stepperZ, enable);
  2560. #if CORE_IS_XZ && X_SENSORLESS
  2561. tmc_sensorless_homing(stepperX, enable);
  2562. #elif CORE_IS_YZ && Y_SENSORLESS
  2563. tmc_sensorless_homing(stepperY, enable);
  2564. #endif
  2565. break;
  2566. #endif
  2567. default: break;
  2568. }
  2569. }
  2570. #endif // SENSORLESS_HOMING
  2571. /**
  2572. * Home an individual linear axis
  2573. */
  2574. static void do_homing_move(const AxisEnum axis, const float distance, const float fr_mm_s=0) {
  2575. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2576. if (DEBUGGING(LEVELING)) {
  2577. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2578. SERIAL_ECHOPAIR(", ", distance);
  2579. SERIAL_ECHOPGM(", ");
  2580. if (fr_mm_s)
  2581. SERIAL_ECHO(fr_mm_s);
  2582. else {
  2583. SERIAL_ECHOPAIR("[", homing_feedrate(axis));
  2584. SERIAL_CHAR(']');
  2585. }
  2586. SERIAL_ECHOLNPGM(")");
  2587. }
  2588. #endif
  2589. #if HOMING_Z_WITH_PROBE && HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  2590. // Wait for bed to heat back up between probing points
  2591. if (axis == Z_AXIS && distance < 0 && thermalManager.isHeatingBed()) {
  2592. serialprintPGM(msg_wait_for_bed_heating);
  2593. LCD_MESSAGEPGM(MSG_BED_HEATING);
  2594. while (thermalManager.isHeatingBed()) safe_delay(200);
  2595. lcd_reset_status();
  2596. }
  2597. #endif
  2598. // Only do some things when moving towards an endstop
  2599. const int8_t axis_home_dir =
  2600. #if ENABLED(DUAL_X_CARRIAGE)
  2601. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2602. #endif
  2603. home_dir(axis);
  2604. const bool is_home_dir = (axis_home_dir > 0) == (distance > 0);
  2605. if (is_home_dir) {
  2606. #if HOMING_Z_WITH_PROBE && QUIET_PROBING
  2607. if (axis == Z_AXIS) probing_pause(true);
  2608. #endif
  2609. // Disable stealthChop if used. Enable diag1 pin on driver.
  2610. #if ENABLED(SENSORLESS_HOMING)
  2611. sensorless_homing_per_axis(axis);
  2612. #endif
  2613. }
  2614. // Tell the planner the axis is at 0
  2615. current_position[axis] = 0;
  2616. // Do the move, which is required to hit an endstop
  2617. #if IS_SCARA
  2618. SYNC_PLAN_POSITION_KINEMATIC();
  2619. current_position[axis] = distance;
  2620. inverse_kinematics(current_position);
  2621. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2622. #elif ENABLED(HANGPRINTER) // TODO: Hangprinter homing is not finished (Jan 7, 2018)
  2623. SYNC_PLAN_POSITION_KINEMATIC();
  2624. current_position[axis] = distance;
  2625. inverse_kinematics(current_position);
  2626. planner.buffer_line(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2627. #else
  2628. sync_plan_position();
  2629. current_position[axis] = distance; // Set delta/cartesian axes directly
  2630. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2631. #endif
  2632. planner.synchronize();
  2633. if (is_home_dir) {
  2634. #if HOMING_Z_WITH_PROBE && QUIET_PROBING
  2635. if (axis == Z_AXIS) probing_pause(false);
  2636. #endif
  2637. endstops.validate_homing_move();
  2638. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2639. #if ENABLED(SENSORLESS_HOMING)
  2640. sensorless_homing_per_axis(axis, false);
  2641. #endif
  2642. }
  2643. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2644. if (DEBUGGING(LEVELING)) {
  2645. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2646. SERIAL_CHAR(')');
  2647. SERIAL_EOL();
  2648. }
  2649. #endif
  2650. }
  2651. /**
  2652. * Home an individual "raw axis" to its endstop.
  2653. * This applies to XYZ on Cartesian and Core robots, and
  2654. * to the individual ABC steppers on DELTA and SCARA.
  2655. *
  2656. * At the end of the procedure the axis is marked as
  2657. * homed and the current position of that axis is updated.
  2658. * Kinematic robots should wait till all axes are homed
  2659. * before updating the current position.
  2660. */
  2661. static void homeaxis(const AxisEnum axis) {
  2662. #if IS_SCARA
  2663. // Only Z homing (with probe) is permitted
  2664. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2665. #else
  2666. #define CAN_HOME(A) \
  2667. (axis == _AXIS(A) && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2668. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2669. #endif
  2670. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2671. if (DEBUGGING(LEVELING)) {
  2672. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2673. SERIAL_CHAR(')');
  2674. SERIAL_EOL();
  2675. }
  2676. #endif
  2677. const int axis_home_dir = (
  2678. #if ENABLED(DUAL_X_CARRIAGE)
  2679. axis == X_AXIS ? x_home_dir(active_extruder) :
  2680. #endif
  2681. home_dir(axis)
  2682. );
  2683. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2684. #if HOMING_Z_WITH_PROBE
  2685. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2686. #endif
  2687. // Set flags for X, Y, Z motor locking
  2688. #if ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  2689. switch (axis) {
  2690. #if ENABLED(X_DUAL_ENDSTOPS)
  2691. case X_AXIS:
  2692. #endif
  2693. #if ENABLED(Y_DUAL_ENDSTOPS)
  2694. case Y_AXIS:
  2695. #endif
  2696. #if ENABLED(Z_DUAL_ENDSTOPS)
  2697. case Z_AXIS:
  2698. #endif
  2699. stepper.set_homing_dual_axis(true);
  2700. default: break;
  2701. }
  2702. #endif
  2703. // Fast move towards endstop until triggered
  2704. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2705. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2706. #endif
  2707. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2708. // BLTOUCH needs to be deployed every time
  2709. if (axis == Z_AXIS && set_bltouch_deployed(true)) return;
  2710. #endif
  2711. do_homing_move(axis, 1.5f * max_length(axis) * axis_home_dir);
  2712. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2713. // BLTOUCH needs to be stowed after trigger to rearm itself
  2714. if (axis == Z_AXIS) set_bltouch_deployed(false);
  2715. #endif
  2716. // When homing Z with probe respect probe clearance
  2717. const float bump = axis_home_dir * (
  2718. #if HOMING_Z_WITH_PROBE
  2719. (axis == Z_AXIS && (Z_HOME_BUMP_MM)) ? MAX(Z_CLEARANCE_BETWEEN_PROBES, Z_HOME_BUMP_MM) :
  2720. #endif
  2721. home_bump_mm(axis)
  2722. );
  2723. // If a second homing move is configured...
  2724. if (bump) {
  2725. // Move away from the endstop by the axis HOME_BUMP_MM
  2726. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2727. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2728. #endif
  2729. do_homing_move(axis, -bump
  2730. #if HOMING_Z_WITH_PROBE
  2731. , axis == Z_AXIS ? MMM_TO_MMS(Z_PROBE_SPEED_FAST) : 0.00
  2732. #endif
  2733. );
  2734. // Slow move towards endstop until triggered
  2735. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2736. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2737. #endif
  2738. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2739. // BLTOUCH needs to be deployed every time
  2740. if (axis == Z_AXIS && set_bltouch_deployed(true)) return;
  2741. #endif
  2742. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2743. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2744. // BLTOUCH needs to be stowed after trigger to rearm itself
  2745. if (axis == Z_AXIS) set_bltouch_deployed(false);
  2746. #endif
  2747. }
  2748. /**
  2749. * Home axes that have dual endstops... differently
  2750. */
  2751. #if ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  2752. const bool pos_dir = axis_home_dir > 0;
  2753. #if ENABLED(X_DUAL_ENDSTOPS)
  2754. if (axis == X_AXIS) {
  2755. const float adj = ABS(endstops.x_endstop_adj);
  2756. if (adj) {
  2757. if (pos_dir ? (endstops.x_endstop_adj > 0) : (endstops.x_endstop_adj < 0)) stepper.set_x_lock(true); else stepper.set_x2_lock(true);
  2758. do_homing_move(axis, pos_dir ? -adj : adj);
  2759. stepper.set_x_lock(false);
  2760. stepper.set_x2_lock(false);
  2761. }
  2762. }
  2763. #endif
  2764. #if ENABLED(Y_DUAL_ENDSTOPS)
  2765. if (axis == Y_AXIS) {
  2766. const float adj = ABS(endstops.y_endstop_adj);
  2767. if (adj) {
  2768. if (pos_dir ? (endstops.y_endstop_adj > 0) : (endstops.y_endstop_adj < 0)) stepper.set_y_lock(true); else stepper.set_y2_lock(true);
  2769. do_homing_move(axis, pos_dir ? -adj : adj);
  2770. stepper.set_y_lock(false);
  2771. stepper.set_y2_lock(false);
  2772. }
  2773. }
  2774. #endif
  2775. #if ENABLED(Z_DUAL_ENDSTOPS)
  2776. if (axis == Z_AXIS) {
  2777. const float adj = ABS(endstops.z_endstop_adj);
  2778. if (adj) {
  2779. if (pos_dir ? (endstops.z_endstop_adj > 0) : (endstops.z_endstop_adj < 0)) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2780. do_homing_move(axis, pos_dir ? -adj : adj);
  2781. stepper.set_z_lock(false);
  2782. stepper.set_z2_lock(false);
  2783. }
  2784. }
  2785. #endif
  2786. stepper.set_homing_dual_axis(false);
  2787. #endif
  2788. #if IS_SCARA
  2789. set_axis_is_at_home(axis);
  2790. SYNC_PLAN_POSITION_KINEMATIC();
  2791. #elif ENABLED(DELTA)
  2792. // Delta has already moved all three towers up in G28
  2793. // so here it re-homes each tower in turn.
  2794. // Delta homing treats the axes as normal linear axes.
  2795. // retrace by the amount specified in delta_endstop_adj + additional dist in order to have minimum steps
  2796. if (delta_endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2797. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2798. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("delta_endstop_adj:");
  2799. #endif
  2800. do_homing_move(axis, delta_endstop_adj[axis] - (MIN_STEPS_PER_SEGMENT + 1) * planner.steps_to_mm[axis] * Z_HOME_DIR);
  2801. }
  2802. #else
  2803. // For cartesian/core machines,
  2804. // set the axis to its home position
  2805. set_axis_is_at_home(axis);
  2806. sync_plan_position();
  2807. destination[axis] = current_position[axis];
  2808. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2809. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2810. #endif
  2811. #endif
  2812. // Put away the Z probe
  2813. #if HOMING_Z_WITH_PROBE
  2814. if (axis == Z_AXIS && STOW_PROBE()) return;
  2815. #endif
  2816. // Clear retracted status if homing the Z axis
  2817. #if ENABLED(FWRETRACT)
  2818. if (axis == Z_AXIS) fwretract.hop_amount = 0.0;
  2819. #endif
  2820. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2821. if (DEBUGGING(LEVELING)) {
  2822. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2823. SERIAL_CHAR(')');
  2824. SERIAL_EOL();
  2825. }
  2826. #endif
  2827. } // homeaxis()
  2828. #if ENABLED(MIXING_EXTRUDER)
  2829. void normalize_mix() {
  2830. float mix_total = 0.0;
  2831. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += mixing_factor[i];
  2832. // Scale all values if they don't add up to ~1.0
  2833. if (!NEAR(mix_total, 1.0)) {
  2834. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2835. const float inverse_sum = RECIPROCAL(mix_total);
  2836. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= inverse_sum;
  2837. }
  2838. }
  2839. #if ENABLED(DIRECT_MIXING_IN_G1)
  2840. // Get mixing parameters from the GCode
  2841. // The total "must" be 1.0 (but it will be normalized)
  2842. // If no mix factors are given, the old mix is preserved
  2843. void gcode_get_mix() {
  2844. const char mixing_codes[] = { 'A', 'B'
  2845. #if MIXING_STEPPERS > 2
  2846. , 'C'
  2847. #if MIXING_STEPPERS > 3
  2848. , 'D'
  2849. #if MIXING_STEPPERS > 4
  2850. , 'H'
  2851. #if MIXING_STEPPERS > 5
  2852. , 'I'
  2853. #endif // MIXING_STEPPERS > 5
  2854. #endif // MIXING_STEPPERS > 4
  2855. #endif // MIXING_STEPPERS > 3
  2856. #endif // MIXING_STEPPERS > 2
  2857. };
  2858. byte mix_bits = 0;
  2859. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2860. if (parser.seenval(mixing_codes[i])) {
  2861. SBI(mix_bits, i);
  2862. mixing_factor[i] = MAX(parser.value_float(), 0.0);
  2863. }
  2864. }
  2865. // If any mixing factors were included, clear the rest
  2866. // If none were included, preserve the last mix
  2867. if (mix_bits) {
  2868. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2869. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2870. normalize_mix();
  2871. }
  2872. }
  2873. #endif
  2874. #endif
  2875. /**
  2876. * ***************************************************************************
  2877. * ***************************** G-CODE HANDLING *****************************
  2878. * ***************************************************************************
  2879. */
  2880. /**
  2881. * Set XYZE destination and feedrate from the current GCode command
  2882. *
  2883. * - Set destination from included axis codes
  2884. * - Set to current for missing axis codes
  2885. * - Set the feedrate, if included
  2886. */
  2887. void gcode_get_destination() {
  2888. LOOP_XYZE(i) {
  2889. if (parser.seen(axis_codes[i])) {
  2890. const float v = parser.value_axis_units((AxisEnum)i);
  2891. destination[i] = (axis_relative_modes[i] || relative_mode)
  2892. ? current_position[i] + v
  2893. : (i == E_CART) ? v : LOGICAL_TO_NATIVE(v, i);
  2894. }
  2895. else
  2896. destination[i] = current_position[i];
  2897. }
  2898. if (parser.linearval('F') > 0)
  2899. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  2900. #if ENABLED(PRINTCOUNTER)
  2901. if (!DEBUGGING(DRYRUN))
  2902. print_job_timer.incFilamentUsed(destination[E_CART] - current_position[E_CART]);
  2903. #endif
  2904. // Get ABCDHI mixing factors
  2905. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2906. gcode_get_mix();
  2907. #endif
  2908. }
  2909. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2910. /**
  2911. * Output a "busy" message at regular intervals
  2912. * while the machine is not accepting commands.
  2913. */
  2914. void host_keepalive() {
  2915. const millis_t ms = millis();
  2916. if (!suspend_auto_report && host_keepalive_interval && busy_state != NOT_BUSY) {
  2917. if (PENDING(ms, next_busy_signal_ms)) return;
  2918. switch (busy_state) {
  2919. case IN_HANDLER:
  2920. case IN_PROCESS:
  2921. SERIAL_ECHO_START();
  2922. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2923. break;
  2924. case PAUSED_FOR_USER:
  2925. SERIAL_ECHO_START();
  2926. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2927. break;
  2928. case PAUSED_FOR_INPUT:
  2929. SERIAL_ECHO_START();
  2930. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2931. break;
  2932. default:
  2933. break;
  2934. }
  2935. }
  2936. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2937. }
  2938. #endif // HOST_KEEPALIVE_FEATURE
  2939. /**************************************************
  2940. ***************** GCode Handlers *****************
  2941. **************************************************/
  2942. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  2943. #define G0_G1_CONDITION !axis_unhomed_error(parser.seen('X'), parser.seen('Y'), parser.seen('Z'))
  2944. #else
  2945. #define G0_G1_CONDITION true
  2946. #endif
  2947. /**
  2948. * G0, G1: Coordinated movement of X Y Z E axes
  2949. */
  2950. inline void gcode_G0_G1(
  2951. #if IS_SCARA
  2952. bool fast_move=false
  2953. #endif
  2954. ) {
  2955. if (IsRunning() && G0_G1_CONDITION) {
  2956. gcode_get_destination(); // For X Y Z E F
  2957. #if ENABLED(FWRETRACT)
  2958. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) {
  2959. // When M209 Autoretract is enabled, convert E-only moves to firmware retract/prime moves
  2960. if (fwretract.autoretract_enabled && parser.seen('E') && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z'))) {
  2961. const float echange = destination[E_CART] - current_position[E_CART];
  2962. // Is this a retract or prime move?
  2963. if (WITHIN(ABS(echange), MIN_AUTORETRACT, MAX_AUTORETRACT) && fwretract.retracted[active_extruder] == (echange > 0.0)) {
  2964. current_position[E_CART] = destination[E_CART]; // Hide a G1-based retract/prime from calculations
  2965. sync_plan_position_e(); // AND from the planner
  2966. return fwretract.retract(echange < 0.0); // Firmware-based retract/prime (double-retract ignored)
  2967. }
  2968. }
  2969. }
  2970. #endif // FWRETRACT
  2971. #if IS_SCARA
  2972. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2973. #else
  2974. prepare_move_to_destination();
  2975. #endif
  2976. #if ENABLED(NANODLP_Z_SYNC)
  2977. #if ENABLED(NANODLP_ALL_AXIS)
  2978. #define _MOVE_SYNC parser.seenval('X') || parser.seenval('Y') || parser.seenval('Z') // For any move wait and output sync message
  2979. #else
  2980. #define _MOVE_SYNC parser.seenval('Z') // Only for Z move
  2981. #endif
  2982. if (_MOVE_SYNC) {
  2983. planner.synchronize();
  2984. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  2985. }
  2986. #endif
  2987. }
  2988. }
  2989. /**
  2990. * G2: Clockwise Arc
  2991. * G3: Counterclockwise Arc
  2992. *
  2993. * This command has two forms: IJ-form and R-form.
  2994. *
  2995. * - I specifies an X offset. J specifies a Y offset.
  2996. * At least one of the IJ parameters is required.
  2997. * X and Y can be omitted to do a complete circle.
  2998. * The given XY is not error-checked. The arc ends
  2999. * based on the angle of the destination.
  3000. * Mixing I or J with R will throw an error.
  3001. *
  3002. * - R specifies the radius. X or Y is required.
  3003. * Omitting both X and Y will throw an error.
  3004. * X or Y must differ from the current XY.
  3005. * Mixing R with I or J will throw an error.
  3006. *
  3007. * - P specifies the number of full circles to do
  3008. * before the specified arc move.
  3009. *
  3010. * Examples:
  3011. *
  3012. * G2 I10 ; CW circle centered at X+10
  3013. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  3014. */
  3015. #if ENABLED(ARC_SUPPORT)
  3016. inline void gcode_G2_G3(const bool clockwise) {
  3017. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3018. if (axis_unhomed_error()) return;
  3019. #endif
  3020. if (IsRunning()) {
  3021. #if ENABLED(SF_ARC_FIX)
  3022. const bool relative_mode_backup = relative_mode;
  3023. relative_mode = true;
  3024. #endif
  3025. gcode_get_destination();
  3026. #if ENABLED(SF_ARC_FIX)
  3027. relative_mode = relative_mode_backup;
  3028. #endif
  3029. float arc_offset[2] = { 0, 0 };
  3030. if (parser.seenval('R')) {
  3031. const float r = parser.value_linear_units(),
  3032. p1 = current_position[X_AXIS], q1 = current_position[Y_AXIS],
  3033. p2 = destination[X_AXIS], q2 = destination[Y_AXIS];
  3034. if (r && (p2 != p1 || q2 != q1)) {
  3035. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  3036. dx = p2 - p1, dy = q2 - q1, // X and Y differences
  3037. d = HYPOT(dx, dy), // Linear distance between the points
  3038. h = SQRT(sq(r) - sq(d * 0.5f)), // Distance to the arc pivot-point
  3039. mx = (p1 + p2) * 0.5f, my = (q1 + q2) * 0.5f, // Point between the two points
  3040. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  3041. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  3042. arc_offset[0] = cx - p1;
  3043. arc_offset[1] = cy - q1;
  3044. }
  3045. }
  3046. else {
  3047. if (parser.seenval('I')) arc_offset[0] = parser.value_linear_units();
  3048. if (parser.seenval('J')) arc_offset[1] = parser.value_linear_units();
  3049. }
  3050. if (arc_offset[0] || arc_offset[1]) {
  3051. #if ENABLED(ARC_P_CIRCLES)
  3052. // P indicates number of circles to do
  3053. int8_t circles_to_do = parser.byteval('P');
  3054. if (!WITHIN(circles_to_do, 0, 100)) {
  3055. SERIAL_ERROR_START();
  3056. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  3057. }
  3058. while (circles_to_do--)
  3059. plan_arc(current_position, arc_offset, clockwise);
  3060. #endif
  3061. // Send the arc to the planner
  3062. plan_arc(destination, arc_offset, clockwise);
  3063. }
  3064. else {
  3065. // Bad arguments
  3066. SERIAL_ERROR_START();
  3067. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  3068. }
  3069. }
  3070. }
  3071. #endif // ARC_SUPPORT
  3072. void dwell(millis_t time) {
  3073. time += millis();
  3074. while (PENDING(millis(), time)) idle();
  3075. }
  3076. /**
  3077. * G4: Dwell S<seconds> or P<milliseconds>
  3078. */
  3079. inline void gcode_G4() {
  3080. millis_t dwell_ms = 0;
  3081. if (parser.seenval('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  3082. if (parser.seenval('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  3083. planner.synchronize();
  3084. #if ENABLED(NANODLP_Z_SYNC)
  3085. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  3086. #endif
  3087. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  3088. dwell(dwell_ms);
  3089. }
  3090. #if ENABLED(BEZIER_CURVE_SUPPORT)
  3091. /**
  3092. * Parameters interpreted according to:
  3093. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  3094. * However I, J omission is not supported at this point; all
  3095. * parameters can be omitted and default to zero.
  3096. */
  3097. /**
  3098. * G5: Cubic B-spline
  3099. */
  3100. inline void gcode_G5() {
  3101. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3102. if (axis_unhomed_error()) return;
  3103. #endif
  3104. if (IsRunning()) {
  3105. #if ENABLED(CNC_WORKSPACE_PLANES)
  3106. if (workspace_plane != PLANE_XY) {
  3107. SERIAL_ERROR_START();
  3108. SERIAL_ERRORLNPGM(MSG_ERR_BAD_PLANE_MODE);
  3109. return;
  3110. }
  3111. #endif
  3112. gcode_get_destination();
  3113. const float offset[] = {
  3114. parser.linearval('I'),
  3115. parser.linearval('J'),
  3116. parser.linearval('P'),
  3117. parser.linearval('Q')
  3118. };
  3119. plan_cubic_move(destination, offset);
  3120. }
  3121. }
  3122. #endif // BEZIER_CURVE_SUPPORT
  3123. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  3124. /**
  3125. * G6 implementation for Hangprinter based on
  3126. * http://reprap.org/wiki/GCodes#G6:_Direct_Stepper_Move
  3127. * Accessed Jan 8, 2018
  3128. *
  3129. * G6 is used frequently to tighten lines with Hangprinter, so Hangprinter default is relative moves.
  3130. * Hangprinter uses switches
  3131. * S1 for absolute moves
  3132. * S2 for saving recording new line length after unregistered move
  3133. * (typically used while tuning LINE_BUILDUP_COMPENSATION_FEATURE parameters)
  3134. */
  3135. /**
  3136. * G6: Direct Stepper Move
  3137. */
  3138. inline void gcode_G6() {
  3139. bool count_it = false;
  3140. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3141. if (axis_unhomed_error()) return;
  3142. #endif
  3143. if (IsRunning()) {
  3144. float go[MOV_AXIS] = { 0.0 },
  3145. tmp_fr_mm_s = 0.0;
  3146. LOOP_MOV_AXIS(i)
  3147. if (parser.seen(RAW_AXIS_CODES(i)))
  3148. go[i] = parser.value_axis_units((AxisEnum)i);
  3149. #if ENABLED(HANGPRINTER)
  3150. #define GO_SRC line_lengths
  3151. #elif ENABLED(DELTA)
  3152. #define GO_SRC delta
  3153. #else
  3154. #define GO_SRC current_position
  3155. #endif
  3156. if (
  3157. #if ENABLED(HANGPRINTER) // Sending R to another machine is the same as not sending S1 to Hangprinter
  3158. parser.byteval('S') != 2
  3159. #else
  3160. parser.seen('R')
  3161. #endif
  3162. )
  3163. LOOP_MOV_AXIS(i) go[i] += GO_SRC[i];
  3164. else
  3165. LOOP_MOV_AXIS(i) if (!parser.seen(RAW_AXIS_CODES(i))) go[i] += GO_SRC[i];
  3166. tmp_fr_mm_s = parser.linearval('F') > 0.0 ? MMM_TO_MMS(parser.value_feedrate()) : feedrate_mm_s;
  3167. #if ENABLED(HANGPRINTER)
  3168. if (parser.byteval('S') == 2) {
  3169. LOOP_MOV_AXIS(i) line_lengths[i] = go[i];
  3170. count_it = true;
  3171. }
  3172. #endif
  3173. planner.buffer_segment(go[A_AXIS], go[B_AXIS], go[C_AXIS]
  3174. #if ENABLED(HANGPRINTER)
  3175. , go[D_AXIS]
  3176. #endif
  3177. , current_position[E_CART], tmp_fr_mm_s, active_extruder, 0.0, count_it
  3178. );
  3179. }
  3180. }
  3181. #endif
  3182. #if ENABLED(FWRETRACT)
  3183. /**
  3184. * G10 - Retract filament according to settings of M207
  3185. */
  3186. inline void gcode_G10() {
  3187. #if EXTRUDERS > 1
  3188. const bool rs = parser.boolval('S');
  3189. #endif
  3190. fwretract.retract(true
  3191. #if EXTRUDERS > 1
  3192. , rs
  3193. #endif
  3194. );
  3195. }
  3196. /**
  3197. * G11 - Recover filament according to settings of M208
  3198. */
  3199. inline void gcode_G11() { fwretract.retract(false); }
  3200. #endif // FWRETRACT
  3201. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  3202. /**
  3203. * G12: Clean the nozzle
  3204. */
  3205. inline void gcode_G12() {
  3206. // Don't allow nozzle cleaning without homing first
  3207. if (axis_unhomed_error()) return;
  3208. const uint8_t pattern = parser.ushortval('P', 0),
  3209. strokes = parser.ushortval('S', NOZZLE_CLEAN_STROKES),
  3210. objects = parser.ushortval('T', NOZZLE_CLEAN_TRIANGLES);
  3211. const float radius = parser.floatval('R', NOZZLE_CLEAN_CIRCLE_RADIUS);
  3212. Nozzle::clean(pattern, strokes, radius, objects);
  3213. }
  3214. #endif
  3215. #if ENABLED(CNC_WORKSPACE_PLANES)
  3216. inline void report_workspace_plane() {
  3217. SERIAL_ECHO_START();
  3218. SERIAL_ECHOPGM("Workspace Plane ");
  3219. serialprintPGM(
  3220. workspace_plane == PLANE_YZ ? PSTR("YZ\n") :
  3221. workspace_plane == PLANE_ZX ? PSTR("ZX\n") :
  3222. PSTR("XY\n")
  3223. );
  3224. }
  3225. inline void set_workspace_plane(const WorkspacePlane plane) {
  3226. workspace_plane = plane;
  3227. if (DEBUGGING(INFO)) report_workspace_plane();
  3228. }
  3229. /**
  3230. * G17: Select Plane XY
  3231. * G18: Select Plane ZX
  3232. * G19: Select Plane YZ
  3233. */
  3234. inline void gcode_G17() { set_workspace_plane(PLANE_XY); }
  3235. inline void gcode_G18() { set_workspace_plane(PLANE_ZX); }
  3236. inline void gcode_G19() { set_workspace_plane(PLANE_YZ); }
  3237. #endif // CNC_WORKSPACE_PLANES
  3238. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  3239. /**
  3240. * Select a coordinate system and update the workspace offset.
  3241. * System index -1 is used to specify machine-native.
  3242. */
  3243. bool select_coordinate_system(const int8_t _new) {
  3244. if (active_coordinate_system == _new) return false;
  3245. float old_offset[XYZ] = { 0 }, new_offset[XYZ] = { 0 };
  3246. if (WITHIN(active_coordinate_system, 0, MAX_COORDINATE_SYSTEMS - 1))
  3247. COPY(old_offset, coordinate_system[active_coordinate_system]);
  3248. if (WITHIN(_new, 0, MAX_COORDINATE_SYSTEMS - 1))
  3249. COPY(new_offset, coordinate_system[_new]);
  3250. active_coordinate_system = _new;
  3251. LOOP_XYZ(i) {
  3252. const float diff = new_offset[i] - old_offset[i];
  3253. if (diff) {
  3254. position_shift[i] += diff;
  3255. update_software_endstops((AxisEnum)i);
  3256. }
  3257. }
  3258. return true;
  3259. }
  3260. /**
  3261. * G53: Apply native workspace to the current move
  3262. *
  3263. * In CNC G-code G53 is a modifier.
  3264. * It precedes a movement command (or other modifiers) on the same line.
  3265. * This is the first command to use parser.chain() to make this possible.
  3266. *
  3267. * Marlin also uses G53 on a line by itself to go back to native space.
  3268. */
  3269. inline void gcode_G53() {
  3270. const int8_t _system = active_coordinate_system;
  3271. active_coordinate_system = -1;
  3272. if (parser.chain()) { // If this command has more following...
  3273. process_parsed_command();
  3274. active_coordinate_system = _system;
  3275. }
  3276. }
  3277. /**
  3278. * G54-G59.3: Select a new workspace
  3279. *
  3280. * A workspace is an XYZ offset to the machine native space.
  3281. * All workspaces default to 0,0,0 at start, or with EEPROM
  3282. * support they may be restored from a previous session.
  3283. *
  3284. * G92 is used to set the current workspace's offset.
  3285. */
  3286. inline void gcode_G54_59(uint8_t subcode=0) {
  3287. const int8_t _space = parser.codenum - 54 + subcode;
  3288. if (select_coordinate_system(_space)) {
  3289. SERIAL_PROTOCOLLNPAIR("Select workspace ", _space);
  3290. report_current_position();
  3291. }
  3292. }
  3293. FORCE_INLINE void gcode_G54() { gcode_G54_59(); }
  3294. FORCE_INLINE void gcode_G55() { gcode_G54_59(); }
  3295. FORCE_INLINE void gcode_G56() { gcode_G54_59(); }
  3296. FORCE_INLINE void gcode_G57() { gcode_G54_59(); }
  3297. FORCE_INLINE void gcode_G58() { gcode_G54_59(); }
  3298. FORCE_INLINE void gcode_G59() { gcode_G54_59(parser.subcode); }
  3299. #endif
  3300. #if ENABLED(INCH_MODE_SUPPORT)
  3301. /**
  3302. * G20: Set input mode to inches
  3303. */
  3304. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  3305. /**
  3306. * G21: Set input mode to millimeters
  3307. */
  3308. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  3309. #endif
  3310. #if ENABLED(NOZZLE_PARK_FEATURE)
  3311. /**
  3312. * G27: Park the nozzle
  3313. */
  3314. inline void gcode_G27() {
  3315. // Don't allow nozzle parking without homing first
  3316. if (axis_unhomed_error()) return;
  3317. Nozzle::park(parser.ushortval('P'));
  3318. }
  3319. #endif // NOZZLE_PARK_FEATURE
  3320. #if ENABLED(QUICK_HOME)
  3321. static void quick_home_xy() {
  3322. // Pretend the current position is 0,0
  3323. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  3324. sync_plan_position();
  3325. const int x_axis_home_dir =
  3326. #if ENABLED(DUAL_X_CARRIAGE)
  3327. x_home_dir(active_extruder)
  3328. #else
  3329. home_dir(X_AXIS)
  3330. #endif
  3331. ;
  3332. const float mlx = max_length(X_AXIS),
  3333. mly = max_length(Y_AXIS),
  3334. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  3335. fr_mm_s = MIN(homing_feedrate(X_AXIS), homing_feedrate(Y_AXIS)) * SQRT(sq(mlratio) + 1.0);
  3336. #if ENABLED(SENSORLESS_HOMING)
  3337. sensorless_homing_per_axis(X_AXIS);
  3338. sensorless_homing_per_axis(Y_AXIS);
  3339. #endif
  3340. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  3341. endstops.validate_homing_move();
  3342. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  3343. #if ENABLED(SENSORLESS_HOMING)
  3344. sensorless_homing_per_axis(X_AXIS, false);
  3345. sensorless_homing_per_axis(Y_AXIS, false);
  3346. #endif
  3347. }
  3348. #endif // QUICK_HOME
  3349. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3350. void log_machine_info() {
  3351. SERIAL_ECHOPGM("Machine Type: ");
  3352. #if ENABLED(DELTA)
  3353. SERIAL_ECHOLNPGM("Delta");
  3354. #elif IS_SCARA
  3355. SERIAL_ECHOLNPGM("SCARA");
  3356. #elif IS_CORE
  3357. SERIAL_ECHOLNPGM("Core");
  3358. #else
  3359. SERIAL_ECHOLNPGM("Cartesian");
  3360. #endif
  3361. SERIAL_ECHOPGM("Probe: ");
  3362. #if ENABLED(PROBE_MANUALLY)
  3363. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  3364. #elif ENABLED(FIX_MOUNTED_PROBE)
  3365. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  3366. #elif ENABLED(BLTOUCH)
  3367. SERIAL_ECHOLNPGM("BLTOUCH");
  3368. #elif HAS_Z_SERVO_PROBE
  3369. SERIAL_ECHOLNPGM("SERVO PROBE");
  3370. #elif ENABLED(Z_PROBE_SLED)
  3371. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  3372. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  3373. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  3374. #else
  3375. SERIAL_ECHOLNPGM("NONE");
  3376. #endif
  3377. #if HAS_BED_PROBE
  3378. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  3379. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  3380. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  3381. #if X_PROBE_OFFSET_FROM_EXTRUDER > 0
  3382. SERIAL_ECHOPGM(" (Right");
  3383. #elif X_PROBE_OFFSET_FROM_EXTRUDER < 0
  3384. SERIAL_ECHOPGM(" (Left");
  3385. #elif Y_PROBE_OFFSET_FROM_EXTRUDER != 0
  3386. SERIAL_ECHOPGM(" (Middle");
  3387. #else
  3388. SERIAL_ECHOPGM(" (Aligned With");
  3389. #endif
  3390. #if Y_PROBE_OFFSET_FROM_EXTRUDER > 0
  3391. #if IS_SCARA
  3392. SERIAL_ECHOPGM("-Distal");
  3393. #else
  3394. SERIAL_ECHOPGM("-Back");
  3395. #endif
  3396. #elif Y_PROBE_OFFSET_FROM_EXTRUDER < 0
  3397. #if IS_SCARA
  3398. SERIAL_ECHOPGM("-Proximal");
  3399. #else
  3400. SERIAL_ECHOPGM("-Front");
  3401. #endif
  3402. #elif X_PROBE_OFFSET_FROM_EXTRUDER != 0
  3403. SERIAL_ECHOPGM("-Center");
  3404. #endif
  3405. if (zprobe_zoffset < 0)
  3406. SERIAL_ECHOPGM(" & Below");
  3407. else if (zprobe_zoffset > 0)
  3408. SERIAL_ECHOPGM(" & Above");
  3409. else
  3410. SERIAL_ECHOPGM(" & Same Z as");
  3411. SERIAL_ECHOLNPGM(" Nozzle)");
  3412. #endif
  3413. #if HAS_ABL
  3414. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  3415. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3416. SERIAL_ECHOPGM("LINEAR");
  3417. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3418. SERIAL_ECHOPGM("BILINEAR");
  3419. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3420. SERIAL_ECHOPGM("3POINT");
  3421. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3422. SERIAL_ECHOPGM("UBL");
  3423. #endif
  3424. if (planner.leveling_active) {
  3425. SERIAL_ECHOLNPGM(" (enabled)");
  3426. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3427. if (planner.z_fade_height)
  3428. SERIAL_ECHOLNPAIR("Z Fade: ", planner.z_fade_height);
  3429. #endif
  3430. #if ABL_PLANAR
  3431. const float diff[XYZ] = {
  3432. planner.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  3433. planner.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  3434. planner.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  3435. };
  3436. SERIAL_ECHOPGM("ABL Adjustment X");
  3437. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  3438. SERIAL_ECHO(diff[X_AXIS]);
  3439. SERIAL_ECHOPGM(" Y");
  3440. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  3441. SERIAL_ECHO(diff[Y_AXIS]);
  3442. SERIAL_ECHOPGM(" Z");
  3443. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  3444. SERIAL_ECHO(diff[Z_AXIS]);
  3445. #else
  3446. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3447. SERIAL_ECHOPGM("UBL Adjustment Z");
  3448. const float rz = ubl.get_z_correction(current_position[X_AXIS], current_position[Y_AXIS]);
  3449. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3450. SERIAL_ECHOPAIR("Bilinear Grid X", bilinear_start[X_AXIS]);
  3451. SERIAL_ECHOPAIR(" Y", bilinear_start[Y_AXIS]);
  3452. SERIAL_ECHOPAIR(" W", ABL_BG_SPACING(X_AXIS));
  3453. SERIAL_ECHOLNPAIR(" H", ABL_BG_SPACING(Y_AXIS));
  3454. SERIAL_ECHOPGM("ABL Adjustment Z");
  3455. const float rz = bilinear_z_offset(current_position);
  3456. #endif
  3457. SERIAL_ECHO(ftostr43sign(rz, '+'));
  3458. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3459. if (planner.z_fade_height) {
  3460. SERIAL_ECHOPAIR(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position[Z_AXIS]), '+'));
  3461. SERIAL_CHAR(')');
  3462. }
  3463. #endif
  3464. #endif
  3465. }
  3466. else
  3467. SERIAL_ECHOLNPGM(" (disabled)");
  3468. SERIAL_EOL();
  3469. #elif ENABLED(MESH_BED_LEVELING)
  3470. SERIAL_ECHOPGM("Mesh Bed Leveling");
  3471. if (planner.leveling_active) {
  3472. SERIAL_ECHOLNPGM(" (enabled)");
  3473. SERIAL_ECHOPAIR("MBL Adjustment Z", ftostr43sign(mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS]
  3474. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3475. , 1.0
  3476. #endif
  3477. ), '+'));
  3478. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3479. if (planner.z_fade_height) {
  3480. SERIAL_ECHOPAIR(" (", ftostr43sign(
  3481. mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS], planner.fade_scaling_factor_for_z(current_position[Z_AXIS])), '+'
  3482. ));
  3483. SERIAL_CHAR(')');
  3484. }
  3485. #endif
  3486. }
  3487. else
  3488. SERIAL_ECHOPGM(" (disabled)");
  3489. SERIAL_EOL();
  3490. #endif // MESH_BED_LEVELING
  3491. }
  3492. #endif // DEBUG_LEVELING_FEATURE
  3493. #if ENABLED(DELTA)
  3494. #if ENABLED(SENSORLESS_HOMING)
  3495. inline void delta_sensorless_homing(const bool on=true) {
  3496. sensorless_homing_per_axis(A_AXIS, on);
  3497. sensorless_homing_per_axis(B_AXIS, on);
  3498. sensorless_homing_per_axis(C_AXIS, on);
  3499. }
  3500. #endif
  3501. /**
  3502. * A delta can only safely home all axes at the same time
  3503. * This is like quick_home_xy() but for 3 towers.
  3504. */
  3505. inline void home_delta() {
  3506. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3507. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3508. #endif
  3509. // Init the current position of all carriages to 0,0,0
  3510. ZERO(current_position);
  3511. sync_plan_position();
  3512. // Disable stealthChop if used. Enable diag1 pin on driver.
  3513. #if ENABLED(SENSORLESS_HOMING)
  3514. delta_sensorless_homing();
  3515. #endif
  3516. // Move all carriages together linearly until an endstop is hit.
  3517. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (delta_height + 10);
  3518. feedrate_mm_s = homing_feedrate(X_AXIS);
  3519. buffer_line_to_current_position();
  3520. planner.synchronize();
  3521. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  3522. #if ENABLED(SENSORLESS_HOMING)
  3523. delta_sensorless_homing(false);
  3524. #endif
  3525. endstops.validate_homing_move();
  3526. // At least one carriage has reached the top.
  3527. // Now re-home each carriage separately.
  3528. homeaxis(A_AXIS);
  3529. homeaxis(B_AXIS);
  3530. homeaxis(C_AXIS);
  3531. // Set all carriages to their home positions
  3532. // Do this here all at once for Delta, because
  3533. // XYZ isn't ABC. Applying this per-tower would
  3534. // give the impression that they are the same.
  3535. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3536. SYNC_PLAN_POSITION_KINEMATIC();
  3537. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3538. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3539. #endif
  3540. }
  3541. #elif ENABLED(HANGPRINTER)
  3542. /**
  3543. * A hangprinter cannot home itself
  3544. */
  3545. inline void home_hangprinter() {
  3546. SERIAL_ECHOLNPGM("Warning: G28 is not implemented for Hangprinter.");
  3547. }
  3548. #endif
  3549. #ifdef Z_AFTER_PROBING
  3550. void move_z_after_probing() {
  3551. if (current_position[Z_AXIS] != Z_AFTER_PROBING) {
  3552. do_blocking_move_to_z(Z_AFTER_PROBING);
  3553. current_position[Z_AXIS] = Z_AFTER_PROBING;
  3554. }
  3555. }
  3556. #endif
  3557. #if ENABLED(Z_SAFE_HOMING)
  3558. inline void home_z_safely() {
  3559. // Disallow Z homing if X or Y are unknown
  3560. if (!TEST(axis_known_position, X_AXIS) || !TEST(axis_known_position, Y_AXIS)) {
  3561. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3562. SERIAL_ECHO_START();
  3563. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3564. return;
  3565. }
  3566. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3567. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3568. #endif
  3569. SYNC_PLAN_POSITION_KINEMATIC();
  3570. /**
  3571. * Move the Z probe (or just the nozzle) to the safe homing point
  3572. */
  3573. destination[X_AXIS] = Z_SAFE_HOMING_X_POINT;
  3574. destination[Y_AXIS] = Z_SAFE_HOMING_Y_POINT;
  3575. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3576. #if HOMING_Z_WITH_PROBE
  3577. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3578. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3579. #endif
  3580. if (position_is_reachable(destination[X_AXIS], destination[Y_AXIS])) {
  3581. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3582. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3583. #endif
  3584. // This causes the carriage on Dual X to unpark
  3585. #if ENABLED(DUAL_X_CARRIAGE)
  3586. active_extruder_parked = false;
  3587. #endif
  3588. #if ENABLED(SENSORLESS_HOMING)
  3589. safe_delay(500); // Short delay needed to settle
  3590. #endif
  3591. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3592. homeaxis(Z_AXIS);
  3593. }
  3594. else {
  3595. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3596. SERIAL_ECHO_START();
  3597. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3598. }
  3599. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3600. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3601. #endif
  3602. }
  3603. #endif // Z_SAFE_HOMING
  3604. #if ENABLED(PROBE_MANUALLY)
  3605. bool g29_in_progress = false;
  3606. #else
  3607. constexpr bool g29_in_progress = false;
  3608. #endif
  3609. /**
  3610. * G28: Home all axes according to settings
  3611. *
  3612. * Parameters
  3613. *
  3614. * None Home to all axes with no parameters.
  3615. * With QUICK_HOME enabled XY will home together, then Z.
  3616. *
  3617. * O Home only if position is unknown
  3618. *
  3619. * Rn Raise by n mm/inches before homing
  3620. *
  3621. * Cartesian parameters
  3622. *
  3623. * X Home to the X endstop
  3624. * Y Home to the Y endstop
  3625. * Z Home to the Z endstop
  3626. *
  3627. */
  3628. inline void gcode_G28(const bool always_home_all) {
  3629. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3630. if (DEBUGGING(LEVELING)) {
  3631. SERIAL_ECHOLNPGM(">>> G28");
  3632. log_machine_info();
  3633. }
  3634. #endif
  3635. #if ENABLED(MARLIN_DEV_MODE)
  3636. if (parser.seen('S')) {
  3637. LOOP_XYZ(a) set_axis_is_at_home((AxisEnum)a);
  3638. SYNC_PLAN_POSITION_KINEMATIC();
  3639. SERIAL_ECHOLNPGM("Simulated Homing");
  3640. report_current_position();
  3641. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3642. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G28");
  3643. #endif
  3644. return;
  3645. }
  3646. #endif
  3647. if (all_axes_known() && parser.boolval('O')) { // home only if needed
  3648. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3649. if (DEBUGGING(LEVELING)) {
  3650. SERIAL_ECHOLNPGM("> homing not needed, skip");
  3651. SERIAL_ECHOLNPGM("<<< G28");
  3652. }
  3653. #endif
  3654. return;
  3655. }
  3656. // Wait for planner moves to finish!
  3657. planner.synchronize();
  3658. // Cancel the active G29 session
  3659. #if ENABLED(PROBE_MANUALLY)
  3660. g29_in_progress = false;
  3661. #endif
  3662. // Disable the leveling matrix before homing
  3663. #if HAS_LEVELING
  3664. #if ENABLED(RESTORE_LEVELING_AFTER_G28)
  3665. const bool leveling_was_active = planner.leveling_active;
  3666. #endif
  3667. set_bed_leveling_enabled(false);
  3668. #endif
  3669. #if ENABLED(CNC_WORKSPACE_PLANES)
  3670. workspace_plane = PLANE_XY;
  3671. #endif
  3672. #if ENABLED(BLTOUCH)
  3673. // Make sure any BLTouch error condition is cleared
  3674. bltouch_command(BLTOUCH_RESET);
  3675. set_bltouch_deployed(false);
  3676. #endif
  3677. // Always home with tool 0 active
  3678. #if HOTENDS > 1
  3679. #if DISABLED(DELTA) || ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3680. const uint8_t old_tool_index = active_extruder;
  3681. #endif
  3682. tool_change(0, 0, true);
  3683. #endif
  3684. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3685. extruder_duplication_enabled = false;
  3686. #endif
  3687. setup_for_endstop_or_probe_move();
  3688. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3689. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3690. #endif
  3691. endstops.enable(true); // Enable endstops for next homing move
  3692. #if ENABLED(DELTA)
  3693. home_delta();
  3694. UNUSED(always_home_all);
  3695. #elif ENABLED(HANGPRINTER)
  3696. home_hangprinter();
  3697. UNUSED(always_home_all);
  3698. #else // NOT Delta or Hangprinter
  3699. const bool homeX = always_home_all || parser.seen('X'),
  3700. homeY = always_home_all || parser.seen('Y'),
  3701. homeZ = always_home_all || parser.seen('Z'),
  3702. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3703. set_destination_from_current();
  3704. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3705. if (home_all || homeZ) homeaxis(Z_AXIS);
  3706. #endif
  3707. const float z_homing_height = (
  3708. #if ENABLED(UNKNOWN_Z_NO_RAISE)
  3709. !TEST(axis_known_position, Z_AXIS) ? 0 :
  3710. #endif
  3711. (parser.seenval('R') ? parser.value_linear_units() : Z_HOMING_HEIGHT)
  3712. );
  3713. if (z_homing_height && (home_all || homeX || homeY)) {
  3714. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3715. destination[Z_AXIS] = z_homing_height;
  3716. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3717. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3718. if (DEBUGGING(LEVELING))
  3719. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3720. #endif
  3721. do_blocking_move_to_z(destination[Z_AXIS]);
  3722. }
  3723. }
  3724. #if ENABLED(QUICK_HOME)
  3725. if (home_all || (homeX && homeY)) quick_home_xy();
  3726. #endif
  3727. // Home Y (before X)
  3728. #if ENABLED(HOME_Y_BEFORE_X)
  3729. if (home_all || homeY
  3730. #if ENABLED(CODEPENDENT_XY_HOMING)
  3731. || homeX
  3732. #endif
  3733. ) homeaxis(Y_AXIS);
  3734. #endif
  3735. // Home X
  3736. if (home_all || homeX
  3737. #if ENABLED(CODEPENDENT_XY_HOMING) && DISABLED(HOME_Y_BEFORE_X)
  3738. || homeY
  3739. #endif
  3740. ) {
  3741. #if ENABLED(DUAL_X_CARRIAGE)
  3742. // Always home the 2nd (right) extruder first
  3743. active_extruder = 1;
  3744. homeaxis(X_AXIS);
  3745. // Remember this extruder's position for later tool change
  3746. inactive_extruder_x_pos = current_position[X_AXIS];
  3747. // Home the 1st (left) extruder
  3748. active_extruder = 0;
  3749. homeaxis(X_AXIS);
  3750. // Consider the active extruder to be parked
  3751. COPY(raised_parked_position, current_position);
  3752. delayed_move_time = 0;
  3753. active_extruder_parked = true;
  3754. #else
  3755. homeaxis(X_AXIS);
  3756. #endif
  3757. }
  3758. // Home Y (after X)
  3759. #if DISABLED(HOME_Y_BEFORE_X)
  3760. if (home_all || homeY) homeaxis(Y_AXIS);
  3761. #endif
  3762. // Home Z last if homing towards the bed
  3763. #if Z_HOME_DIR < 0
  3764. if (home_all || homeZ) {
  3765. #if ENABLED(Z_SAFE_HOMING)
  3766. home_z_safely();
  3767. #else
  3768. homeaxis(Z_AXIS);
  3769. #endif
  3770. #if HOMING_Z_WITH_PROBE && defined(Z_AFTER_PROBING)
  3771. move_z_after_probing();
  3772. #endif
  3773. } // home_all || homeZ
  3774. #endif // Z_HOME_DIR < 0
  3775. SYNC_PLAN_POSITION_KINEMATIC();
  3776. #endif // !DELTA (gcode_G28)
  3777. endstops.not_homing();
  3778. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3779. // move to a height where we can use the full xy-area
  3780. do_blocking_move_to_z(delta_clip_start_height);
  3781. #endif
  3782. #if ENABLED(RESTORE_LEVELING_AFTER_G28)
  3783. set_bed_leveling_enabled(leveling_was_active);
  3784. #endif
  3785. clean_up_after_endstop_or_probe_move();
  3786. // Restore the active tool after homing
  3787. #if HOTENDS > 1 && (DISABLED(DELTA) || ENABLED(DELTA_HOME_TO_SAFE_ZONE))
  3788. #if ENABLED(PARKING_EXTRUDER)
  3789. #define NO_FETCH false // fetch the previous toolhead
  3790. #else
  3791. #define NO_FETCH true
  3792. #endif
  3793. tool_change(old_tool_index, 0, NO_FETCH);
  3794. #endif
  3795. lcd_refresh();
  3796. report_current_position();
  3797. #if ENABLED(NANODLP_Z_SYNC)
  3798. #if ENABLED(NANODLP_ALL_AXIS)
  3799. #define _HOME_SYNC true // For any axis, output sync text.
  3800. #else
  3801. #define _HOME_SYNC (home_all || homeZ) // Only for Z-axis
  3802. #endif
  3803. if (_HOME_SYNC)
  3804. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  3805. #endif
  3806. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3807. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G28");
  3808. #endif
  3809. } // G28
  3810. void home_all_axes() { gcode_G28(true); }
  3811. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3812. inline void _manual_goto_xy(const float &rx, const float &ry) {
  3813. #ifdef MANUAL_PROBE_START_Z
  3814. #if MANUAL_PROBE_HEIGHT > 0
  3815. do_blocking_move_to(rx, ry, MANUAL_PROBE_HEIGHT);
  3816. do_blocking_move_to_z(MAX(0,MANUAL_PROBE_START_Z));
  3817. #else
  3818. do_blocking_move_to(rx, ry, MAX(0,MANUAL_PROBE_START_Z));
  3819. #endif
  3820. #elif MANUAL_PROBE_HEIGHT > 0
  3821. const float prev_z = current_position[Z_AXIS];
  3822. do_blocking_move_to(rx, ry, MANUAL_PROBE_HEIGHT);
  3823. do_blocking_move_to_z(prev_z);
  3824. #else
  3825. do_blocking_move_to_xy(rx, ry);
  3826. #endif
  3827. current_position[X_AXIS] = rx;
  3828. current_position[Y_AXIS] = ry;
  3829. #if ENABLED(LCD_BED_LEVELING)
  3830. lcd_wait_for_move = false;
  3831. #endif
  3832. }
  3833. #endif
  3834. #if ENABLED(MESH_BED_LEVELING)
  3835. // Save 130 bytes with non-duplication of PSTR
  3836. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3837. /**
  3838. * G29: Mesh-based Z probe, probes a grid and produces a
  3839. * mesh to compensate for variable bed height
  3840. *
  3841. * Parameters With MESH_BED_LEVELING:
  3842. *
  3843. * S0 Produce a mesh report
  3844. * S1 Start probing mesh points
  3845. * S2 Probe the next mesh point
  3846. * S3 Xn Yn Zn.nn Manually modify a single point
  3847. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3848. * S5 Reset and disable mesh
  3849. *
  3850. * The S0 report the points as below
  3851. *
  3852. * +----> X-axis 1-n
  3853. * |
  3854. * |
  3855. * v Y-axis 1-n
  3856. *
  3857. */
  3858. inline void gcode_G29() {
  3859. static int mbl_probe_index = -1;
  3860. #if HAS_SOFTWARE_ENDSTOPS
  3861. static bool enable_soft_endstops;
  3862. #endif
  3863. MeshLevelingState state = (MeshLevelingState)parser.byteval('S', (int8_t)MeshReport);
  3864. if (!WITHIN(state, 0, 5)) {
  3865. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3866. return;
  3867. }
  3868. int8_t px, py;
  3869. switch (state) {
  3870. case MeshReport:
  3871. if (leveling_is_valid()) {
  3872. SERIAL_PROTOCOLLNPAIR("State: ", planner.leveling_active ? MSG_ON : MSG_OFF);
  3873. mbl.report_mesh();
  3874. }
  3875. else
  3876. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3877. break;
  3878. case MeshStart:
  3879. mbl.reset();
  3880. mbl_probe_index = 0;
  3881. if (!lcd_wait_for_move) {
  3882. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3883. return;
  3884. }
  3885. state = MeshNext;
  3886. case MeshNext:
  3887. if (mbl_probe_index < 0) {
  3888. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3889. return;
  3890. }
  3891. // For each G29 S2...
  3892. if (mbl_probe_index == 0) {
  3893. #if HAS_SOFTWARE_ENDSTOPS
  3894. // For the initial G29 S2 save software endstop state
  3895. enable_soft_endstops = soft_endstops_enabled;
  3896. #endif
  3897. // Move close to the bed before the first point
  3898. do_blocking_move_to_z(0);
  3899. }
  3900. else {
  3901. // Save Z for the previous mesh position
  3902. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  3903. #if HAS_SOFTWARE_ENDSTOPS
  3904. soft_endstops_enabled = enable_soft_endstops;
  3905. #endif
  3906. }
  3907. // If there's another point to sample, move there with optional lift.
  3908. if (mbl_probe_index < GRID_MAX_POINTS) {
  3909. #if HAS_SOFTWARE_ENDSTOPS
  3910. // Disable software endstops to allow manual adjustment
  3911. // If G29 is not completed, they will not be re-enabled
  3912. soft_endstops_enabled = false;
  3913. #endif
  3914. mbl.zigzag(mbl_probe_index++, px, py);
  3915. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  3916. }
  3917. else {
  3918. // One last "return to the bed" (as originally coded) at completion
  3919. current_position[Z_AXIS] = MANUAL_PROBE_HEIGHT;
  3920. buffer_line_to_current_position();
  3921. planner.synchronize();
  3922. // After recording the last point, activate home and activate
  3923. mbl_probe_index = -1;
  3924. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3925. BUZZ(100, 659);
  3926. BUZZ(100, 698);
  3927. home_all_axes();
  3928. set_bed_leveling_enabled(true);
  3929. #if ENABLED(MESH_G28_REST_ORIGIN)
  3930. current_position[Z_AXIS] = 0;
  3931. set_destination_from_current();
  3932. buffer_line_to_destination(homing_feedrate(Z_AXIS));
  3933. planner.synchronize();
  3934. #endif
  3935. #if ENABLED(LCD_BED_LEVELING)
  3936. lcd_wait_for_move = false;
  3937. #endif
  3938. }
  3939. break;
  3940. case MeshSet:
  3941. if (parser.seenval('X')) {
  3942. px = parser.value_int() - 1;
  3943. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  3944. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  3945. return;
  3946. }
  3947. }
  3948. else {
  3949. SERIAL_CHAR('X'); echo_not_entered();
  3950. return;
  3951. }
  3952. if (parser.seenval('Y')) {
  3953. py = parser.value_int() - 1;
  3954. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  3955. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  3956. return;
  3957. }
  3958. }
  3959. else {
  3960. SERIAL_CHAR('Y'); echo_not_entered();
  3961. return;
  3962. }
  3963. if (parser.seenval('Z'))
  3964. mbl.z_values[px][py] = parser.value_linear_units();
  3965. else {
  3966. SERIAL_CHAR('Z'); echo_not_entered();
  3967. return;
  3968. }
  3969. break;
  3970. case MeshSetZOffset:
  3971. if (parser.seenval('Z'))
  3972. mbl.z_offset = parser.value_linear_units();
  3973. else {
  3974. SERIAL_CHAR('Z'); echo_not_entered();
  3975. return;
  3976. }
  3977. break;
  3978. case MeshReset:
  3979. reset_bed_level();
  3980. break;
  3981. } // switch (state)
  3982. if (state == MeshNext) {
  3983. SERIAL_PROTOCOLPAIR("MBL G29 point ", MIN(mbl_probe_index, GRID_MAX_POINTS));
  3984. SERIAL_PROTOCOLLNPAIR(" of ", int(GRID_MAX_POINTS));
  3985. }
  3986. report_current_position();
  3987. }
  3988. #elif OLDSCHOOL_ABL
  3989. #if ABL_GRID
  3990. #if ENABLED(PROBE_Y_FIRST)
  3991. #define PR_OUTER_VAR xCount
  3992. #define PR_OUTER_END abl_grid_points_x
  3993. #define PR_INNER_VAR yCount
  3994. #define PR_INNER_END abl_grid_points_y
  3995. #else
  3996. #define PR_OUTER_VAR yCount
  3997. #define PR_OUTER_END abl_grid_points_y
  3998. #define PR_INNER_VAR xCount
  3999. #define PR_INNER_END abl_grid_points_x
  4000. #endif
  4001. #endif
  4002. /**
  4003. * G29: Detailed Z probe, probes the bed at 3 or more points.
  4004. * Will fail if the printer has not been homed with G28.
  4005. *
  4006. * Enhanced G29 Auto Bed Leveling Probe Routine
  4007. *
  4008. * O Auto-level only if needed
  4009. *
  4010. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  4011. * or alter the bed level data. Useful to check the topology
  4012. * after a first run of G29.
  4013. *
  4014. * J Jettison current bed leveling data
  4015. *
  4016. * V Set the verbose level (0-4). Example: "G29 V3"
  4017. *
  4018. * Parameters With LINEAR leveling only:
  4019. *
  4020. * P Set the size of the grid that will be probed (P x P points).
  4021. * Example: "G29 P4"
  4022. *
  4023. * X Set the X size of the grid that will be probed (X x Y points).
  4024. * Example: "G29 X7 Y5"
  4025. *
  4026. * Y Set the Y size of the grid that will be probed (X x Y points).
  4027. *
  4028. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  4029. * This is useful for manual bed leveling and finding flaws in the bed (to
  4030. * assist with part placement).
  4031. * Not supported by non-linear delta printer bed leveling.
  4032. *
  4033. * Parameters With LINEAR and BILINEAR leveling only:
  4034. *
  4035. * S Set the XY travel speed between probe points (in units/min)
  4036. *
  4037. * F Set the Front limit of the probing grid
  4038. * B Set the Back limit of the probing grid
  4039. * L Set the Left limit of the probing grid
  4040. * R Set the Right limit of the probing grid
  4041. *
  4042. * Parameters with DEBUG_LEVELING_FEATURE only:
  4043. *
  4044. * C Make a totally fake grid with no actual probing.
  4045. * For use in testing when no probing is possible.
  4046. *
  4047. * Parameters with BILINEAR leveling only:
  4048. *
  4049. * Z Supply an additional Z probe offset
  4050. *
  4051. * Extra parameters with PROBE_MANUALLY:
  4052. *
  4053. * To do manual probing simply repeat G29 until the procedure is complete.
  4054. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  4055. *
  4056. * Q Query leveling and G29 state
  4057. *
  4058. * A Abort current leveling procedure
  4059. *
  4060. * Extra parameters with BILINEAR only:
  4061. *
  4062. * W Write a mesh point. (If G29 is idle.)
  4063. * I X index for mesh point
  4064. * J Y index for mesh point
  4065. * X X for mesh point, overrides I
  4066. * Y Y for mesh point, overrides J
  4067. * Z Z for mesh point. Otherwise, raw current Z.
  4068. *
  4069. * Without PROBE_MANUALLY:
  4070. *
  4071. * E By default G29 will engage the Z probe, test the bed, then disengage.
  4072. * Include "E" to engage/disengage the Z probe for each sample.
  4073. * There's no extra effect if you have a fixed Z probe.
  4074. *
  4075. */
  4076. inline void gcode_G29() {
  4077. #if ENABLED(DEBUG_LEVELING_FEATURE) || ENABLED(PROBE_MANUALLY)
  4078. const bool seenQ = parser.seen('Q');
  4079. #else
  4080. constexpr bool seenQ = false;
  4081. #endif
  4082. // G29 Q is also available if debugging
  4083. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4084. const uint8_t old_debug_flags = marlin_debug_flags;
  4085. if (seenQ) marlin_debug_flags |= DEBUG_LEVELING;
  4086. if (DEBUGGING(LEVELING)) {
  4087. DEBUG_POS(">>> G29", current_position);
  4088. log_machine_info();
  4089. }
  4090. marlin_debug_flags = old_debug_flags;
  4091. #if DISABLED(PROBE_MANUALLY)
  4092. if (seenQ) return;
  4093. #endif
  4094. #endif
  4095. #if ENABLED(PROBE_MANUALLY)
  4096. const bool seenA = parser.seen('A');
  4097. #else
  4098. constexpr bool seenA = false;
  4099. #endif
  4100. const bool no_action = seenA || seenQ,
  4101. faux =
  4102. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  4103. parser.boolval('C')
  4104. #else
  4105. no_action
  4106. #endif
  4107. ;
  4108. // Don't allow auto-leveling without homing first
  4109. if (axis_unhomed_error()) return;
  4110. if (!no_action && planner.leveling_active && parser.boolval('O')) { // Auto-level only if needed
  4111. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4112. if (DEBUGGING(LEVELING)) {
  4113. SERIAL_ECHOLNPGM("> Auto-level not needed, skip");
  4114. SERIAL_ECHOLNPGM("<<< G29");
  4115. }
  4116. #endif
  4117. return;
  4118. }
  4119. // Define local vars 'static' for manual probing, 'auto' otherwise
  4120. #if ENABLED(PROBE_MANUALLY)
  4121. #define ABL_VAR static
  4122. #else
  4123. #define ABL_VAR
  4124. #endif
  4125. ABL_VAR int verbose_level;
  4126. ABL_VAR float xProbe, yProbe, measured_z;
  4127. ABL_VAR bool dryrun, abl_should_enable;
  4128. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  4129. ABL_VAR int16_t abl_probe_index;
  4130. #endif
  4131. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  4132. ABL_VAR bool enable_soft_endstops = true;
  4133. #endif
  4134. #if ABL_GRID
  4135. #if ENABLED(PROBE_MANUALLY)
  4136. ABL_VAR uint8_t PR_OUTER_VAR;
  4137. ABL_VAR int8_t PR_INNER_VAR;
  4138. #endif
  4139. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  4140. ABL_VAR float xGridSpacing = 0, yGridSpacing = 0;
  4141. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4142. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  4143. abl_grid_points_y = GRID_MAX_POINTS_Y;
  4144. ABL_VAR bool do_topography_map;
  4145. #else // Bilinear
  4146. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  4147. abl_grid_points_y = GRID_MAX_POINTS_Y;
  4148. #endif
  4149. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4150. ABL_VAR int16_t abl_points;
  4151. #elif ENABLED(PROBE_MANUALLY) // Bilinear
  4152. int16_t constexpr abl_points = GRID_MAX_POINTS;
  4153. #endif
  4154. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4155. ABL_VAR float zoffset;
  4156. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4157. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  4158. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  4159. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  4160. mean;
  4161. #endif
  4162. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4163. #if ENABLED(PROBE_MANUALLY)
  4164. int8_t constexpr abl_points = 3; // used to show total points
  4165. #endif
  4166. // Probe at 3 arbitrary points
  4167. ABL_VAR vector_3 points[3] = {
  4168. vector_3(PROBE_PT_1_X, PROBE_PT_1_Y, 0),
  4169. vector_3(PROBE_PT_2_X, PROBE_PT_2_Y, 0),
  4170. vector_3(PROBE_PT_3_X, PROBE_PT_3_Y, 0)
  4171. };
  4172. #endif // AUTO_BED_LEVELING_3POINT
  4173. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4174. struct linear_fit_data lsf_results;
  4175. incremental_LSF_reset(&lsf_results);
  4176. #endif
  4177. /**
  4178. * On the initial G29 fetch command parameters.
  4179. */
  4180. if (!g29_in_progress) {
  4181. #if ENABLED(DUAL_X_CARRIAGE)
  4182. if (active_extruder != 0) tool_change(0);
  4183. #endif
  4184. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  4185. abl_probe_index = -1;
  4186. #endif
  4187. abl_should_enable = planner.leveling_active;
  4188. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4189. const bool seen_w = parser.seen('W');
  4190. if (seen_w) {
  4191. if (!leveling_is_valid()) {
  4192. SERIAL_ERROR_START();
  4193. SERIAL_ERRORLNPGM("No bilinear grid");
  4194. return;
  4195. }
  4196. const float rz = parser.seenval('Z') ? RAW_Z_POSITION(parser.value_linear_units()) : current_position[Z_AXIS];
  4197. if (!WITHIN(rz, -10, 10)) {
  4198. SERIAL_ERROR_START();
  4199. SERIAL_ERRORLNPGM("Bad Z value");
  4200. return;
  4201. }
  4202. const float rx = RAW_X_POSITION(parser.linearval('X', NAN)),
  4203. ry = RAW_Y_POSITION(parser.linearval('Y', NAN));
  4204. int8_t i = parser.byteval('I', -1),
  4205. j = parser.byteval('J', -1);
  4206. if (!isnan(rx) && !isnan(ry)) {
  4207. // Get nearest i / j from rx / ry
  4208. i = (rx - bilinear_start[X_AXIS] + 0.5f * xGridSpacing) / xGridSpacing;
  4209. j = (ry - bilinear_start[Y_AXIS] + 0.5f * yGridSpacing) / yGridSpacing;
  4210. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  4211. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  4212. }
  4213. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  4214. set_bed_leveling_enabled(false);
  4215. z_values[i][j] = rz;
  4216. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4217. bed_level_virt_interpolate();
  4218. #endif
  4219. set_bed_leveling_enabled(abl_should_enable);
  4220. if (abl_should_enable) report_current_position();
  4221. }
  4222. return;
  4223. } // parser.seen('W')
  4224. #else
  4225. constexpr bool seen_w = false;
  4226. #endif
  4227. // Jettison bed leveling data
  4228. if (!seen_w && parser.seen('J')) {
  4229. reset_bed_level();
  4230. return;
  4231. }
  4232. verbose_level = parser.intval('V');
  4233. if (!WITHIN(verbose_level, 0, 4)) {
  4234. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  4235. return;
  4236. }
  4237. dryrun = parser.boolval('D')
  4238. #if ENABLED(PROBE_MANUALLY)
  4239. || no_action
  4240. #endif
  4241. ;
  4242. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4243. do_topography_map = verbose_level > 2 || parser.boolval('T');
  4244. // X and Y specify points in each direction, overriding the default
  4245. // These values may be saved with the completed mesh
  4246. abl_grid_points_x = parser.intval('X', GRID_MAX_POINTS_X);
  4247. abl_grid_points_y = parser.intval('Y', GRID_MAX_POINTS_Y);
  4248. if (parser.seenval('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  4249. if (!WITHIN(abl_grid_points_x, 2, GRID_MAX_POINTS_X)) {
  4250. SERIAL_PROTOCOLLNPGM("?Probe points (X) is implausible (2-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  4251. return;
  4252. }
  4253. if (!WITHIN(abl_grid_points_y, 2, GRID_MAX_POINTS_Y)) {
  4254. SERIAL_PROTOCOLLNPGM("?Probe points (Y) is implausible (2-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  4255. return;
  4256. }
  4257. abl_points = abl_grid_points_x * abl_grid_points_y;
  4258. mean = 0;
  4259. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4260. zoffset = parser.linearval('Z');
  4261. #endif
  4262. #if ABL_GRID
  4263. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_SPEED));
  4264. left_probe_bed_position = parser.seenval('L') ? int(RAW_X_POSITION(parser.value_linear_units())) : LEFT_PROBE_BED_POSITION;
  4265. right_probe_bed_position = parser.seenval('R') ? int(RAW_X_POSITION(parser.value_linear_units())) : RIGHT_PROBE_BED_POSITION;
  4266. front_probe_bed_position = parser.seenval('F') ? int(RAW_Y_POSITION(parser.value_linear_units())) : FRONT_PROBE_BED_POSITION;
  4267. back_probe_bed_position = parser.seenval('B') ? int(RAW_Y_POSITION(parser.value_linear_units())) : BACK_PROBE_BED_POSITION;
  4268. if (
  4269. #if IS_SCARA || ENABLED(DELTA)
  4270. !position_is_reachable_by_probe(left_probe_bed_position, 0)
  4271. || !position_is_reachable_by_probe(right_probe_bed_position, 0)
  4272. || !position_is_reachable_by_probe(0, front_probe_bed_position)
  4273. || !position_is_reachable_by_probe(0, back_probe_bed_position)
  4274. #else
  4275. !position_is_reachable_by_probe(left_probe_bed_position, front_probe_bed_position)
  4276. || !position_is_reachable_by_probe(right_probe_bed_position, back_probe_bed_position)
  4277. #endif
  4278. ) {
  4279. SERIAL_PROTOCOLLNPGM("? (L,R,F,B) out of bounds.");
  4280. return;
  4281. }
  4282. // probe at the points of a lattice grid
  4283. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  4284. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  4285. #endif // ABL_GRID
  4286. if (verbose_level > 0) {
  4287. SERIAL_PROTOCOLPGM("G29 Auto Bed Leveling");
  4288. if (dryrun) SERIAL_PROTOCOLPGM(" (DRYRUN)");
  4289. SERIAL_EOL();
  4290. }
  4291. planner.synchronize();
  4292. // Disable auto bed leveling during G29.
  4293. // Be formal so G29 can be done successively without G28.
  4294. if (!no_action) set_bed_leveling_enabled(false);
  4295. #if HAS_BED_PROBE
  4296. // Deploy the probe. Probe will raise if needed.
  4297. if (DEPLOY_PROBE()) {
  4298. set_bed_leveling_enabled(abl_should_enable);
  4299. return;
  4300. }
  4301. #endif
  4302. if (!faux) setup_for_endstop_or_probe_move();
  4303. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4304. #if ENABLED(PROBE_MANUALLY)
  4305. if (!no_action)
  4306. #endif
  4307. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  4308. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  4309. || left_probe_bed_position != bilinear_start[X_AXIS]
  4310. || front_probe_bed_position != bilinear_start[Y_AXIS]
  4311. ) {
  4312. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  4313. reset_bed_level();
  4314. // Initialize a grid with the given dimensions
  4315. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  4316. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  4317. bilinear_start[X_AXIS] = left_probe_bed_position;
  4318. bilinear_start[Y_AXIS] = front_probe_bed_position;
  4319. // Can't re-enable (on error) until the new grid is written
  4320. abl_should_enable = false;
  4321. }
  4322. #endif // AUTO_BED_LEVELING_BILINEAR
  4323. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  4324. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4325. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  4326. #endif
  4327. // Probe at 3 arbitrary points
  4328. points[0].z = points[1].z = points[2].z = 0;
  4329. #endif // AUTO_BED_LEVELING_3POINT
  4330. } // !g29_in_progress
  4331. #if ENABLED(PROBE_MANUALLY)
  4332. // For manual probing, get the next index to probe now.
  4333. // On the first probe this will be incremented to 0.
  4334. if (!no_action) {
  4335. ++abl_probe_index;
  4336. g29_in_progress = true;
  4337. }
  4338. // Abort current G29 procedure, go back to idle state
  4339. if (seenA && g29_in_progress) {
  4340. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  4341. #if HAS_SOFTWARE_ENDSTOPS
  4342. soft_endstops_enabled = enable_soft_endstops;
  4343. #endif
  4344. set_bed_leveling_enabled(abl_should_enable);
  4345. g29_in_progress = false;
  4346. #if ENABLED(LCD_BED_LEVELING)
  4347. lcd_wait_for_move = false;
  4348. #endif
  4349. }
  4350. // Query G29 status
  4351. if (verbose_level || seenQ) {
  4352. SERIAL_PROTOCOLPGM("Manual G29 ");
  4353. if (g29_in_progress) {
  4354. SERIAL_PROTOCOLPAIR("point ", MIN(abl_probe_index + 1, abl_points));
  4355. SERIAL_PROTOCOLLNPAIR(" of ", abl_points);
  4356. }
  4357. else
  4358. SERIAL_PROTOCOLLNPGM("idle");
  4359. }
  4360. if (no_action) return;
  4361. if (abl_probe_index == 0) {
  4362. // For the initial G29 save software endstop state
  4363. #if HAS_SOFTWARE_ENDSTOPS
  4364. enable_soft_endstops = soft_endstops_enabled;
  4365. #endif
  4366. // Move close to the bed before the first point
  4367. do_blocking_move_to_z(0);
  4368. }
  4369. else {
  4370. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(AUTO_BED_LEVELING_3POINT)
  4371. const uint16_t index = abl_probe_index - 1;
  4372. #endif
  4373. // For G29 after adjusting Z.
  4374. // Save the previous Z before going to the next point
  4375. measured_z = current_position[Z_AXIS];
  4376. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4377. mean += measured_z;
  4378. eqnBVector[index] = measured_z;
  4379. eqnAMatrix[index + 0 * abl_points] = xProbe;
  4380. eqnAMatrix[index + 1 * abl_points] = yProbe;
  4381. eqnAMatrix[index + 2 * abl_points] = 1;
  4382. incremental_LSF(&lsf_results, xProbe, yProbe, measured_z);
  4383. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4384. points[index].z = measured_z;
  4385. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4386. z_values[xCount][yCount] = measured_z + zoffset;
  4387. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4388. if (DEBUGGING(LEVELING)) {
  4389. SERIAL_PROTOCOLPAIR("Save X", xCount);
  4390. SERIAL_PROTOCOLPAIR(" Y", yCount);
  4391. SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset);
  4392. }
  4393. #endif
  4394. #endif
  4395. }
  4396. //
  4397. // If there's another point to sample, move there with optional lift.
  4398. //
  4399. #if ABL_GRID
  4400. // Skip any unreachable points
  4401. while (abl_probe_index < abl_points) {
  4402. // Set xCount, yCount based on abl_probe_index, with zig-zag
  4403. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  4404. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  4405. // Probe in reverse order for every other row/column
  4406. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  4407. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  4408. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  4409. yBase = yCount * yGridSpacing + front_probe_bed_position;
  4410. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4411. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4412. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4413. indexIntoAB[xCount][yCount] = abl_probe_index;
  4414. #endif
  4415. // Keep looping till a reachable point is found
  4416. if (position_is_reachable(xProbe, yProbe)) break;
  4417. ++abl_probe_index;
  4418. }
  4419. // Is there a next point to move to?
  4420. if (abl_probe_index < abl_points) {
  4421. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  4422. #if HAS_SOFTWARE_ENDSTOPS
  4423. // Disable software endstops to allow manual adjustment
  4424. // If G29 is not completed, they will not be re-enabled
  4425. soft_endstops_enabled = false;
  4426. #endif
  4427. return;
  4428. }
  4429. else {
  4430. // Leveling done! Fall through to G29 finishing code below
  4431. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  4432. // Re-enable software endstops, if needed
  4433. #if HAS_SOFTWARE_ENDSTOPS
  4434. soft_endstops_enabled = enable_soft_endstops;
  4435. #endif
  4436. }
  4437. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4438. // Probe at 3 arbitrary points
  4439. if (abl_probe_index < abl_points) {
  4440. xProbe = points[abl_probe_index].x;
  4441. yProbe = points[abl_probe_index].y;
  4442. _manual_goto_xy(xProbe, yProbe);
  4443. #if HAS_SOFTWARE_ENDSTOPS
  4444. // Disable software endstops to allow manual adjustment
  4445. // If G29 is not completed, they will not be re-enabled
  4446. soft_endstops_enabled = false;
  4447. #endif
  4448. return;
  4449. }
  4450. else {
  4451. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  4452. // Re-enable software endstops, if needed
  4453. #if HAS_SOFTWARE_ENDSTOPS
  4454. soft_endstops_enabled = enable_soft_endstops;
  4455. #endif
  4456. if (!dryrun) {
  4457. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4458. if (planeNormal.z < 0) {
  4459. planeNormal.x *= -1;
  4460. planeNormal.y *= -1;
  4461. planeNormal.z *= -1;
  4462. }
  4463. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4464. // Can't re-enable (on error) until the new grid is written
  4465. abl_should_enable = false;
  4466. }
  4467. }
  4468. #endif // AUTO_BED_LEVELING_3POINT
  4469. #else // !PROBE_MANUALLY
  4470. {
  4471. const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE;
  4472. measured_z = 0;
  4473. #if ABL_GRID
  4474. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  4475. measured_z = 0;
  4476. // Outer loop is Y with PROBE_Y_FIRST disabled
  4477. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END && !isnan(measured_z); PR_OUTER_VAR++) {
  4478. int8_t inStart, inStop, inInc;
  4479. if (zig) { // away from origin
  4480. inStart = 0;
  4481. inStop = PR_INNER_END;
  4482. inInc = 1;
  4483. }
  4484. else { // towards origin
  4485. inStart = PR_INNER_END - 1;
  4486. inStop = -1;
  4487. inInc = -1;
  4488. }
  4489. zig ^= true; // zag
  4490. // Inner loop is Y with PROBE_Y_FIRST enabled
  4491. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  4492. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  4493. yBase = front_probe_bed_position + yGridSpacing * yCount;
  4494. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4495. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4496. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4497. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  4498. #endif
  4499. #if IS_KINEMATIC
  4500. // Avoid probing outside the round or hexagonal area
  4501. if (!position_is_reachable_by_probe(xProbe, yProbe)) continue;
  4502. #endif
  4503. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, raise_after, verbose_level);
  4504. if (isnan(measured_z)) {
  4505. set_bed_leveling_enabled(abl_should_enable);
  4506. break;
  4507. }
  4508. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4509. mean += measured_z;
  4510. eqnBVector[abl_probe_index] = measured_z;
  4511. eqnAMatrix[abl_probe_index + 0 * abl_points] = xProbe;
  4512. eqnAMatrix[abl_probe_index + 1 * abl_points] = yProbe;
  4513. eqnAMatrix[abl_probe_index + 2 * abl_points] = 1;
  4514. incremental_LSF(&lsf_results, xProbe, yProbe, measured_z);
  4515. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4516. z_values[xCount][yCount] = measured_z + zoffset;
  4517. #endif
  4518. abl_should_enable = false;
  4519. idle();
  4520. } // inner
  4521. } // outer
  4522. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4523. // Probe at 3 arbitrary points
  4524. for (uint8_t i = 0; i < 3; ++i) {
  4525. // Retain the last probe position
  4526. xProbe = points[i].x;
  4527. yProbe = points[i].y;
  4528. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, raise_after, verbose_level);
  4529. if (isnan(measured_z)) {
  4530. set_bed_leveling_enabled(abl_should_enable);
  4531. break;
  4532. }
  4533. points[i].z = measured_z;
  4534. }
  4535. if (!dryrun && !isnan(measured_z)) {
  4536. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4537. if (planeNormal.z < 0) {
  4538. planeNormal.x *= -1;
  4539. planeNormal.y *= -1;
  4540. planeNormal.z *= -1;
  4541. }
  4542. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4543. // Can't re-enable (on error) until the new grid is written
  4544. abl_should_enable = false;
  4545. }
  4546. #endif // AUTO_BED_LEVELING_3POINT
  4547. // Stow the probe. No raise for FIX_MOUNTED_PROBE.
  4548. if (STOW_PROBE()) {
  4549. set_bed_leveling_enabled(abl_should_enable);
  4550. measured_z = NAN;
  4551. }
  4552. }
  4553. #endif // !PROBE_MANUALLY
  4554. //
  4555. // G29 Finishing Code
  4556. //
  4557. // Unless this is a dry run, auto bed leveling will
  4558. // definitely be enabled after this point.
  4559. //
  4560. // If code above wants to continue leveling, it should
  4561. // return or loop before this point.
  4562. //
  4563. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4564. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  4565. #endif
  4566. #if ENABLED(PROBE_MANUALLY)
  4567. g29_in_progress = false;
  4568. #if ENABLED(LCD_BED_LEVELING)
  4569. lcd_wait_for_move = false;
  4570. #endif
  4571. #endif
  4572. // Calculate leveling, print reports, correct the position
  4573. if (!isnan(measured_z)) {
  4574. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4575. if (!dryrun) extrapolate_unprobed_bed_level();
  4576. print_bilinear_leveling_grid();
  4577. refresh_bed_level();
  4578. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4579. print_bilinear_leveling_grid_virt();
  4580. #endif
  4581. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4582. // For LINEAR leveling calculate matrix, print reports, correct the position
  4583. /**
  4584. * solve the plane equation ax + by + d = z
  4585. * A is the matrix with rows [x y 1] for all the probed points
  4586. * B is the vector of the Z positions
  4587. * the normal vector to the plane is formed by the coefficients of the
  4588. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  4589. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4590. */
  4591. float plane_equation_coefficients[3];
  4592. finish_incremental_LSF(&lsf_results);
  4593. plane_equation_coefficients[0] = -lsf_results.A; // We should be able to eliminate the '-' on these three lines and down below
  4594. plane_equation_coefficients[1] = -lsf_results.B; // but that is not yet tested.
  4595. plane_equation_coefficients[2] = -lsf_results.D;
  4596. mean /= abl_points;
  4597. if (verbose_level) {
  4598. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4599. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  4600. SERIAL_PROTOCOLPGM(" b: ");
  4601. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  4602. SERIAL_PROTOCOLPGM(" d: ");
  4603. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  4604. SERIAL_EOL();
  4605. if (verbose_level > 2) {
  4606. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  4607. SERIAL_PROTOCOL_F(mean, 8);
  4608. SERIAL_EOL();
  4609. }
  4610. }
  4611. // Create the matrix but don't correct the position yet
  4612. if (!dryrun)
  4613. planner.bed_level_matrix = matrix_3x3::create_look_at(
  4614. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1) // We can eliminate the '-' here and up above
  4615. );
  4616. // Show the Topography map if enabled
  4617. if (do_topography_map) {
  4618. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4619. " +--- BACK --+\n"
  4620. " | |\n"
  4621. " L | (+) | R\n"
  4622. " E | | I\n"
  4623. " F | (-) N (+) | G\n"
  4624. " T | | H\n"
  4625. " | (-) | T\n"
  4626. " | |\n"
  4627. " O-- FRONT --+\n"
  4628. " (0,0)");
  4629. float min_diff = 999;
  4630. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4631. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4632. int ind = indexIntoAB[xx][yy];
  4633. float diff = eqnBVector[ind] - mean,
  4634. x_tmp = eqnAMatrix[ind + 0 * abl_points],
  4635. y_tmp = eqnAMatrix[ind + 1 * abl_points],
  4636. z_tmp = 0;
  4637. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4638. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4639. if (diff >= 0.0)
  4640. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4641. else
  4642. SERIAL_PROTOCOLCHAR(' ');
  4643. SERIAL_PROTOCOL_F(diff, 5);
  4644. } // xx
  4645. SERIAL_EOL();
  4646. } // yy
  4647. SERIAL_EOL();
  4648. if (verbose_level > 3) {
  4649. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4650. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4651. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4652. int ind = indexIntoAB[xx][yy];
  4653. float x_tmp = eqnAMatrix[ind + 0 * abl_points],
  4654. y_tmp = eqnAMatrix[ind + 1 * abl_points],
  4655. z_tmp = 0;
  4656. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4657. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4658. if (diff >= 0.0)
  4659. SERIAL_PROTOCOLPGM(" +");
  4660. // Include + for column alignment
  4661. else
  4662. SERIAL_PROTOCOLCHAR(' ');
  4663. SERIAL_PROTOCOL_F(diff, 5);
  4664. } // xx
  4665. SERIAL_EOL();
  4666. } // yy
  4667. SERIAL_EOL();
  4668. }
  4669. } //do_topography_map
  4670. #endif // AUTO_BED_LEVELING_LINEAR
  4671. #if ABL_PLANAR
  4672. // For LINEAR and 3POINT leveling correct the current position
  4673. if (verbose_level > 0)
  4674. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4675. if (!dryrun) {
  4676. //
  4677. // Correct the current XYZ position based on the tilted plane.
  4678. //
  4679. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4680. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4681. #endif
  4682. float converted[XYZ];
  4683. COPY(converted, current_position);
  4684. planner.leveling_active = true;
  4685. planner.unapply_leveling(converted); // use conversion machinery
  4686. planner.leveling_active = false;
  4687. // Use the last measured distance to the bed, if possible
  4688. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4689. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4690. ) {
  4691. const float simple_z = current_position[Z_AXIS] - measured_z;
  4692. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4693. if (DEBUGGING(LEVELING)) {
  4694. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4695. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4696. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4697. }
  4698. #endif
  4699. converted[Z_AXIS] = simple_z;
  4700. }
  4701. // The rotated XY and corrected Z are now current_position
  4702. COPY(current_position, converted);
  4703. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4704. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4705. #endif
  4706. }
  4707. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4708. if (!dryrun) {
  4709. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4710. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4711. #endif
  4712. // Unapply the offset because it is going to be immediately applied
  4713. // and cause compensation movement in Z
  4714. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  4715. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4716. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4717. #endif
  4718. }
  4719. #endif // ABL_PLANAR
  4720. #ifdef Z_PROBE_END_SCRIPT
  4721. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4722. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4723. #endif
  4724. planner.synchronize();
  4725. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4726. #endif
  4727. // Auto Bed Leveling is complete! Enable if possible.
  4728. planner.leveling_active = dryrun ? abl_should_enable : true;
  4729. } // !isnan(measured_z)
  4730. // Restore state after probing
  4731. if (!faux) clean_up_after_endstop_or_probe_move();
  4732. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4733. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G29");
  4734. #endif
  4735. KEEPALIVE_STATE(IN_HANDLER);
  4736. if (planner.leveling_active)
  4737. SYNC_PLAN_POSITION_KINEMATIC();
  4738. #if HAS_BED_PROBE && defined(Z_AFTER_PROBING)
  4739. move_z_after_probing();
  4740. #endif
  4741. report_current_position();
  4742. }
  4743. #endif // OLDSCHOOL_ABL
  4744. #if HAS_BED_PROBE
  4745. /**
  4746. * G30: Do a single Z probe at the current XY
  4747. *
  4748. * Parameters:
  4749. *
  4750. * X Probe X position (default current X)
  4751. * Y Probe Y position (default current Y)
  4752. * E Engage the probe for each probe (default 1)
  4753. */
  4754. inline void gcode_G30() {
  4755. const float xpos = parser.linearval('X', current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER),
  4756. ypos = parser.linearval('Y', current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER);
  4757. if (!position_is_reachable_by_probe(xpos, ypos)) return;
  4758. // Disable leveling so the planner won't mess with us
  4759. #if HAS_LEVELING
  4760. set_bed_leveling_enabled(false);
  4761. #endif
  4762. setup_for_endstop_or_probe_move();
  4763. const ProbePtRaise raise_after = parser.boolval('E', true) ? PROBE_PT_STOW : PROBE_PT_NONE;
  4764. const float measured_z = probe_pt(xpos, ypos, raise_after, parser.intval('V', 1));
  4765. if (!isnan(measured_z)) {
  4766. SERIAL_PROTOCOLPAIR_F("Bed X: ", xpos);
  4767. SERIAL_PROTOCOLPAIR_F(" Y: ", ypos);
  4768. SERIAL_PROTOCOLLNPAIR_F(" Z: ", measured_z);
  4769. }
  4770. clean_up_after_endstop_or_probe_move();
  4771. #ifdef Z_AFTER_PROBING
  4772. if (raise_after == PROBE_PT_STOW) move_z_after_probing();
  4773. #endif
  4774. report_current_position();
  4775. }
  4776. #if ENABLED(Z_PROBE_SLED)
  4777. /**
  4778. * G31: Deploy the Z probe
  4779. */
  4780. inline void gcode_G31() { DEPLOY_PROBE(); }
  4781. /**
  4782. * G32: Stow the Z probe
  4783. */
  4784. inline void gcode_G32() { STOW_PROBE(); }
  4785. #endif // Z_PROBE_SLED
  4786. #endif // HAS_BED_PROBE
  4787. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4788. constexpr uint8_t _7P_STEP = 1, // 7-point step - to change number of calibration points
  4789. _4P_STEP = _7P_STEP * 2, // 4-point step
  4790. NPP = _7P_STEP * 6; // number of calibration points on the radius
  4791. enum CalEnum : char { // the 7 main calibration points - add definitions if needed
  4792. CEN = 0,
  4793. __A = 1,
  4794. _AB = __A + _7P_STEP,
  4795. __B = _AB + _7P_STEP,
  4796. _BC = __B + _7P_STEP,
  4797. __C = _BC + _7P_STEP,
  4798. _CA = __C + _7P_STEP,
  4799. };
  4800. #define LOOP_CAL_PT(VAR, S, N) for (uint8_t VAR=S; VAR<=NPP; VAR+=N)
  4801. #define F_LOOP_CAL_PT(VAR, S, N) for (float VAR=S; VAR<NPP+0.9999; VAR+=N)
  4802. #define I_LOOP_CAL_PT(VAR, S, N) for (float VAR=S; VAR>CEN+0.9999; VAR-=N)
  4803. #define LOOP_CAL_ALL(VAR) LOOP_CAL_PT(VAR, CEN, 1)
  4804. #define LOOP_CAL_RAD(VAR) LOOP_CAL_PT(VAR, __A, _7P_STEP)
  4805. #define LOOP_CAL_ACT(VAR, _4P, _OP) LOOP_CAL_PT(VAR, _OP ? _AB : __A, _4P ? _4P_STEP : _7P_STEP)
  4806. #if HOTENDS > 1
  4807. const uint8_t old_tool_index = active_extruder;
  4808. #define AC_CLEANUP() ac_cleanup(old_tool_index)
  4809. #else
  4810. #define AC_CLEANUP() ac_cleanup()
  4811. #endif
  4812. float lcd_probe_pt(const float &rx, const float &ry);
  4813. void ac_home() {
  4814. endstops.enable(true);
  4815. home_delta();
  4816. endstops.not_homing();
  4817. }
  4818. void ac_setup(const bool reset_bed) {
  4819. #if HOTENDS > 1
  4820. tool_change(0, 0, true);
  4821. #endif
  4822. planner.synchronize();
  4823. setup_for_endstop_or_probe_move();
  4824. #if HAS_LEVELING
  4825. if (reset_bed) reset_bed_level(); // After full calibration bed-level data is no longer valid
  4826. #endif
  4827. }
  4828. void ac_cleanup(
  4829. #if HOTENDS > 1
  4830. const uint8_t old_tool_index
  4831. #endif
  4832. ) {
  4833. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  4834. do_blocking_move_to_z(delta_clip_start_height);
  4835. #endif
  4836. #if HAS_BED_PROBE
  4837. STOW_PROBE();
  4838. #endif
  4839. clean_up_after_endstop_or_probe_move();
  4840. #if HOTENDS > 1
  4841. tool_change(old_tool_index, 0, true);
  4842. #endif
  4843. }
  4844. void print_signed_float(const char * const prefix, const float &f) {
  4845. SERIAL_PROTOCOLPGM(" ");
  4846. serialprintPGM(prefix);
  4847. SERIAL_PROTOCOLCHAR(':');
  4848. if (f >= 0) SERIAL_CHAR('+');
  4849. SERIAL_PROTOCOL_F(f, 2);
  4850. }
  4851. /**
  4852. * - Print the delta settings
  4853. */
  4854. static void print_calibration_settings(const bool end_stops, const bool tower_angles) {
  4855. SERIAL_PROTOCOLPAIR(".Height:", delta_height);
  4856. if (end_stops) {
  4857. print_signed_float(PSTR("Ex"), delta_endstop_adj[A_AXIS]);
  4858. print_signed_float(PSTR("Ey"), delta_endstop_adj[B_AXIS]);
  4859. print_signed_float(PSTR("Ez"), delta_endstop_adj[C_AXIS]);
  4860. }
  4861. if (end_stops && tower_angles) {
  4862. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4863. SERIAL_EOL();
  4864. SERIAL_CHAR('.');
  4865. SERIAL_PROTOCOL_SP(13);
  4866. }
  4867. if (tower_angles) {
  4868. print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]);
  4869. print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]);
  4870. print_signed_float(PSTR("Tz"), delta_tower_angle_trim[C_AXIS]);
  4871. }
  4872. if ((!end_stops && tower_angles) || (end_stops && !tower_angles)) { // XOR
  4873. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4874. }
  4875. #if HAS_BED_PROBE
  4876. if (!end_stops && !tower_angles) {
  4877. SERIAL_PROTOCOL_SP(30);
  4878. print_signed_float(PSTR("Offset"), zprobe_zoffset);
  4879. }
  4880. #endif
  4881. SERIAL_EOL();
  4882. }
  4883. /**
  4884. * - Print the probe results
  4885. */
  4886. static void print_calibration_results(const float z_pt[NPP + 1], const bool tower_points, const bool opposite_points) {
  4887. SERIAL_PROTOCOLPGM(". ");
  4888. print_signed_float(PSTR("c"), z_pt[CEN]);
  4889. if (tower_points) {
  4890. print_signed_float(PSTR(" x"), z_pt[__A]);
  4891. print_signed_float(PSTR(" y"), z_pt[__B]);
  4892. print_signed_float(PSTR(" z"), z_pt[__C]);
  4893. }
  4894. if (tower_points && opposite_points) {
  4895. SERIAL_EOL();
  4896. SERIAL_CHAR('.');
  4897. SERIAL_PROTOCOL_SP(13);
  4898. }
  4899. if (opposite_points) {
  4900. print_signed_float(PSTR("yz"), z_pt[_BC]);
  4901. print_signed_float(PSTR("zx"), z_pt[_CA]);
  4902. print_signed_float(PSTR("xy"), z_pt[_AB]);
  4903. }
  4904. SERIAL_EOL();
  4905. }
  4906. /**
  4907. * - Calculate the standard deviation from the zero plane
  4908. */
  4909. static float std_dev_points(float z_pt[NPP + 1], const bool _0p_cal, const bool _1p_cal, const bool _4p_cal, const bool _4p_opp) {
  4910. if (!_0p_cal) {
  4911. float S2 = sq(z_pt[CEN]);
  4912. int16_t N = 1;
  4913. if (!_1p_cal) { // std dev from zero plane
  4914. LOOP_CAL_ACT(rad, _4p_cal, _4p_opp) {
  4915. S2 += sq(z_pt[rad]);
  4916. N++;
  4917. }
  4918. return LROUND(SQRT(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  4919. }
  4920. }
  4921. return 0.00001;
  4922. }
  4923. /**
  4924. * - Probe a point
  4925. */
  4926. static float calibration_probe(const float &nx, const float &ny, const bool stow, const bool set_up) {
  4927. #if HAS_BED_PROBE
  4928. return probe_pt(nx, ny, set_up ? PROBE_PT_BIG_RAISE : stow ? PROBE_PT_STOW : PROBE_PT_RAISE, 0, false);
  4929. #else
  4930. UNUSED(stow);
  4931. UNUSED(set_up);
  4932. return lcd_probe_pt(nx, ny);
  4933. #endif
  4934. }
  4935. #if HAS_BED_PROBE && ENABLED(ULTIPANEL)
  4936. static float probe_z_shift(const float center) {
  4937. STOW_PROBE();
  4938. endstops.enable_z_probe(false);
  4939. float z_shift = lcd_probe_pt(0, 0) - center;
  4940. endstops.enable_z_probe(true);
  4941. return z_shift;
  4942. }
  4943. #endif
  4944. /**
  4945. * - Probe a grid
  4946. */
  4947. static bool probe_calibration_points(float z_pt[NPP + 1], const int8_t probe_points, const bool towers_set, const bool stow_after_each, const bool set_up) {
  4948. const bool _0p_calibration = probe_points == 0,
  4949. _1p_calibration = probe_points == 1 || probe_points == -1,
  4950. _4p_calibration = probe_points == 2,
  4951. _4p_opposite_points = _4p_calibration && !towers_set,
  4952. _7p_calibration = probe_points >= 3,
  4953. _7p_no_intermediates = probe_points == 3,
  4954. _7p_1_intermediates = probe_points == 4,
  4955. _7p_2_intermediates = probe_points == 5,
  4956. _7p_4_intermediates = probe_points == 6,
  4957. _7p_6_intermediates = probe_points == 7,
  4958. _7p_8_intermediates = probe_points == 8,
  4959. _7p_11_intermediates = probe_points == 9,
  4960. _7p_14_intermediates = probe_points == 10,
  4961. _7p_intermed_points = probe_points >= 4,
  4962. _7p_6_center = probe_points >= 5 && probe_points <= 7,
  4963. _7p_9_center = probe_points >= 8;
  4964. LOOP_CAL_ALL(rad) z_pt[rad] = 0.0;
  4965. if (!_0p_calibration) {
  4966. if (!_7p_no_intermediates && !_7p_4_intermediates && !_7p_11_intermediates) { // probe the center
  4967. z_pt[CEN] += calibration_probe(0, 0, stow_after_each, set_up);
  4968. if (isnan(z_pt[CEN])) return false;
  4969. }
  4970. if (_7p_calibration) { // probe extra center points
  4971. const float start = _7p_9_center ? float(_CA) + _7P_STEP / 3.0 : _7p_6_center ? float(_CA) : float(__C),
  4972. steps = _7p_9_center ? _4P_STEP / 3.0 : _7p_6_center ? _7P_STEP : _4P_STEP;
  4973. I_LOOP_CAL_PT(rad, start, steps) {
  4974. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  4975. r = delta_calibration_radius * 0.1;
  4976. z_pt[CEN] += calibration_probe(cos(a) * r, sin(a) * r, stow_after_each, set_up);
  4977. if (isnan(z_pt[CEN])) return false;
  4978. }
  4979. z_pt[CEN] /= float(_7p_2_intermediates ? 7 : probe_points);
  4980. }
  4981. if (!_1p_calibration) { // probe the radius
  4982. const CalEnum start = _4p_opposite_points ? _AB : __A;
  4983. const float steps = _7p_14_intermediates ? _7P_STEP / 15.0 : // 15r * 6 + 10c = 100
  4984. _7p_11_intermediates ? _7P_STEP / 12.0 : // 12r * 6 + 9c = 81
  4985. _7p_8_intermediates ? _7P_STEP / 9.0 : // 9r * 6 + 10c = 64
  4986. _7p_6_intermediates ? _7P_STEP / 7.0 : // 7r * 6 + 7c = 49
  4987. _7p_4_intermediates ? _7P_STEP / 5.0 : // 5r * 6 + 6c = 36
  4988. _7p_2_intermediates ? _7P_STEP / 3.0 : // 3r * 6 + 7c = 25
  4989. _7p_1_intermediates ? _7P_STEP / 2.0 : // 2r * 6 + 4c = 16
  4990. _7p_no_intermediates ? _7P_STEP : // 1r * 6 + 3c = 9
  4991. _4P_STEP; // .5r * 6 + 1c = 4
  4992. bool zig_zag = true;
  4993. F_LOOP_CAL_PT(rad, start, _7p_9_center ? steps * 3 : steps) {
  4994. const int8_t offset = _7p_9_center ? 2 : 0;
  4995. for (int8_t circle = 0; circle <= offset; circle++) {
  4996. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  4997. r = delta_calibration_radius * (1 - 0.1 * (zig_zag ? offset - circle : circle)),
  4998. interpol = fmod(rad, 1);
  4999. const float z_temp = calibration_probe(cos(a) * r, sin(a) * r, stow_after_each, set_up);
  5000. if (isnan(z_temp)) return false;
  5001. // split probe point to neighbouring calibration points
  5002. z_pt[uint8_t(LROUND(rad - interpol + NPP - 1)) % NPP + 1] += z_temp * sq(cos(RADIANS(interpol * 90)));
  5003. z_pt[uint8_t(LROUND(rad - interpol)) % NPP + 1] += z_temp * sq(sin(RADIANS(interpol * 90)));
  5004. }
  5005. zig_zag = !zig_zag;
  5006. }
  5007. if (_7p_intermed_points)
  5008. LOOP_CAL_RAD(rad)
  5009. z_pt[rad] /= _7P_STEP / steps;
  5010. do_blocking_move_to_xy(0.0, 0.0);
  5011. }
  5012. }
  5013. return true;
  5014. }
  5015. /**
  5016. * kinematics routines and auto tune matrix scaling parameters:
  5017. * see https://github.com/LVD-AC/Marlin-AC/tree/1.1.x-AC/documentation for
  5018. * - formulae for approximative forward kinematics in the end-stop displacement matrix
  5019. * - definition of the matrix scaling parameters
  5020. */
  5021. static void reverse_kinematics_probe_points(float z_pt[NPP + 1], float mm_at_pt_axis[NPP + 1][ABC]) {
  5022. float pos[XYZ] = { 0.0 };
  5023. LOOP_CAL_ALL(rad) {
  5024. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  5025. r = (rad == CEN ? 0.0 : delta_calibration_radius);
  5026. pos[X_AXIS] = cos(a) * r;
  5027. pos[Y_AXIS] = sin(a) * r;
  5028. pos[Z_AXIS] = z_pt[rad];
  5029. inverse_kinematics(pos);
  5030. LOOP_XYZ(axis) mm_at_pt_axis[rad][axis] = delta[axis];
  5031. }
  5032. }
  5033. static void forward_kinematics_probe_points(float mm_at_pt_axis[NPP + 1][ABC], float z_pt[NPP + 1]) {
  5034. const float r_quot = delta_calibration_radius / delta_radius;
  5035. #define ZPP(N,I,A) ((1 / 3.0 + r_quot * (N) / 3.0 ) * mm_at_pt_axis[I][A])
  5036. #define Z00(I, A) ZPP( 0, I, A)
  5037. #define Zp1(I, A) ZPP(+1, I, A)
  5038. #define Zm1(I, A) ZPP(-1, I, A)
  5039. #define Zp2(I, A) ZPP(+2, I, A)
  5040. #define Zm2(I, A) ZPP(-2, I, A)
  5041. z_pt[CEN] = Z00(CEN, A_AXIS) + Z00(CEN, B_AXIS) + Z00(CEN, C_AXIS);
  5042. z_pt[__A] = Zp2(__A, A_AXIS) + Zm1(__A, B_AXIS) + Zm1(__A, C_AXIS);
  5043. z_pt[__B] = Zm1(__B, A_AXIS) + Zp2(__B, B_AXIS) + Zm1(__B, C_AXIS);
  5044. z_pt[__C] = Zm1(__C, A_AXIS) + Zm1(__C, B_AXIS) + Zp2(__C, C_AXIS);
  5045. z_pt[_BC] = Zm2(_BC, A_AXIS) + Zp1(_BC, B_AXIS) + Zp1(_BC, C_AXIS);
  5046. z_pt[_CA] = Zp1(_CA, A_AXIS) + Zm2(_CA, B_AXIS) + Zp1(_CA, C_AXIS);
  5047. z_pt[_AB] = Zp1(_AB, A_AXIS) + Zp1(_AB, B_AXIS) + Zm2(_AB, C_AXIS);
  5048. }
  5049. static void calc_kinematics_diff_probe_points(float z_pt[NPP + 1], float delta_e[ABC], float delta_r, float delta_t[ABC]) {
  5050. const float z_center = z_pt[CEN];
  5051. float diff_mm_at_pt_axis[NPP + 1][ABC],
  5052. new_mm_at_pt_axis[NPP + 1][ABC];
  5053. reverse_kinematics_probe_points(z_pt, diff_mm_at_pt_axis);
  5054. delta_radius += delta_r;
  5055. LOOP_XYZ(axis) delta_tower_angle_trim[axis] += delta_t[axis];
  5056. recalc_delta_settings();
  5057. reverse_kinematics_probe_points(z_pt, new_mm_at_pt_axis);
  5058. LOOP_XYZ(axis) LOOP_CAL_ALL(rad) diff_mm_at_pt_axis[rad][axis] -= new_mm_at_pt_axis[rad][axis] + delta_e[axis];
  5059. forward_kinematics_probe_points(diff_mm_at_pt_axis, z_pt);
  5060. LOOP_CAL_RAD(rad) z_pt[rad] -= z_pt[CEN] - z_center;
  5061. z_pt[CEN] = z_center;
  5062. delta_radius -= delta_r;
  5063. LOOP_XYZ(axis) delta_tower_angle_trim[axis] -= delta_t[axis];
  5064. recalc_delta_settings();
  5065. }
  5066. static float auto_tune_h() {
  5067. const float r_quot = delta_calibration_radius / delta_radius;
  5068. float h_fac = 0.0;
  5069. h_fac = r_quot / (2.0 / 3.0);
  5070. h_fac = 1.0f / h_fac; // (2/3)/CR
  5071. return h_fac;
  5072. }
  5073. static float auto_tune_r() {
  5074. const float diff = 0.01;
  5075. float r_fac = 0.0,
  5076. z_pt[NPP + 1] = { 0.0 },
  5077. delta_e[ABC] = {0.0},
  5078. delta_r = {0.0},
  5079. delta_t[ABC] = {0.0};
  5080. delta_r = diff;
  5081. calc_kinematics_diff_probe_points(z_pt, delta_e, delta_r, delta_t);
  5082. r_fac = -(z_pt[__A] + z_pt[__B] + z_pt[__C] + z_pt[_BC] + z_pt[_CA] + z_pt[_AB]) / 6.0;
  5083. r_fac = diff / r_fac / 3.0; // 1/(3*delta_Z)
  5084. return r_fac;
  5085. }
  5086. static float auto_tune_a() {
  5087. const float diff = 0.01;
  5088. float a_fac = 0.0,
  5089. z_pt[NPP + 1] = { 0.0 },
  5090. delta_e[ABC] = {0.0},
  5091. delta_r = {0.0},
  5092. delta_t[ABC] = {0.0};
  5093. LOOP_XYZ(axis) {
  5094. LOOP_XYZ(axis_2) delta_t[axis_2] = 0.0;
  5095. delta_t[axis] = diff;
  5096. calc_kinematics_diff_probe_points(z_pt, delta_e, delta_r, delta_t);
  5097. a_fac += z_pt[uint8_t((axis * _4P_STEP) - _7P_STEP + NPP) % NPP + 1] / 6.0;
  5098. a_fac -= z_pt[uint8_t((axis * _4P_STEP) + 1 + _7P_STEP)] / 6.0;
  5099. }
  5100. a_fac = diff / a_fac / 3.0; // 1/(3*delta_Z)
  5101. return a_fac;
  5102. }
  5103. /**
  5104. * G33 - Delta '1-4-7-point' Auto-Calibration
  5105. * Calibrate height, z_offset, endstops, delta radius, and tower angles.
  5106. *
  5107. * Parameters:
  5108. *
  5109. * S Setup mode; disables probe protection
  5110. *
  5111. * Pn Number of probe points:
  5112. * P-1 Checks the z_offset with a center probe and paper test.
  5113. * P0 Normalizes calibration.
  5114. * P1 Calibrates height only with center probe.
  5115. * P2 Probe center and towers. Calibrate height, endstops and delta radius.
  5116. * P3 Probe all positions: center, towers and opposite towers. Calibrate all.
  5117. * P4-P10 Probe all positions at different intermediate locations and average them.
  5118. *
  5119. * T Don't calibrate tower angle corrections
  5120. *
  5121. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  5122. *
  5123. * Fn Force to run at least n iterations and take the best result
  5124. *
  5125. * Vn Verbose level:
  5126. * V0 Dry-run mode. Report settings and probe results. No calibration.
  5127. * V1 Report start and end settings only
  5128. * V2 Report settings at each iteration
  5129. * V3 Report settings and probe results
  5130. *
  5131. * E Engage the probe for each point
  5132. */
  5133. inline void gcode_G33() {
  5134. const bool set_up =
  5135. #if HAS_BED_PROBE
  5136. parser.seen('S');
  5137. #else
  5138. false;
  5139. #endif
  5140. const int8_t probe_points = set_up ? 2 : parser.intval('P', DELTA_CALIBRATION_DEFAULT_POINTS);
  5141. if (!WITHIN(probe_points, -1, 10)) {
  5142. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (-1 - 10).");
  5143. return;
  5144. }
  5145. const bool towers_set = !parser.seen('T');
  5146. const float calibration_precision = set_up ? Z_CLEARANCE_BETWEEN_PROBES / 5.0 : parser.floatval('C', 0.0);
  5147. if (calibration_precision < 0) {
  5148. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>=0).");
  5149. return;
  5150. }
  5151. const int8_t force_iterations = parser.intval('F', 0);
  5152. if (!WITHIN(force_iterations, 0, 30)) {
  5153. SERIAL_PROTOCOLLNPGM("?(F)orce iteration is implausible (0 - 30).");
  5154. return;
  5155. }
  5156. const int8_t verbose_level = parser.byteval('V', 1);
  5157. if (!WITHIN(verbose_level, 0, 3)) {
  5158. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0 - 3).");
  5159. return;
  5160. }
  5161. const bool stow_after_each = parser.seen('E');
  5162. if (set_up) {
  5163. delta_height = 999.99;
  5164. delta_radius = DELTA_PRINTABLE_RADIUS;
  5165. ZERO(delta_endstop_adj);
  5166. ZERO(delta_tower_angle_trim);
  5167. recalc_delta_settings();
  5168. }
  5169. const bool _0p_calibration = probe_points == 0,
  5170. _1p_calibration = probe_points == 1 || probe_points == -1,
  5171. _4p_calibration = probe_points == 2,
  5172. _4p_opposite_points = _4p_calibration && !towers_set,
  5173. _7p_9_center = probe_points >= 8,
  5174. _tower_results = (_4p_calibration && towers_set) || probe_points >= 3,
  5175. _opposite_results = (_4p_calibration && !towers_set) || probe_points >= 3,
  5176. _endstop_results = probe_points != 1 && probe_points != -1 && probe_points != 0,
  5177. _angle_results = probe_points >= 3 && towers_set;
  5178. static const char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  5179. int8_t iterations = 0;
  5180. float test_precision,
  5181. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  5182. zero_std_dev_min = zero_std_dev,
  5183. zero_std_dev_old = zero_std_dev,
  5184. h_factor,
  5185. r_factor,
  5186. a_factor,
  5187. e_old[ABC] = {
  5188. delta_endstop_adj[A_AXIS],
  5189. delta_endstop_adj[B_AXIS],
  5190. delta_endstop_adj[C_AXIS]
  5191. },
  5192. r_old = delta_radius,
  5193. h_old = delta_height,
  5194. a_old[ABC] = {
  5195. delta_tower_angle_trim[A_AXIS],
  5196. delta_tower_angle_trim[B_AXIS],
  5197. delta_tower_angle_trim[C_AXIS]
  5198. };
  5199. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  5200. if (!_1p_calibration && !_0p_calibration) { // test if the outer radius is reachable
  5201. LOOP_CAL_RAD(axis) {
  5202. const float a = RADIANS(210 + (360 / NPP) * (axis - 1)),
  5203. r = delta_calibration_radius;
  5204. if (!position_is_reachable(cos(a) * r, sin(a) * r)) {
  5205. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  5206. return;
  5207. }
  5208. }
  5209. }
  5210. // Report settings
  5211. const char *checkingac = PSTR("Checking... AC");
  5212. serialprintPGM(checkingac);
  5213. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  5214. if (set_up) SERIAL_PROTOCOLPGM(" (SET-UP)");
  5215. SERIAL_EOL();
  5216. lcd_setstatusPGM(checkingac);
  5217. print_calibration_settings(_endstop_results, _angle_results);
  5218. ac_setup(!_0p_calibration && !_1p_calibration);
  5219. if (!_0p_calibration) ac_home();
  5220. do { // start iterations
  5221. float z_at_pt[NPP + 1] = { 0.0 };
  5222. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  5223. iterations++;
  5224. // Probe the points
  5225. zero_std_dev_old = zero_std_dev;
  5226. if (!probe_calibration_points(z_at_pt, probe_points, towers_set, stow_after_each, set_up)) {
  5227. SERIAL_PROTOCOLLNPGM("Correct delta settings with M665 and M666");
  5228. return AC_CLEANUP();
  5229. }
  5230. zero_std_dev = std_dev_points(z_at_pt, _0p_calibration, _1p_calibration, _4p_calibration, _4p_opposite_points);
  5231. // Solve matrices
  5232. if ((zero_std_dev < test_precision || iterations <= force_iterations) && zero_std_dev > calibration_precision) {
  5233. #if !HAS_BED_PROBE
  5234. test_precision = 0.00; // forced end
  5235. #endif
  5236. if (zero_std_dev < zero_std_dev_min) {
  5237. // set roll-back point
  5238. COPY(e_old, delta_endstop_adj);
  5239. r_old = delta_radius;
  5240. h_old = delta_height;
  5241. COPY(a_old, delta_tower_angle_trim);
  5242. }
  5243. float e_delta[ABC] = { 0.0 },
  5244. r_delta = 0.0,
  5245. t_delta[ABC] = { 0.0 };
  5246. /**
  5247. * convergence matrices:
  5248. * see https://github.com/LVD-AC/Marlin-AC/tree/1.1.x-AC/documentation for
  5249. * - definition of the matrix scaling parameters
  5250. * - matrices for 4 and 7 point calibration
  5251. */
  5252. #define ZP(N,I) ((N) * z_at_pt[I] / 4.0) // 4.0 = divider to normalize to integers
  5253. #define Z12(I) ZP(12, I)
  5254. #define Z4(I) ZP(4, I)
  5255. #define Z2(I) ZP(2, I)
  5256. #define Z1(I) ZP(1, I)
  5257. #define Z0(I) ZP(0, I)
  5258. // calculate factors
  5259. const float cr_old = delta_calibration_radius;
  5260. if (_7p_9_center) delta_calibration_radius *= 0.9;
  5261. h_factor = auto_tune_h();
  5262. r_factor = auto_tune_r();
  5263. a_factor = auto_tune_a();
  5264. delta_calibration_radius = cr_old;
  5265. switch (probe_points) {
  5266. case -1:
  5267. #if HAS_BED_PROBE && ENABLED(ULTIPANEL)
  5268. zprobe_zoffset += probe_z_shift(z_at_pt[CEN]);
  5269. #endif
  5270. case 0:
  5271. test_precision = 0.00; // forced end
  5272. break;
  5273. case 1:
  5274. test_precision = 0.00; // forced end
  5275. LOOP_XYZ(axis) e_delta[axis] = +Z4(CEN);
  5276. break;
  5277. case 2:
  5278. if (towers_set) { // see 4 point calibration (towers) matrix
  5279. e_delta[A_AXIS] = (+Z4(__A) -Z2(__B) -Z2(__C)) * h_factor +Z4(CEN);
  5280. e_delta[B_AXIS] = (-Z2(__A) +Z4(__B) -Z2(__C)) * h_factor +Z4(CEN);
  5281. e_delta[C_AXIS] = (-Z2(__A) -Z2(__B) +Z4(__C)) * h_factor +Z4(CEN);
  5282. r_delta = (+Z4(__A) +Z4(__B) +Z4(__C) -Z12(CEN)) * r_factor;
  5283. }
  5284. else { // see 4 point calibration (opposites) matrix
  5285. e_delta[A_AXIS] = (-Z4(_BC) +Z2(_CA) +Z2(_AB)) * h_factor +Z4(CEN);
  5286. e_delta[B_AXIS] = (+Z2(_BC) -Z4(_CA) +Z2(_AB)) * h_factor +Z4(CEN);
  5287. e_delta[C_AXIS] = (+Z2(_BC) +Z2(_CA) -Z4(_AB)) * h_factor +Z4(CEN);
  5288. r_delta = (+Z4(_BC) +Z4(_CA) +Z4(_AB) -Z12(CEN)) * r_factor;
  5289. }
  5290. break;
  5291. default: // see 7 point calibration (towers & opposites) matrix
  5292. e_delta[A_AXIS] = (+Z2(__A) -Z1(__B) -Z1(__C) -Z2(_BC) +Z1(_CA) +Z1(_AB)) * h_factor +Z4(CEN);
  5293. e_delta[B_AXIS] = (-Z1(__A) +Z2(__B) -Z1(__C) +Z1(_BC) -Z2(_CA) +Z1(_AB)) * h_factor +Z4(CEN);
  5294. e_delta[C_AXIS] = (-Z1(__A) -Z1(__B) +Z2(__C) +Z1(_BC) +Z1(_CA) -Z2(_AB)) * h_factor +Z4(CEN);
  5295. r_delta = (+Z2(__A) +Z2(__B) +Z2(__C) +Z2(_BC) +Z2(_CA) +Z2(_AB) -Z12(CEN)) * r_factor;
  5296. if (towers_set) { // see 7 point tower angle calibration (towers & opposites) matrix
  5297. t_delta[A_AXIS] = (+Z0(__A) -Z4(__B) +Z4(__C) +Z0(_BC) -Z4(_CA) +Z4(_AB) +Z0(CEN)) * a_factor;
  5298. t_delta[B_AXIS] = (+Z4(__A) +Z0(__B) -Z4(__C) +Z4(_BC) +Z0(_CA) -Z4(_AB) +Z0(CEN)) * a_factor;
  5299. t_delta[C_AXIS] = (-Z4(__A) +Z4(__B) +Z0(__C) -Z4(_BC) +Z4(_CA) +Z0(_AB) +Z0(CEN)) * a_factor;
  5300. }
  5301. break;
  5302. }
  5303. LOOP_XYZ(axis) delta_endstop_adj[axis] += e_delta[axis];
  5304. delta_radius += r_delta;
  5305. LOOP_XYZ(axis) delta_tower_angle_trim[axis] += t_delta[axis];
  5306. }
  5307. else if (zero_std_dev >= test_precision) {
  5308. // roll back
  5309. COPY(delta_endstop_adj, e_old);
  5310. delta_radius = r_old;
  5311. delta_height = h_old;
  5312. COPY(delta_tower_angle_trim, a_old);
  5313. }
  5314. if (verbose_level != 0) { // !dry run
  5315. // normalise angles to least squares
  5316. if (_angle_results) {
  5317. float a_sum = 0.0;
  5318. LOOP_XYZ(axis) a_sum += delta_tower_angle_trim[axis];
  5319. LOOP_XYZ(axis) delta_tower_angle_trim[axis] -= a_sum / 3.0;
  5320. }
  5321. // adjust delta_height and endstops by the max amount
  5322. const float z_temp = MAX3(delta_endstop_adj[A_AXIS], delta_endstop_adj[B_AXIS], delta_endstop_adj[C_AXIS]);
  5323. delta_height -= z_temp;
  5324. LOOP_XYZ(axis) delta_endstop_adj[axis] -= z_temp;
  5325. }
  5326. recalc_delta_settings();
  5327. NOMORE(zero_std_dev_min, zero_std_dev);
  5328. // print report
  5329. if (verbose_level == 3)
  5330. print_calibration_results(z_at_pt, _tower_results, _opposite_results);
  5331. if (verbose_level != 0) { // !dry run
  5332. if ((zero_std_dev >= test_precision && iterations > force_iterations) || zero_std_dev <= calibration_precision) { // end iterations
  5333. SERIAL_PROTOCOLPGM("Calibration OK");
  5334. SERIAL_PROTOCOL_SP(32);
  5335. #if HAS_BED_PROBE
  5336. if (zero_std_dev >= test_precision && !_1p_calibration && !_0p_calibration)
  5337. SERIAL_PROTOCOLPGM("rolling back.");
  5338. else
  5339. #endif
  5340. {
  5341. SERIAL_PROTOCOLPGM("std dev:");
  5342. SERIAL_PROTOCOL_F(zero_std_dev_min, 3);
  5343. }
  5344. SERIAL_EOL();
  5345. char mess[21];
  5346. strcpy_P(mess, PSTR("Calibration sd:"));
  5347. if (zero_std_dev_min < 1)
  5348. sprintf_P(&mess[15], PSTR("0.%03i"), int(LROUND(zero_std_dev_min * 1000.0)));
  5349. else
  5350. sprintf_P(&mess[15], PSTR("%03i.x"), int(LROUND(zero_std_dev_min)));
  5351. lcd_setstatus(mess);
  5352. print_calibration_settings(_endstop_results, _angle_results);
  5353. serialprintPGM(save_message);
  5354. SERIAL_EOL();
  5355. }
  5356. else { // !end iterations
  5357. char mess[15];
  5358. if (iterations < 31)
  5359. sprintf_P(mess, PSTR("Iteration : %02i"), int(iterations));
  5360. else
  5361. strcpy_P(mess, PSTR("No convergence"));
  5362. SERIAL_PROTOCOL(mess);
  5363. SERIAL_PROTOCOL_SP(32);
  5364. SERIAL_PROTOCOLPGM("std dev:");
  5365. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  5366. SERIAL_EOL();
  5367. lcd_setstatus(mess);
  5368. if (verbose_level > 1)
  5369. print_calibration_settings(_endstop_results, _angle_results);
  5370. }
  5371. }
  5372. else { // dry run
  5373. const char *enddryrun = PSTR("End DRY-RUN");
  5374. serialprintPGM(enddryrun);
  5375. SERIAL_PROTOCOL_SP(35);
  5376. SERIAL_PROTOCOLPGM("std dev:");
  5377. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  5378. SERIAL_EOL();
  5379. char mess[21];
  5380. strcpy_P(mess, enddryrun);
  5381. strcpy_P(&mess[11], PSTR(" sd:"));
  5382. if (zero_std_dev < 1)
  5383. sprintf_P(&mess[15], PSTR("0.%03i"), int(LROUND(zero_std_dev * 1000.0)));
  5384. else
  5385. sprintf_P(&mess[15], PSTR("%03i.x"), int(LROUND(zero_std_dev)));
  5386. lcd_setstatus(mess);
  5387. }
  5388. ac_home();
  5389. }
  5390. while (((zero_std_dev < test_precision && iterations < 31) || iterations <= force_iterations) && zero_std_dev > calibration_precision);
  5391. AC_CLEANUP();
  5392. }
  5393. #endif // DELTA_AUTO_CALIBRATION
  5394. #if ENABLED(G38_PROBE_TARGET)
  5395. static bool G38_run_probe() {
  5396. bool G38_pass_fail = false;
  5397. #if MULTIPLE_PROBING > 1
  5398. // Get direction of move and retract
  5399. float retract_mm[XYZ];
  5400. LOOP_XYZ(i) {
  5401. float dist = destination[i] - current_position[i];
  5402. retract_mm[i] = ABS(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  5403. }
  5404. #endif
  5405. // Move until destination reached or target hit
  5406. planner.synchronize();
  5407. endstops.enable(true);
  5408. G38_move = true;
  5409. G38_endstop_hit = false;
  5410. prepare_move_to_destination();
  5411. planner.synchronize();
  5412. G38_move = false;
  5413. endstops.hit_on_purpose();
  5414. set_current_from_steppers_for_axis(ALL_AXES);
  5415. SYNC_PLAN_POSITION_KINEMATIC();
  5416. if (G38_endstop_hit) {
  5417. G38_pass_fail = true;
  5418. #if MULTIPLE_PROBING > 1
  5419. // Move away by the retract distance
  5420. set_destination_from_current();
  5421. LOOP_XYZ(i) destination[i] += retract_mm[i];
  5422. endstops.enable(false);
  5423. prepare_move_to_destination();
  5424. feedrate_mm_s /= 4;
  5425. // Bump the target more slowly
  5426. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  5427. planner.synchronize();
  5428. endstops.enable(true);
  5429. G38_move = true;
  5430. prepare_move_to_destination();
  5431. planner.synchronize();
  5432. G38_move = false;
  5433. set_current_from_steppers_for_axis(ALL_AXES);
  5434. SYNC_PLAN_POSITION_KINEMATIC();
  5435. #endif
  5436. }
  5437. endstops.hit_on_purpose();
  5438. endstops.not_homing();
  5439. return G38_pass_fail;
  5440. }
  5441. /**
  5442. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  5443. * G38.3 - probe toward workpiece, stop on contact
  5444. *
  5445. * Like G28 except uses Z min probe for all axes
  5446. */
  5447. inline void gcode_G38(bool is_38_2) {
  5448. // Get X Y Z E F
  5449. gcode_get_destination();
  5450. setup_for_endstop_or_probe_move();
  5451. // If any axis has enough movement, do the move
  5452. LOOP_XYZ(i)
  5453. if (ABS(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  5454. if (!parser.seenval('F')) feedrate_mm_s = homing_feedrate((AxisEnum)i);
  5455. // If G38.2 fails throw an error
  5456. if (!G38_run_probe() && is_38_2) {
  5457. SERIAL_ERROR_START();
  5458. SERIAL_ERRORLNPGM("Failed to reach target");
  5459. }
  5460. break;
  5461. }
  5462. clean_up_after_endstop_or_probe_move();
  5463. }
  5464. #endif // G38_PROBE_TARGET
  5465. #if HAS_MESH
  5466. /**
  5467. * G42: Move X & Y axes to mesh coordinates (I & J)
  5468. */
  5469. inline void gcode_G42() {
  5470. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  5471. if (axis_unhomed_error()) return;
  5472. #endif
  5473. if (IsRunning()) {
  5474. const bool hasI = parser.seenval('I');
  5475. const int8_t ix = hasI ? parser.value_int() : 0;
  5476. const bool hasJ = parser.seenval('J');
  5477. const int8_t iy = hasJ ? parser.value_int() : 0;
  5478. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  5479. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  5480. return;
  5481. }
  5482. set_destination_from_current();
  5483. if (hasI) destination[X_AXIS] = _GET_MESH_X(ix);
  5484. if (hasJ) destination[Y_AXIS] = _GET_MESH_Y(iy);
  5485. if (parser.boolval('P')) {
  5486. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  5487. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  5488. }
  5489. const float fval = parser.linearval('F');
  5490. if (fval > 0.0) feedrate_mm_s = MMM_TO_MMS(fval);
  5491. // SCARA kinematic has "safe" XY raw moves
  5492. #if IS_SCARA
  5493. prepare_uninterpolated_move_to_destination();
  5494. #else
  5495. prepare_move_to_destination();
  5496. #endif
  5497. }
  5498. }
  5499. #endif // HAS_MESH
  5500. /**
  5501. * G92: Set current position to given X Y Z E
  5502. */
  5503. inline void gcode_G92() {
  5504. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5505. switch (parser.subcode) {
  5506. case 1:
  5507. // Zero the G92 values and restore current position
  5508. #if !IS_SCARA
  5509. LOOP_XYZ(i) {
  5510. const float v = position_shift[i];
  5511. if (v) {
  5512. position_shift[i] = 0;
  5513. update_software_endstops((AxisEnum)i);
  5514. }
  5515. }
  5516. #endif // Not SCARA
  5517. return;
  5518. }
  5519. #endif
  5520. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5521. #define IS_G92_0 (parser.subcode == 0)
  5522. #else
  5523. #define IS_G92_0 true
  5524. #endif
  5525. bool didE = false;
  5526. #if IS_SCARA || !HAS_POSITION_SHIFT || ENABLED(HANGPRINTER)
  5527. bool didXYZ = false;
  5528. #else
  5529. constexpr bool didXYZ = false;
  5530. #endif
  5531. if (IS_G92_0) LOOP_XYZE(i) {
  5532. if (parser.seenval(axis_codes[i])) {
  5533. const float l = parser.value_axis_units((AxisEnum)i),
  5534. v = i == E_CART ? l : LOGICAL_TO_NATIVE(l, i),
  5535. d = v - current_position[i];
  5536. if (!NEAR_ZERO(d)
  5537. #if ENABLED(HANGPRINTER)
  5538. || true // Hangprinter needs to update its line lengths whether current_position changed or not
  5539. #endif
  5540. ) {
  5541. #if IS_SCARA || !HAS_POSITION_SHIFT || ENABLED(HANGPRINTER)
  5542. if (i == E_CART) didE = true; else didXYZ = true;
  5543. current_position[i] = v; // Without workspaces revert to Marlin 1.0 behavior
  5544. #elif HAS_POSITION_SHIFT
  5545. if (i == E_CART) {
  5546. didE = true;
  5547. current_position[E_CART] = v; // When using coordinate spaces, only E is set directly
  5548. }
  5549. else {
  5550. position_shift[i] += d; // Other axes simply offset the coordinate space
  5551. update_software_endstops((AxisEnum)i);
  5552. }
  5553. #endif
  5554. }
  5555. }
  5556. }
  5557. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5558. // Apply workspace offset to the active coordinate system
  5559. if (WITHIN(active_coordinate_system, 0, MAX_COORDINATE_SYSTEMS - 1))
  5560. COPY(coordinate_system[active_coordinate_system], position_shift);
  5561. #endif
  5562. // Update planner/steppers only if the native coordinates changed
  5563. if (didXYZ) SYNC_PLAN_POSITION_KINEMATIC();
  5564. else if (didE) sync_plan_position_e();
  5565. report_current_position();
  5566. }
  5567. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  5568. /**
  5569. * G95: Set torque mode
  5570. */
  5571. inline void gcode_G95() {
  5572. i2cFloat torques[NUM_AXIS]; // Assumes 4-byte floats here and in Mechaduino firmware
  5573. LOOP_NUM_AXIS(i)
  5574. torques[i].fval = parser.floatval(RAW_AXIS_CODES(i), 999.9); // 999.9 chosen to satisfy fabs(999.9) > 255.0
  5575. // 0x5f == 95
  5576. #define G95_SEND(LETTER) do { \
  5577. if (fabs(torques[_AXIS(LETTER)].fval) < 255.0){ \
  5578. torques[_AXIS(LETTER)].fval = -fabs(torques[_AXIS(LETTER)].fval); \
  5579. if(!INVERT_##LETTER##_DIR) torques[_AXIS(LETTER)].fval = -torques[_AXIS(LETTER)].fval; \
  5580. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5581. i2c.reset(); \
  5582. i2c.addbyte(0x5f); \
  5583. i2c.addbytes(torques[_AXIS(LETTER)].bval, sizeof(float)); \
  5584. i2c.send(); \
  5585. }} while(0)
  5586. #if ENABLED(HANGPRINTER)
  5587. #if ENABLED(A_IS_MECHADUINO)
  5588. G95_SEND(A);
  5589. #endif
  5590. #if ENABLED(B_IS_MECHADUINO)
  5591. G95_SEND(B);
  5592. #endif
  5593. #if ENABLED(C_IS_MECHADUINO)
  5594. G95_SEND(C);
  5595. #endif
  5596. #if ENABLED(D_IS_MECHADUINO)
  5597. G95_SEND(D);
  5598. #endif
  5599. #else
  5600. #if ENABLED(X_IS_MECHADUINO)
  5601. G95_SEND(X);
  5602. #endif
  5603. #if ENABLED(Y_IS_MECHADUINO)
  5604. G95_SEND(Y);
  5605. #endif
  5606. #if ENABLED(Z_IS_MECHADUINO)
  5607. G95_SEND(Z);
  5608. #endif
  5609. #endif
  5610. #if ENABLED(E_IS_MECHADUINO)
  5611. G95_SEND(E);
  5612. #endif
  5613. }
  5614. /**
  5615. * G96: Mark encoder reference point
  5616. */
  5617. inline void gcode_G96() {
  5618. bool mark[NUM_AXIS] = { false };
  5619. if (!parser.seen_any())
  5620. LOOP_NUM_AXIS(i)
  5621. mark[i] = true;
  5622. else
  5623. LOOP_NUM_AXIS(i)
  5624. if (parser.seen(RAW_AXIS_CODES(i)))
  5625. mark[i] = true;
  5626. // 0x60 == 96
  5627. #define G96_SEND(LETTER) do {\
  5628. if (mark[LETTER##_AXIS]){ \
  5629. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5630. i2c.reset(); \
  5631. i2c.addbyte(0x60); \
  5632. i2c.send(); \
  5633. }} while(0)
  5634. #if ENABLED(HANGPRINTER)
  5635. #if ENABLED(A_IS_MECHADUINO)
  5636. G96_SEND(A);
  5637. #endif
  5638. #if ENABLED(B_IS_MECHADUINO)
  5639. G96_SEND(B);
  5640. #endif
  5641. #if ENABLED(C_IS_MECHADUINO)
  5642. G96_SEND(C);
  5643. #endif
  5644. #if ENABLED(D_IS_MECHADUINO)
  5645. G96_SEND(D);
  5646. #endif
  5647. #else
  5648. #if ENABLED(X_IS_MECHADUINO)
  5649. G96_SEND(X);
  5650. #endif
  5651. #if ENABLED(Y_IS_MECHADUINO)
  5652. G96_SEND(Y);
  5653. #endif
  5654. #if ENABLED(Z_IS_MECHADUINO)
  5655. G96_SEND(Z);
  5656. #endif
  5657. #endif
  5658. #if ENABLED(E_IS_MECHADUINO)
  5659. G96_SEND(E); // E ref point not used by any other commands (Feb 7, 2018)
  5660. #endif
  5661. }
  5662. float ang_to_mm(float ang, const AxisEnum axis) {
  5663. const float abs_step_in_origin =
  5664. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  5665. planner.k0[axis] * (SQRT(planner.k1[axis] + planner.k2[axis] * line_lengths_origin[axis]) - planner.sqrtk1[axis])
  5666. #else
  5667. line_lengths_origin[axis] * planner.axis_steps_per_mm[axis]
  5668. #endif
  5669. ;
  5670. const float c = abs_step_in_origin + ang * float(STEPS_PER_MOTOR_REVOLUTION) / 360.0; // current step count
  5671. return
  5672. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  5673. // Inverse function found in planner.cpp, where target[AXIS_A] is calculated
  5674. ((c / planner.k0[axis] + planner.sqrtk1[axis]) * (c / planner.k0[axis] + planner.sqrtk1[axis]) - planner.k1[axis]) / planner.k2[axis] - line_lengths_origin[axis]
  5675. #else
  5676. c / planner.axis_steps_per_mm[axis] - line_lengths_origin[axis]
  5677. #endif
  5678. ;
  5679. }
  5680. void report_axis_position_from_encoder_data() {
  5681. i2cFloat ang;
  5682. #define M114_S1_RECEIVE(LETTER) do { \
  5683. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5684. i2c.request(sizeof(float)); \
  5685. i2c.capture(ang.bval, sizeof(float)); \
  5686. if(LETTER##_INVERT_REPORTED_ANGLE == INVERT_##LETTER##_DIR) ang.fval = -ang.fval; \
  5687. SERIAL_PROTOCOL(ang_to_mm(ang.fval, LETTER##_AXIS)); \
  5688. } while(0)
  5689. SERIAL_CHAR('[');
  5690. #if ENABLED(HANGPRINTER)
  5691. #if ENABLED(A_IS_MECHADUINO)
  5692. M114_S1_RECEIVE(A);
  5693. #endif
  5694. #if ENABLED(B_IS_MECHADUINO)
  5695. SERIAL_PROTOCOLPGM(", ");
  5696. M114_S1_RECEIVE(B);
  5697. #endif
  5698. #if ENABLED(C_IS_MECHADUINO)
  5699. SERIAL_PROTOCOLPGM(", ");
  5700. M114_S1_RECEIVE(C);
  5701. #endif
  5702. #if ENABLED(D_IS_MECHADUINO)
  5703. SERIAL_PROTOCOLPGM(", ");
  5704. M114_S1_RECEIVE(D);
  5705. #endif
  5706. #else
  5707. #if ENABLED(X_IS_MECHADUINO)
  5708. M114_S1_RECEIVE(X);
  5709. #endif
  5710. #if ENABLED(Y_IS_MECHADUINO)
  5711. SERIAL_PROTOCOLPGM(", ");
  5712. M114_S1_RECEIVE(Y);
  5713. #endif
  5714. #if ENABLED(Z_IS_MECHADUINO)
  5715. SERIAL_PROTOCOLPGM(", ");
  5716. M114_S1_RECEIVE(Z);
  5717. #endif
  5718. #endif
  5719. SERIAL_CHAR(']');
  5720. SERIAL_EOL();
  5721. }
  5722. #endif // MECHADUINO_I2C_COMMANDS
  5723. void report_xyz_from_stepper_position() {
  5724. get_cartesian_from_steppers(); // writes to cartes[XYZ]
  5725. SERIAL_CHAR('[');
  5726. SERIAL_PROTOCOL(cartes[X_AXIS]);
  5727. SERIAL_PROTOCOLPAIR(", ", cartes[Y_AXIS]);
  5728. SERIAL_PROTOCOLPAIR(", ", cartes[Z_AXIS]);
  5729. SERIAL_CHAR(']');
  5730. SERIAL_EOL();
  5731. }
  5732. #if HAS_RESUME_CONTINUE
  5733. /**
  5734. * M0: Unconditional stop - Wait for user button press on LCD
  5735. * M1: Conditional stop - Wait for user button press on LCD
  5736. */
  5737. inline void gcode_M0_M1() {
  5738. const char * const args = parser.string_arg;
  5739. millis_t ms = 0;
  5740. bool hasP = false, hasS = false;
  5741. if (parser.seenval('P')) {
  5742. ms = parser.value_millis(); // milliseconds to wait
  5743. hasP = ms > 0;
  5744. }
  5745. if (parser.seenval('S')) {
  5746. ms = parser.value_millis_from_seconds(); // seconds to wait
  5747. hasS = ms > 0;
  5748. }
  5749. const bool has_message = !hasP && !hasS && args && *args;
  5750. planner.synchronize();
  5751. #if ENABLED(ULTIPANEL)
  5752. if (has_message)
  5753. lcd_setstatus(args, true);
  5754. else {
  5755. LCD_MESSAGEPGM(MSG_USERWAIT);
  5756. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  5757. dontExpireStatus();
  5758. #endif
  5759. }
  5760. #else
  5761. if (has_message) {
  5762. SERIAL_ECHO_START();
  5763. SERIAL_ECHOLN(args);
  5764. }
  5765. #endif
  5766. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5767. wait_for_user = true;
  5768. if (ms > 0) {
  5769. ms += millis(); // wait until this time for a click
  5770. while (PENDING(millis(), ms) && wait_for_user) idle();
  5771. }
  5772. else
  5773. while (wait_for_user) idle();
  5774. #if ENABLED(PRINTER_EVENT_LEDS) && ENABLED(SDSUPPORT)
  5775. if (lights_off_after_print) {
  5776. leds.set_off();
  5777. lights_off_after_print = false;
  5778. }
  5779. #endif
  5780. lcd_reset_status();
  5781. wait_for_user = false;
  5782. KEEPALIVE_STATE(IN_HANDLER);
  5783. }
  5784. #endif // HAS_RESUME_CONTINUE
  5785. #if ENABLED(SPINDLE_LASER_ENABLE)
  5786. /**
  5787. * M3: Spindle Clockwise
  5788. * M4: Spindle Counter-clockwise
  5789. *
  5790. * S0 turns off spindle.
  5791. *
  5792. * If no speed PWM output is defined then M3/M4 just turns it on.
  5793. *
  5794. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  5795. * Hardware PWM is required. ISRs are too slow.
  5796. *
  5797. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  5798. * No other settings give a PWM signal that goes from 0 to 5 volts.
  5799. *
  5800. * The system automatically sets WGM to Mode 1, so no special
  5801. * initialization is needed.
  5802. *
  5803. * WGM bits for timer 2 are automatically set by the system to
  5804. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  5805. * No special initialization is needed.
  5806. *
  5807. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  5808. * factors for timers 2, 3, 4, and 5 are acceptable.
  5809. *
  5810. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  5811. * the spindle/laser during power-up or when connecting to the host
  5812. * (usually goes through a reset which sets all I/O pins to tri-state)
  5813. *
  5814. * PWM duty cycle goes from 0 (off) to 255 (always on).
  5815. */
  5816. // Wait for spindle to come up to speed
  5817. inline void delay_for_power_up() { dwell(SPINDLE_LASER_POWERUP_DELAY); }
  5818. // Wait for spindle to stop turning
  5819. inline void delay_for_power_down() { dwell(SPINDLE_LASER_POWERDOWN_DELAY); }
  5820. /**
  5821. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  5822. *
  5823. * it accepts inputs of 0-255
  5824. */
  5825. inline void ocr_val_mode() {
  5826. uint8_t spindle_laser_power = parser.value_byte();
  5827. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  5828. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  5829. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  5830. }
  5831. inline void gcode_M3_M4(bool is_M3) {
  5832. planner.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  5833. #if SPINDLE_DIR_CHANGE
  5834. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  5835. if (SPINDLE_STOP_ON_DIR_CHANGE \
  5836. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  5837. && READ(SPINDLE_DIR_PIN) != rotation_dir
  5838. ) {
  5839. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  5840. delay_for_power_down();
  5841. }
  5842. WRITE(SPINDLE_DIR_PIN, rotation_dir);
  5843. #endif
  5844. /**
  5845. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  5846. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  5847. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  5848. */
  5849. #if ENABLED(SPINDLE_LASER_PWM)
  5850. if (parser.seen('O')) ocr_val_mode();
  5851. else {
  5852. const float spindle_laser_power = parser.floatval('S');
  5853. if (spindle_laser_power == 0) {
  5854. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  5855. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // only write low byte
  5856. delay_for_power_down();
  5857. }
  5858. else {
  5859. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  5860. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  5861. if (spindle_laser_power <= SPEED_POWER_MIN)
  5862. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // minimum setting
  5863. if (spindle_laser_power >= SPEED_POWER_MAX)
  5864. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // limit to max RPM
  5865. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  5866. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  5867. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  5868. delay_for_power_up();
  5869. }
  5870. }
  5871. #else
  5872. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  5873. delay_for_power_up();
  5874. #endif
  5875. }
  5876. /**
  5877. * M5 turn off spindle
  5878. */
  5879. inline void gcode_M5() {
  5880. planner.synchronize();
  5881. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  5882. #if ENABLED(SPINDLE_LASER_PWM)
  5883. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0);
  5884. #endif
  5885. delay_for_power_down();
  5886. }
  5887. #endif // SPINDLE_LASER_ENABLE
  5888. /**
  5889. * M17: Enable power on all stepper motors
  5890. */
  5891. inline void gcode_M17() {
  5892. LCD_MESSAGEPGM(MSG_NO_MOVE);
  5893. enable_all_steppers();
  5894. }
  5895. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  5896. void do_pause_e_move(const float &length, const float &fr) {
  5897. set_destination_from_current();
  5898. destination[E_CART] += length / planner.e_factor[active_extruder];
  5899. planner.buffer_line_kinematic(destination, fr, active_extruder);
  5900. set_current_from_destination();
  5901. planner.synchronize();
  5902. }
  5903. static float resume_position[XYZE];
  5904. int8_t did_pause_print = 0;
  5905. #if HAS_BUZZER
  5906. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  5907. static millis_t next_buzz = 0;
  5908. static int8_t runout_beep = 0;
  5909. if (init) next_buzz = runout_beep = 0;
  5910. const millis_t ms = millis();
  5911. if (ELAPSED(ms, next_buzz)) {
  5912. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  5913. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 1000 : 500);
  5914. BUZZ(50, 880 - (runout_beep & 1) * 220);
  5915. runout_beep++;
  5916. }
  5917. }
  5918. }
  5919. #endif
  5920. /**
  5921. * Ensure a safe temperature for extrusion
  5922. *
  5923. * - Fail if the TARGET temperature is too low
  5924. * - Display LCD placard with temperature status
  5925. * - Return when heating is done or aborted
  5926. *
  5927. * Returns 'true' if heating was completed, 'false' for abort
  5928. */
  5929. static bool ensure_safe_temperature(const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT) {
  5930. #if ENABLED(PREVENT_COLD_EXTRUSION)
  5931. if (!DEBUGGING(DRYRUN) && thermalManager.targetTooColdToExtrude(active_extruder)) {
  5932. SERIAL_ERROR_START();
  5933. SERIAL_ERRORLNPGM(MSG_HOTEND_TOO_COLD);
  5934. return false;
  5935. }
  5936. #endif
  5937. #if ENABLED(ULTIPANEL)
  5938. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT, mode);
  5939. #else
  5940. UNUSED(mode);
  5941. #endif
  5942. wait_for_heatup = true; // M108 will clear this
  5943. while (wait_for_heatup && thermalManager.wait_for_heating(active_extruder)) idle();
  5944. const bool status = wait_for_heatup;
  5945. wait_for_heatup = false;
  5946. return status;
  5947. }
  5948. /**
  5949. * Load filament into the hotend
  5950. *
  5951. * - Fail if the a safe temperature was not reached
  5952. * - If pausing for confirmation, wait for a click or M108
  5953. * - Show "wait for load" placard
  5954. * - Load and purge filament
  5955. * - Show "Purge more" / "Continue" menu
  5956. * - Return when "Continue" is selected
  5957. *
  5958. * Returns 'true' if load was completed, 'false' for abort
  5959. */
  5960. static bool load_filament(const float &slow_load_length=0, const float &fast_load_length=0, const float &purge_length=0, const int8_t max_beep_count=0,
  5961. const bool show_lcd=false, const bool pause_for_user=false,
  5962. const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT
  5963. ) {
  5964. #if DISABLED(ULTIPANEL)
  5965. UNUSED(show_lcd);
  5966. #endif
  5967. if (!ensure_safe_temperature(mode)) {
  5968. #if ENABLED(ULTIPANEL)
  5969. if (show_lcd) // Show status screen
  5970. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  5971. #endif
  5972. return false;
  5973. }
  5974. if (pause_for_user) {
  5975. #if ENABLED(ULTIPANEL)
  5976. if (show_lcd) // Show "insert filament"
  5977. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT, mode);
  5978. #endif
  5979. SERIAL_ECHO_START();
  5980. SERIAL_ECHOLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  5981. #if HAS_BUZZER
  5982. filament_change_beep(max_beep_count, true);
  5983. #else
  5984. UNUSED(max_beep_count);
  5985. #endif
  5986. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5987. wait_for_user = true; // LCD click or M108 will clear this
  5988. while (wait_for_user) {
  5989. #if HAS_BUZZER
  5990. filament_change_beep(max_beep_count);
  5991. #endif
  5992. idle(true);
  5993. }
  5994. KEEPALIVE_STATE(IN_HANDLER);
  5995. }
  5996. #if ENABLED(ULTIPANEL)
  5997. if (show_lcd) // Show "wait for load" message
  5998. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD, mode);
  5999. #endif
  6000. // Slow Load filament
  6001. if (slow_load_length) do_pause_e_move(slow_load_length, FILAMENT_CHANGE_SLOW_LOAD_FEEDRATE);
  6002. // Fast Load Filament
  6003. if (fast_load_length) {
  6004. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6005. const float saved_acceleration = planner.retract_acceleration;
  6006. planner.retract_acceleration = FILAMENT_CHANGE_FAST_LOAD_ACCEL;
  6007. #endif
  6008. do_pause_e_move(fast_load_length, FILAMENT_CHANGE_FAST_LOAD_FEEDRATE);
  6009. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6010. planner.retract_acceleration = saved_acceleration;
  6011. #endif
  6012. }
  6013. #if ENABLED(ADVANCED_PAUSE_CONTINUOUS_PURGE)
  6014. #if ENABLED(ULTIPANEL)
  6015. if (show_lcd)
  6016. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CONTINUOUS_PURGE);
  6017. #endif
  6018. wait_for_user = true;
  6019. for (float purge_count = purge_length; purge_count > 0 && wait_for_user; --purge_count)
  6020. do_pause_e_move(1, ADVANCED_PAUSE_PURGE_FEEDRATE);
  6021. wait_for_user = false;
  6022. #else
  6023. do {
  6024. if (purge_length > 0) {
  6025. // "Wait for filament purge"
  6026. #if ENABLED(ULTIPANEL)
  6027. if (show_lcd)
  6028. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_PURGE, mode);
  6029. #endif
  6030. // Extrude filament to get into hotend
  6031. do_pause_e_move(purge_length, ADVANCED_PAUSE_PURGE_FEEDRATE);
  6032. }
  6033. // Show "Purge More" / "Resume" menu and wait for reply
  6034. #if ENABLED(ULTIPANEL)
  6035. if (show_lcd) {
  6036. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6037. wait_for_user = false;
  6038. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION, mode);
  6039. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  6040. KEEPALIVE_STATE(IN_HANDLER);
  6041. }
  6042. #endif
  6043. // Keep looping if "Purge More" was selected
  6044. } while (
  6045. #if ENABLED(ULTIPANEL)
  6046. show_lcd && advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE
  6047. #else
  6048. 0
  6049. #endif
  6050. );
  6051. #endif
  6052. return true;
  6053. }
  6054. /**
  6055. * Unload filament from the hotend
  6056. *
  6057. * - Fail if the a safe temperature was not reached
  6058. * - Show "wait for unload" placard
  6059. * - Retract, pause, then unload filament
  6060. * - Disable E stepper (on most machines)
  6061. *
  6062. * Returns 'true' if unload was completed, 'false' for abort
  6063. */
  6064. static bool unload_filament(const float &unload_length, const bool show_lcd=false,
  6065. const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT
  6066. ) {
  6067. if (!ensure_safe_temperature(mode)) {
  6068. #if ENABLED(ULTIPANEL)
  6069. if (show_lcd) // Show status screen
  6070. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6071. #endif
  6072. return false;
  6073. }
  6074. #if DISABLED(ULTIPANEL)
  6075. UNUSED(show_lcd);
  6076. #else
  6077. if (show_lcd)
  6078. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD, mode);
  6079. #endif
  6080. // Retract filament
  6081. do_pause_e_move(-FILAMENT_UNLOAD_RETRACT_LENGTH, PAUSE_PARK_RETRACT_FEEDRATE);
  6082. // Wait for filament to cool
  6083. safe_delay(FILAMENT_UNLOAD_DELAY);
  6084. // Quickly purge
  6085. do_pause_e_move(FILAMENT_UNLOAD_RETRACT_LENGTH + FILAMENT_UNLOAD_PURGE_LENGTH, planner.max_feedrate_mm_s[E_AXIS]);
  6086. // Unload filament
  6087. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6088. const float saved_acceleration = planner.retract_acceleration;
  6089. planner.retract_acceleration = FILAMENT_CHANGE_UNLOAD_ACCEL;
  6090. #endif
  6091. do_pause_e_move(unload_length, FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  6092. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6093. planner.retract_acceleration = saved_acceleration;
  6094. #endif
  6095. // Disable extruders steppers for manual filament changing (only on boards that have separate ENABLE_PINS)
  6096. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN
  6097. disable_e_stepper(active_extruder);
  6098. safe_delay(100);
  6099. #endif
  6100. return true;
  6101. }
  6102. /**
  6103. * Pause procedure
  6104. *
  6105. * - Abort if already paused
  6106. * - Send host action for pause, if configured
  6107. * - Abort if TARGET temperature is too low
  6108. * - Display "wait for start of filament change" (if a length was specified)
  6109. * - Initial retract, if current temperature is hot enough
  6110. * - Park the nozzle at the given position
  6111. * - Call unload_filament (if a length was specified)
  6112. *
  6113. * Returns 'true' if pause was completed, 'false' for abort
  6114. */
  6115. static bool pause_print(const float &retract, const point_t &park_point, const float &unload_length=0, const bool show_lcd=false) {
  6116. if (did_pause_print) return false; // already paused
  6117. #ifdef ACTION_ON_PAUSE
  6118. SERIAL_ECHOLNPGM("//action:" ACTION_ON_PAUSE);
  6119. #endif
  6120. if (!DEBUGGING(DRYRUN) && unload_length && thermalManager.targetTooColdToExtrude(active_extruder)) {
  6121. SERIAL_ERROR_START();
  6122. SERIAL_ERRORLNPGM(MSG_HOTEND_TOO_COLD);
  6123. #if ENABLED(ULTIPANEL)
  6124. if (show_lcd) // Show status screen
  6125. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6126. LCD_MESSAGEPGM(MSG_M600_TOO_COLD);
  6127. #endif
  6128. return false; // unable to reach safe temperature
  6129. }
  6130. // Indicate that the printer is paused
  6131. ++did_pause_print;
  6132. // Pause the print job and timer
  6133. #if ENABLED(SDSUPPORT)
  6134. if (card.sdprinting) {
  6135. card.pauseSDPrint();
  6136. ++did_pause_print; // Indicate SD pause also
  6137. }
  6138. #endif
  6139. print_job_timer.pause();
  6140. // Save current position
  6141. COPY(resume_position, current_position);
  6142. // Wait for synchronize steppers
  6143. planner.synchronize();
  6144. // Initial retract before move to filament change position
  6145. if (retract && thermalManager.hotEnoughToExtrude(active_extruder))
  6146. do_pause_e_move(retract, PAUSE_PARK_RETRACT_FEEDRATE);
  6147. // Park the nozzle by moving up by z_lift and then moving to (x_pos, y_pos)
  6148. if (!axis_unhomed_error())
  6149. Nozzle::park(2, park_point);
  6150. // Unload the filament
  6151. if (unload_length)
  6152. unload_filament(unload_length, show_lcd);
  6153. return true;
  6154. }
  6155. /**
  6156. * - Show "Insert filament and press button to continue"
  6157. * - Wait for a click before returning
  6158. * - Heaters can time out, reheated before accepting a click
  6159. *
  6160. * Used by M125 and M600
  6161. */
  6162. static void wait_for_filament_reload(const int8_t max_beep_count=0) {
  6163. bool nozzle_timed_out = false;
  6164. #if ENABLED(ULTIPANEL)
  6165. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  6166. #endif
  6167. SERIAL_ECHO_START();
  6168. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  6169. #if HAS_BUZZER
  6170. filament_change_beep(max_beep_count, true);
  6171. #endif
  6172. // Start the heater idle timers
  6173. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  6174. HOTEND_LOOP()
  6175. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  6176. // Wait for filament insert by user and press button
  6177. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6178. wait_for_user = true; // LCD click or M108 will clear this
  6179. while (wait_for_user) {
  6180. #if HAS_BUZZER
  6181. filament_change_beep(max_beep_count);
  6182. #endif
  6183. // If the nozzle has timed out, wait for the user to press the button to re-heat the nozzle, then
  6184. // re-heat the nozzle, re-show the insert screen, restart the idle timers, and start over
  6185. if (!nozzle_timed_out)
  6186. HOTEND_LOOP()
  6187. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  6188. if (nozzle_timed_out) {
  6189. #if ENABLED(ULTIPANEL)
  6190. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  6191. #endif
  6192. SERIAL_ECHO_START();
  6193. #if ENABLED(ULTIPANEL) && ENABLED(EMERGENCY_PARSER)
  6194. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT);
  6195. #elif ENABLED(EMERGENCY_PARSER)
  6196. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT_M108);
  6197. #else
  6198. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT_LCD);
  6199. #endif
  6200. // Wait for LCD click or M108
  6201. while (wait_for_user) idle(true);
  6202. // Re-enable the heaters if they timed out
  6203. HOTEND_LOOP() thermalManager.reset_heater_idle_timer(e);
  6204. // Wait for the heaters to reach the target temperatures
  6205. ensure_safe_temperature();
  6206. #if ENABLED(ULTIPANEL)
  6207. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  6208. #endif
  6209. SERIAL_ECHO_START();
  6210. #if ENABLED(ULTIPANEL) && ENABLED(EMERGENCY_PARSER)
  6211. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  6212. #elif ENABLED(EMERGENCY_PARSER)
  6213. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT_M108);
  6214. #else
  6215. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT_LCD);
  6216. #endif
  6217. // Start the heater idle timers
  6218. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  6219. HOTEND_LOOP()
  6220. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  6221. wait_for_user = true; // Wait for user to load filament
  6222. nozzle_timed_out = false;
  6223. #if HAS_BUZZER
  6224. filament_change_beep(max_beep_count, true);
  6225. #endif
  6226. }
  6227. idle(true);
  6228. }
  6229. KEEPALIVE_STATE(IN_HANDLER);
  6230. }
  6231. /**
  6232. * Resume or Start print procedure
  6233. *
  6234. * - Abort if not paused
  6235. * - Reset heater idle timers
  6236. * - Load filament if specified, but only if:
  6237. * - a nozzle timed out, or
  6238. * - the nozzle is already heated.
  6239. * - Display "wait for print to resume"
  6240. * - Re-prime the nozzle...
  6241. * - FWRETRACT: Recover/prime from the prior G10.
  6242. * - !FWRETRACT: Retract by resume_position[E], if negative.
  6243. * Not sure how this logic comes into use.
  6244. * - Move the nozzle back to resume_position
  6245. * - Sync the planner E to resume_position[E]
  6246. * - Send host action for resume, if configured
  6247. * - Resume the current SD print job, if any
  6248. */
  6249. static void resume_print(const float &slow_load_length=0, const float &fast_load_length=0, const float &purge_length=ADVANCED_PAUSE_PURGE_LENGTH, const int8_t max_beep_count=0) {
  6250. if (!did_pause_print) return;
  6251. // Re-enable the heaters if they timed out
  6252. bool nozzle_timed_out = false;
  6253. HOTEND_LOOP() {
  6254. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  6255. thermalManager.reset_heater_idle_timer(e);
  6256. }
  6257. if (nozzle_timed_out || thermalManager.hotEnoughToExtrude(active_extruder)) {
  6258. // Load the new filament
  6259. load_filament(slow_load_length, fast_load_length, purge_length, max_beep_count, true, nozzle_timed_out);
  6260. }
  6261. #if ENABLED(ULTIPANEL)
  6262. // "Wait for print to resume"
  6263. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  6264. #endif
  6265. // Intelligent resuming
  6266. #if ENABLED(FWRETRACT)
  6267. // If retracted before goto pause
  6268. if (fwretract.retracted[active_extruder])
  6269. do_pause_e_move(-fwretract.retract_length, fwretract.retract_feedrate_mm_s);
  6270. #endif
  6271. // If resume_position is negative
  6272. if (resume_position[E_CART] < 0) do_pause_e_move(resume_position[E_CART], PAUSE_PARK_RETRACT_FEEDRATE);
  6273. // Move XY to starting position, then Z
  6274. do_blocking_move_to_xy(resume_position[X_AXIS], resume_position[Y_AXIS], NOZZLE_PARK_XY_FEEDRATE);
  6275. // Set Z_AXIS to saved position
  6276. do_blocking_move_to_z(resume_position[Z_AXIS], NOZZLE_PARK_Z_FEEDRATE);
  6277. // Now all extrusion positions are resumed and ready to be confirmed
  6278. // Set extruder to saved position
  6279. planner.set_e_position_mm((destination[E_CART] = current_position[E_CART] = resume_position[E_CART]));
  6280. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6281. runout.reset();
  6282. #endif
  6283. #if ENABLED(ULTIPANEL)
  6284. // Show status screen
  6285. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6286. #endif
  6287. #ifdef ACTION_ON_RESUME
  6288. SERIAL_ECHOLNPGM("//action:" ACTION_ON_RESUME);
  6289. #endif
  6290. --did_pause_print;
  6291. #if ENABLED(SDSUPPORT)
  6292. if (did_pause_print) {
  6293. card.startFileprint();
  6294. --did_pause_print;
  6295. }
  6296. #endif
  6297. }
  6298. #endif // ADVANCED_PAUSE_FEATURE
  6299. #if ENABLED(SDSUPPORT)
  6300. /**
  6301. * M20: List SD card to serial output
  6302. */
  6303. inline void gcode_M20() {
  6304. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  6305. card.ls();
  6306. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  6307. }
  6308. /**
  6309. * M21: Init SD Card
  6310. */
  6311. inline void gcode_M21() { card.initsd(); }
  6312. /**
  6313. * M22: Release SD Card
  6314. */
  6315. inline void gcode_M22() { card.release(); }
  6316. /**
  6317. * M23: Open a file
  6318. */
  6319. inline void gcode_M23() {
  6320. #if ENABLED(POWER_LOSS_RECOVERY)
  6321. card.removeJobRecoveryFile();
  6322. #endif
  6323. // Simplify3D includes the size, so zero out all spaces (#7227)
  6324. for (char *fn = parser.string_arg; *fn; ++fn) if (*fn == ' ') *fn = '\0';
  6325. card.openFile(parser.string_arg, true);
  6326. }
  6327. /**
  6328. * M24: Start or Resume SD Print
  6329. */
  6330. inline void gcode_M24() {
  6331. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6332. resume_print();
  6333. #endif
  6334. #if ENABLED(POWER_LOSS_RECOVERY)
  6335. if (parser.seenval('S')) card.setIndex(parser.value_long());
  6336. #endif
  6337. card.startFileprint();
  6338. #if ENABLED(POWER_LOSS_RECOVERY)
  6339. if (parser.seenval('T'))
  6340. print_job_timer.resume(parser.value_long());
  6341. else
  6342. #endif
  6343. print_job_timer.start();
  6344. }
  6345. /**
  6346. * M25: Pause SD Print
  6347. */
  6348. inline void gcode_M25() {
  6349. card.pauseSDPrint();
  6350. print_job_timer.pause();
  6351. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6352. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  6353. #endif
  6354. }
  6355. /**
  6356. * M26: Set SD Card file index
  6357. */
  6358. inline void gcode_M26() {
  6359. if (card.cardOK && parser.seenval('S'))
  6360. card.setIndex(parser.value_long());
  6361. }
  6362. /**
  6363. * M27: Get SD Card status
  6364. * OR, with 'S<seconds>' set the SD status auto-report interval. (Requires AUTO_REPORT_SD_STATUS)
  6365. * OR, with 'C' get the current filename.
  6366. */
  6367. inline void gcode_M27() {
  6368. if (parser.seen('C')) {
  6369. SERIAL_ECHOPGM("Current file: ");
  6370. card.printFilename();
  6371. }
  6372. #if ENABLED(AUTO_REPORT_SD_STATUS)
  6373. else if (parser.seenval('S'))
  6374. card.set_auto_report_interval(parser.value_byte());
  6375. #endif
  6376. else
  6377. card.getStatus();
  6378. }
  6379. /**
  6380. * M28: Start SD Write
  6381. */
  6382. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  6383. /**
  6384. * M29: Stop SD Write
  6385. * Processed in write to file routine above
  6386. */
  6387. inline void gcode_M29() {
  6388. // card.saving = false;
  6389. }
  6390. /**
  6391. * M30 <filename>: Delete SD Card file
  6392. */
  6393. inline void gcode_M30() {
  6394. if (card.cardOK) {
  6395. card.closefile();
  6396. card.removeFile(parser.string_arg);
  6397. }
  6398. }
  6399. #endif // SDSUPPORT
  6400. /**
  6401. * M31: Get the time since the start of SD Print (or last M109)
  6402. */
  6403. inline void gcode_M31() {
  6404. char buffer[21];
  6405. duration_t elapsed = print_job_timer.duration();
  6406. elapsed.toString(buffer);
  6407. lcd_setstatus(buffer);
  6408. SERIAL_ECHO_START();
  6409. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  6410. }
  6411. #if ENABLED(SDSUPPORT)
  6412. /**
  6413. * M32: Select file and start SD Print
  6414. *
  6415. * Examples:
  6416. *
  6417. * M32 !PATH/TO/FILE.GCO# ; Start FILE.GCO
  6418. * M32 P !PATH/TO/FILE.GCO# ; Start FILE.GCO as a procedure
  6419. * M32 S60 !PATH/TO/FILE.GCO# ; Start FILE.GCO at byte 60
  6420. *
  6421. */
  6422. inline void gcode_M32() {
  6423. if (card.sdprinting) planner.synchronize();
  6424. if (card.cardOK) {
  6425. const bool call_procedure = parser.boolval('P');
  6426. card.openFile(parser.string_arg, true, call_procedure);
  6427. if (parser.seenval('S')) card.setIndex(parser.value_long());
  6428. card.startFileprint();
  6429. // Procedure calls count as normal print time.
  6430. if (!call_procedure) print_job_timer.start();
  6431. }
  6432. }
  6433. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  6434. /**
  6435. * M33: Get the long full path of a file or folder
  6436. *
  6437. * Parameters:
  6438. * <dospath> Case-insensitive DOS-style path to a file or folder
  6439. *
  6440. * Example:
  6441. * M33 miscel~1/armchair/armcha~1.gco
  6442. *
  6443. * Output:
  6444. * /Miscellaneous/Armchair/Armchair.gcode
  6445. */
  6446. inline void gcode_M33() {
  6447. card.printLongPath(parser.string_arg);
  6448. }
  6449. #endif
  6450. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  6451. /**
  6452. * M34: Set SD Card Sorting Options
  6453. */
  6454. inline void gcode_M34() {
  6455. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  6456. if (parser.seenval('F')) {
  6457. const int v = parser.value_long();
  6458. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  6459. }
  6460. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  6461. }
  6462. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  6463. /**
  6464. * M928: Start SD Write
  6465. */
  6466. inline void gcode_M928() {
  6467. card.openLogFile(parser.string_arg);
  6468. }
  6469. #endif // SDSUPPORT
  6470. /**
  6471. * Sensitive pin test for M42, M226
  6472. */
  6473. static bool pin_is_protected(const pin_t pin) {
  6474. static const pin_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
  6475. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  6476. if (pin == (pin_t)pgm_read_byte(&sensitive_pins[i])) return true;
  6477. return false;
  6478. }
  6479. inline void protected_pin_err() {
  6480. SERIAL_ERROR_START();
  6481. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  6482. }
  6483. /**
  6484. * M42: Change pin status via GCode
  6485. *
  6486. * P<pin> Pin number (LED if omitted)
  6487. * S<byte> Pin status from 0 - 255
  6488. * I Flag to ignore Marlin's pin protection
  6489. */
  6490. inline void gcode_M42() {
  6491. if (!parser.seenval('S')) return;
  6492. const byte pin_status = parser.value_byte();
  6493. const pin_t pin_number = parser.byteval('P', LED_PIN);
  6494. if (pin_number < 0) return;
  6495. if (!parser.boolval('I') && pin_is_protected(pin_number)) return protected_pin_err();
  6496. pinMode(pin_number, OUTPUT);
  6497. digitalWrite(pin_number, pin_status);
  6498. analogWrite(pin_number, pin_status);
  6499. #if FAN_COUNT > 0
  6500. switch (pin_number) {
  6501. #if HAS_FAN0
  6502. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  6503. #endif
  6504. #if HAS_FAN1
  6505. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  6506. #endif
  6507. #if HAS_FAN2
  6508. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  6509. #endif
  6510. }
  6511. #endif
  6512. }
  6513. #if ENABLED(PINS_DEBUGGING)
  6514. #include "pinsDebug.h"
  6515. inline void toggle_pins() {
  6516. const bool ignore_protection = parser.boolval('I');
  6517. const int repeat = parser.intval('R', 1),
  6518. start = parser.intval('S'),
  6519. end = parser.intval('L', NUM_DIGITAL_PINS - 1),
  6520. wait = parser.intval('W', 500);
  6521. for (uint8_t pin = start; pin <= end; pin++) {
  6522. //report_pin_state_extended(pin, ignore_protection, false);
  6523. if (!ignore_protection && pin_is_protected(pin)) {
  6524. report_pin_state_extended(pin, ignore_protection, true, "Untouched ");
  6525. SERIAL_EOL();
  6526. }
  6527. else {
  6528. report_pin_state_extended(pin, ignore_protection, true, "Pulsing ");
  6529. #if AVR_AT90USB1286_FAMILY // Teensy IDEs don't know about these pins so must use FASTIO
  6530. if (pin == TEENSY_E2) {
  6531. SET_OUTPUT(TEENSY_E2);
  6532. for (int16_t j = 0; j < repeat; j++) {
  6533. WRITE(TEENSY_E2, LOW); safe_delay(wait);
  6534. WRITE(TEENSY_E2, HIGH); safe_delay(wait);
  6535. WRITE(TEENSY_E2, LOW); safe_delay(wait);
  6536. }
  6537. }
  6538. else if (pin == TEENSY_E3) {
  6539. SET_OUTPUT(TEENSY_E3);
  6540. for (int16_t j = 0; j < repeat; j++) {
  6541. WRITE(TEENSY_E3, LOW); safe_delay(wait);
  6542. WRITE(TEENSY_E3, HIGH); safe_delay(wait);
  6543. WRITE(TEENSY_E3, LOW); safe_delay(wait);
  6544. }
  6545. }
  6546. else
  6547. #endif
  6548. {
  6549. pinMode(pin, OUTPUT);
  6550. for (int16_t j = 0; j < repeat; j++) {
  6551. digitalWrite(pin, 0); safe_delay(wait);
  6552. digitalWrite(pin, 1); safe_delay(wait);
  6553. digitalWrite(pin, 0); safe_delay(wait);
  6554. }
  6555. }
  6556. }
  6557. SERIAL_EOL();
  6558. }
  6559. SERIAL_ECHOLNPGM("Done.");
  6560. } // toggle_pins
  6561. inline void servo_probe_test() {
  6562. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  6563. SERIAL_ERROR_START();
  6564. SERIAL_ERRORLNPGM("SERVO not setup");
  6565. #elif !HAS_Z_SERVO_PROBE
  6566. SERIAL_ERROR_START();
  6567. SERIAL_ERRORLNPGM("Z_PROBE_SERVO_NR not setup");
  6568. #else // HAS_Z_SERVO_PROBE
  6569. const uint8_t probe_index = parser.byteval('P', Z_PROBE_SERVO_NR);
  6570. SERIAL_PROTOCOLLNPGM("Servo probe test");
  6571. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  6572. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  6573. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  6574. bool probe_inverting;
  6575. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  6576. #define PROBE_TEST_PIN Z_MIN_PIN
  6577. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  6578. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  6579. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  6580. #if Z_MIN_ENDSTOP_INVERTING
  6581. SERIAL_PROTOCOLLNPGM("true");
  6582. #else
  6583. SERIAL_PROTOCOLLNPGM("false");
  6584. #endif
  6585. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  6586. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  6587. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  6588. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  6589. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  6590. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  6591. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  6592. SERIAL_PROTOCOLLNPGM("true");
  6593. #else
  6594. SERIAL_PROTOCOLLNPGM("false");
  6595. #endif
  6596. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  6597. #endif
  6598. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  6599. SET_INPUT_PULLUP(PROBE_TEST_PIN);
  6600. bool deploy_state, stow_state;
  6601. for (uint8_t i = 0; i < 4; i++) {
  6602. MOVE_SERVO(probe_index, z_servo_angle[0]); //deploy
  6603. safe_delay(500);
  6604. deploy_state = READ(PROBE_TEST_PIN);
  6605. MOVE_SERVO(probe_index, z_servo_angle[1]); //stow
  6606. safe_delay(500);
  6607. stow_state = READ(PROBE_TEST_PIN);
  6608. }
  6609. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  6610. if (deploy_state != stow_state) {
  6611. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  6612. if (deploy_state) {
  6613. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  6614. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  6615. }
  6616. else {
  6617. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  6618. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  6619. }
  6620. #if ENABLED(BLTOUCH)
  6621. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  6622. #endif
  6623. }
  6624. else { // measure active signal length
  6625. MOVE_SERVO(probe_index, z_servo_angle[0]); // deploy
  6626. safe_delay(500);
  6627. SERIAL_PROTOCOLLNPGM("please trigger probe");
  6628. uint16_t probe_counter = 0;
  6629. // Allow 30 seconds max for operator to trigger probe
  6630. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  6631. safe_delay(2);
  6632. if (0 == j % (500 * 1)) reset_stepper_timeout(); // Keep steppers powered
  6633. if (deploy_state != READ(PROBE_TEST_PIN)) { // probe triggered
  6634. for (probe_counter = 1; probe_counter < 50 && deploy_state != READ(PROBE_TEST_PIN); ++probe_counter)
  6635. safe_delay(2);
  6636. if (probe_counter == 50)
  6637. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  6638. else if (probe_counter >= 2)
  6639. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  6640. else
  6641. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  6642. MOVE_SERVO(probe_index, z_servo_angle[1]); //stow
  6643. } // pulse detected
  6644. } // for loop waiting for trigger
  6645. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  6646. } // measure active signal length
  6647. #endif
  6648. } // servo_probe_test
  6649. /**
  6650. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  6651. *
  6652. * M43 - report name and state of pin(s)
  6653. * P<pin> Pin to read or watch. If omitted, reads all pins.
  6654. * I Flag to ignore Marlin's pin protection.
  6655. *
  6656. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  6657. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  6658. * I Flag to ignore Marlin's pin protection.
  6659. *
  6660. * M43 E<bool> - Enable / disable background endstop monitoring
  6661. * - Machine continues to operate
  6662. * - Reports changes to endstops
  6663. * - Toggles LED_PIN when an endstop changes
  6664. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  6665. *
  6666. * M43 T - Toggle pin(s) and report which pin is being toggled
  6667. * S<pin> - Start Pin number. If not given, will default to 0
  6668. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  6669. * I<bool> - Flag to ignore Marlin's pin protection. Use with caution!!!!
  6670. * R - Repeat pulses on each pin this number of times before continueing to next pin
  6671. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  6672. *
  6673. * M43 S - Servo probe test
  6674. * P<index> - Probe index (optional - defaults to 0
  6675. */
  6676. inline void gcode_M43() {
  6677. if (parser.seen('T')) { // must be first or else its "S" and "E" parameters will execute endstop or servo test
  6678. toggle_pins();
  6679. return;
  6680. }
  6681. // Enable or disable endstop monitoring
  6682. if (parser.seen('E')) {
  6683. endstop_monitor_flag = parser.value_bool();
  6684. SERIAL_PROTOCOLPGM("endstop monitor ");
  6685. serialprintPGM(endstop_monitor_flag ? PSTR("en") : PSTR("dis"));
  6686. SERIAL_PROTOCOLLNPGM("abled");
  6687. return;
  6688. }
  6689. if (parser.seen('S')) {
  6690. servo_probe_test();
  6691. return;
  6692. }
  6693. // Get the range of pins to test or watch
  6694. const pin_t first_pin = parser.byteval('P'),
  6695. last_pin = parser.seenval('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  6696. if (first_pin > last_pin) return;
  6697. const bool ignore_protection = parser.boolval('I');
  6698. // Watch until click, M108, or reset
  6699. if (parser.boolval('W')) {
  6700. SERIAL_PROTOCOLLNPGM("Watching pins");
  6701. byte pin_state[last_pin - first_pin + 1];
  6702. for (pin_t pin = first_pin; pin <= last_pin; pin++) {
  6703. if (!ignore_protection && pin_is_protected(pin)) continue;
  6704. pinMode(pin, INPUT_PULLUP);
  6705. delay(1);
  6706. /*
  6707. if (IS_ANALOG(pin))
  6708. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  6709. else
  6710. //*/
  6711. pin_state[pin - first_pin] = digitalRead(pin);
  6712. }
  6713. #if HAS_RESUME_CONTINUE
  6714. wait_for_user = true;
  6715. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6716. #endif
  6717. for (;;) {
  6718. for (pin_t pin = first_pin; pin <= last_pin; pin++) {
  6719. if (!ignore_protection && pin_is_protected(pin)) continue;
  6720. const byte val =
  6721. /*
  6722. IS_ANALOG(pin)
  6723. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  6724. :
  6725. //*/
  6726. digitalRead(pin);
  6727. if (val != pin_state[pin - first_pin]) {
  6728. report_pin_state_extended(pin, ignore_protection, false);
  6729. pin_state[pin - first_pin] = val;
  6730. }
  6731. }
  6732. #if HAS_RESUME_CONTINUE
  6733. if (!wait_for_user) {
  6734. KEEPALIVE_STATE(IN_HANDLER);
  6735. break;
  6736. }
  6737. #endif
  6738. safe_delay(200);
  6739. }
  6740. return;
  6741. }
  6742. // Report current state of selected pin(s)
  6743. for (pin_t pin = first_pin; pin <= last_pin; pin++)
  6744. report_pin_state_extended(pin, ignore_protection, true);
  6745. }
  6746. #endif // PINS_DEBUGGING
  6747. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  6748. /**
  6749. * M48: Z probe repeatability measurement function.
  6750. *
  6751. * Usage:
  6752. * M48 <P#> <X#> <Y#> <V#> <E> <L#> <S>
  6753. * P = Number of sampled points (4-50, default 10)
  6754. * X = Sample X position
  6755. * Y = Sample Y position
  6756. * V = Verbose level (0-4, default=1)
  6757. * E = Engage Z probe for each reading
  6758. * L = Number of legs of movement before probe
  6759. * S = Schizoid (Or Star if you prefer)
  6760. *
  6761. * This function requires the machine to be homed before invocation.
  6762. */
  6763. inline void gcode_M48() {
  6764. if (axis_unhomed_error()) return;
  6765. const int8_t verbose_level = parser.byteval('V', 1);
  6766. if (!WITHIN(verbose_level, 0, 4)) {
  6767. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  6768. return;
  6769. }
  6770. if (verbose_level > 0)
  6771. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  6772. const int8_t n_samples = parser.byteval('P', 10);
  6773. if (!WITHIN(n_samples, 4, 50)) {
  6774. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  6775. return;
  6776. }
  6777. const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE;
  6778. float X_current = current_position[X_AXIS],
  6779. Y_current = current_position[Y_AXIS];
  6780. const float X_probe_location = parser.linearval('X', X_current + X_PROBE_OFFSET_FROM_EXTRUDER),
  6781. Y_probe_location = parser.linearval('Y', Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER);
  6782. if (!position_is_reachable_by_probe(X_probe_location, Y_probe_location)) {
  6783. SERIAL_PROTOCOLLNPGM("? (X,Y) out of bounds.");
  6784. return;
  6785. }
  6786. bool seen_L = parser.seen('L');
  6787. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  6788. if (n_legs > 15) {
  6789. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  6790. return;
  6791. }
  6792. if (n_legs == 1) n_legs = 2;
  6793. const bool schizoid_flag = parser.boolval('S');
  6794. if (schizoid_flag && !seen_L) n_legs = 7;
  6795. /**
  6796. * Now get everything to the specified probe point So we can safely do a
  6797. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  6798. * we don't want to use that as a starting point for each probe.
  6799. */
  6800. if (verbose_level > 2)
  6801. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  6802. // Disable bed level correction in M48 because we want the raw data when we probe
  6803. #if HAS_LEVELING
  6804. const bool was_enabled = planner.leveling_active;
  6805. set_bed_leveling_enabled(false);
  6806. #endif
  6807. setup_for_endstop_or_probe_move();
  6808. float mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  6809. // Move to the first point, deploy, and probe
  6810. const float t = probe_pt(X_probe_location, Y_probe_location, raise_after, verbose_level);
  6811. bool probing_good = !isnan(t);
  6812. if (probing_good) {
  6813. randomSeed(millis());
  6814. for (uint8_t n = 0; n < n_samples; n++) {
  6815. if (n_legs) {
  6816. const int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  6817. float angle = random(0.0, 360.0);
  6818. const float radius = random(
  6819. #if ENABLED(DELTA)
  6820. 0.1250000000 * (DELTA_PRINTABLE_RADIUS),
  6821. 0.3333333333 * (DELTA_PRINTABLE_RADIUS)
  6822. #else
  6823. 5.0, 0.125 * MIN(X_BED_SIZE, Y_BED_SIZE)
  6824. #endif
  6825. );
  6826. if (verbose_level > 3) {
  6827. SERIAL_ECHOPAIR("Starting radius: ", radius);
  6828. SERIAL_ECHOPAIR(" angle: ", angle);
  6829. SERIAL_ECHOPGM(" Direction: ");
  6830. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  6831. SERIAL_ECHOLNPGM("Clockwise");
  6832. }
  6833. for (uint8_t l = 0; l < n_legs - 1; l++) {
  6834. float delta_angle;
  6835. if (schizoid_flag)
  6836. // The points of a 5 point star are 72 degrees apart. We need to
  6837. // skip a point and go to the next one on the star.
  6838. delta_angle = dir * 2.0 * 72.0;
  6839. else
  6840. // If we do this line, we are just trying to move further
  6841. // around the circle.
  6842. delta_angle = dir * (float) random(25, 45);
  6843. angle += delta_angle;
  6844. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  6845. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  6846. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  6847. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  6848. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  6849. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  6850. #if DISABLED(DELTA)
  6851. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  6852. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  6853. #else
  6854. // If we have gone out too far, we can do a simple fix and scale the numbers
  6855. // back in closer to the origin.
  6856. while (!position_is_reachable_by_probe(X_current, Y_current)) {
  6857. X_current *= 0.8;
  6858. Y_current *= 0.8;
  6859. if (verbose_level > 3) {
  6860. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  6861. SERIAL_ECHOLNPAIR(", ", Y_current);
  6862. }
  6863. }
  6864. #endif
  6865. if (verbose_level > 3) {
  6866. SERIAL_PROTOCOLPGM("Going to:");
  6867. SERIAL_ECHOPAIR(" X", X_current);
  6868. SERIAL_ECHOPAIR(" Y", Y_current);
  6869. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  6870. }
  6871. do_blocking_move_to_xy(X_current, Y_current);
  6872. } // n_legs loop
  6873. } // n_legs
  6874. // Probe a single point
  6875. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, raise_after);
  6876. // Break the loop if the probe fails
  6877. probing_good = !isnan(sample_set[n]);
  6878. if (!probing_good) break;
  6879. /**
  6880. * Get the current mean for the data points we have so far
  6881. */
  6882. float sum = 0.0;
  6883. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  6884. mean = sum / (n + 1);
  6885. NOMORE(min, sample_set[n]);
  6886. NOLESS(max, sample_set[n]);
  6887. /**
  6888. * Now, use that mean to calculate the standard deviation for the
  6889. * data points we have so far
  6890. */
  6891. sum = 0.0;
  6892. for (uint8_t j = 0; j <= n; j++)
  6893. sum += sq(sample_set[j] - mean);
  6894. sigma = SQRT(sum / (n + 1));
  6895. if (verbose_level > 0) {
  6896. if (verbose_level > 1) {
  6897. SERIAL_PROTOCOL(n + 1);
  6898. SERIAL_PROTOCOLPGM(" of ");
  6899. SERIAL_PROTOCOL(int(n_samples));
  6900. SERIAL_PROTOCOLPGM(": z: ");
  6901. SERIAL_PROTOCOL_F(sample_set[n], 3);
  6902. if (verbose_level > 2) {
  6903. SERIAL_PROTOCOLPGM(" mean: ");
  6904. SERIAL_PROTOCOL_F(mean, 4);
  6905. SERIAL_PROTOCOLPGM(" sigma: ");
  6906. SERIAL_PROTOCOL_F(sigma, 6);
  6907. SERIAL_PROTOCOLPGM(" min: ");
  6908. SERIAL_PROTOCOL_F(min, 3);
  6909. SERIAL_PROTOCOLPGM(" max: ");
  6910. SERIAL_PROTOCOL_F(max, 3);
  6911. SERIAL_PROTOCOLPGM(" range: ");
  6912. SERIAL_PROTOCOL_F(max-min, 3);
  6913. }
  6914. SERIAL_EOL();
  6915. }
  6916. }
  6917. } // n_samples loop
  6918. }
  6919. STOW_PROBE();
  6920. if (probing_good) {
  6921. SERIAL_PROTOCOLLNPGM("Finished!");
  6922. if (verbose_level > 0) {
  6923. SERIAL_PROTOCOLPGM("Mean: ");
  6924. SERIAL_PROTOCOL_F(mean, 6);
  6925. SERIAL_PROTOCOLPGM(" Min: ");
  6926. SERIAL_PROTOCOL_F(min, 3);
  6927. SERIAL_PROTOCOLPGM(" Max: ");
  6928. SERIAL_PROTOCOL_F(max, 3);
  6929. SERIAL_PROTOCOLPGM(" Range: ");
  6930. SERIAL_PROTOCOL_F(max-min, 3);
  6931. SERIAL_EOL();
  6932. }
  6933. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  6934. SERIAL_PROTOCOL_F(sigma, 6);
  6935. SERIAL_EOL();
  6936. SERIAL_EOL();
  6937. }
  6938. clean_up_after_endstop_or_probe_move();
  6939. // Re-enable bed level correction if it had been on
  6940. #if HAS_LEVELING
  6941. set_bed_leveling_enabled(was_enabled);
  6942. #endif
  6943. #ifdef Z_AFTER_PROBING
  6944. move_z_after_probing();
  6945. #endif
  6946. report_current_position();
  6947. }
  6948. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  6949. #if ENABLED(G26_MESH_VALIDATION)
  6950. inline void gcode_M49() {
  6951. g26_debug_flag ^= true;
  6952. SERIAL_PROTOCOLPGM("G26 Debug ");
  6953. serialprintPGM(g26_debug_flag ? PSTR("on.\n") : PSTR("off.\n"));
  6954. }
  6955. #endif // G26_MESH_VALIDATION
  6956. #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY)
  6957. /**
  6958. * M73: Set percentage complete (for display on LCD)
  6959. *
  6960. * Example:
  6961. * M73 P25 ; Set progress to 25%
  6962. *
  6963. * Notes:
  6964. * This has no effect during an SD print job
  6965. */
  6966. inline void gcode_M73() {
  6967. if (!IS_SD_PRINTING && parser.seen('P')) {
  6968. progress_bar_percent = parser.value_byte();
  6969. NOMORE(progress_bar_percent, 100);
  6970. }
  6971. }
  6972. #endif // ULTRA_LCD && LCD_SET_PROGRESS_MANUALLY
  6973. /**
  6974. * M75: Start print timer
  6975. */
  6976. inline void gcode_M75() { print_job_timer.start(); }
  6977. /**
  6978. * M76: Pause print timer
  6979. */
  6980. inline void gcode_M76() { print_job_timer.pause(); }
  6981. /**
  6982. * M77: Stop print timer
  6983. */
  6984. inline void gcode_M77() { print_job_timer.stop(); }
  6985. #if ENABLED(PRINTCOUNTER)
  6986. /**
  6987. * M78: Show print statistics
  6988. */
  6989. inline void gcode_M78() {
  6990. // "M78 S78" will reset the statistics
  6991. if (parser.intval('S') == 78)
  6992. print_job_timer.initStats();
  6993. else
  6994. print_job_timer.showStats();
  6995. }
  6996. #endif
  6997. /**
  6998. * M104: Set hot end temperature
  6999. */
  7000. inline void gcode_M104() {
  7001. if (get_target_extruder_from_command(104)) return;
  7002. if (DEBUGGING(DRYRUN)) return;
  7003. #if ENABLED(SINGLENOZZLE)
  7004. if (target_extruder != active_extruder) return;
  7005. #endif
  7006. if (parser.seenval('S')) {
  7007. const int16_t temp = parser.value_celsius();
  7008. thermalManager.setTargetHotend(temp, target_extruder);
  7009. #if ENABLED(DUAL_X_CARRIAGE)
  7010. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  7011. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  7012. #endif
  7013. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  7014. /**
  7015. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  7016. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  7017. * standby mode, for instance in a dual extruder setup, without affecting
  7018. * the running print timer.
  7019. */
  7020. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  7021. print_job_timer.stop();
  7022. lcd_reset_status();
  7023. }
  7024. #endif
  7025. }
  7026. #if ENABLED(AUTOTEMP)
  7027. planner.autotemp_M104_M109();
  7028. #endif
  7029. }
  7030. /**
  7031. * M105: Read hot end and bed temperature
  7032. */
  7033. inline void gcode_M105() {
  7034. if (get_target_extruder_from_command(105)) return;
  7035. #if HAS_TEMP_SENSOR
  7036. SERIAL_PROTOCOLPGM(MSG_OK);
  7037. thermalManager.print_heaterstates();
  7038. #else // !HAS_TEMP_SENSOR
  7039. SERIAL_ERROR_START();
  7040. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  7041. #endif
  7042. SERIAL_EOL();
  7043. }
  7044. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  7045. /**
  7046. * M155: Set temperature auto-report interval. M155 S<seconds>
  7047. */
  7048. inline void gcode_M155() {
  7049. if (parser.seenval('S'))
  7050. thermalManager.set_auto_report_interval(parser.value_byte());
  7051. }
  7052. #endif // AUTO_REPORT_TEMPERATURES
  7053. #if FAN_COUNT > 0
  7054. /**
  7055. * M106: Set Fan Speed
  7056. *
  7057. * S<int> Speed between 0-255
  7058. * P<index> Fan index, if more than one fan
  7059. *
  7060. * With EXTRA_FAN_SPEED enabled:
  7061. *
  7062. * T<int> Restore/Use/Set Temporary Speed:
  7063. * 1 = Restore previous speed after T2
  7064. * 2 = Use temporary speed set with T3-255
  7065. * 3-255 = Set the speed for use with T2
  7066. */
  7067. inline void gcode_M106() {
  7068. const uint8_t p = parser.byteval('P');
  7069. if (p < FAN_COUNT) {
  7070. #if ENABLED(EXTRA_FAN_SPEED)
  7071. const int16_t t = parser.intval('T');
  7072. if (t > 0) {
  7073. switch (t) {
  7074. case 1:
  7075. fanSpeeds[p] = old_fanSpeeds[p];
  7076. break;
  7077. case 2:
  7078. old_fanSpeeds[p] = fanSpeeds[p];
  7079. fanSpeeds[p] = new_fanSpeeds[p];
  7080. break;
  7081. default:
  7082. new_fanSpeeds[p] = MIN(t, 255);
  7083. break;
  7084. }
  7085. return;
  7086. }
  7087. #endif // EXTRA_FAN_SPEED
  7088. const uint16_t s = parser.ushortval('S', 255);
  7089. fanSpeeds[p] = MIN(s, 255U);
  7090. }
  7091. }
  7092. /**
  7093. * M107: Fan Off
  7094. */
  7095. inline void gcode_M107() {
  7096. const uint16_t p = parser.ushortval('P');
  7097. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  7098. }
  7099. #endif // FAN_COUNT > 0
  7100. #if DISABLED(EMERGENCY_PARSER)
  7101. /**
  7102. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  7103. */
  7104. inline void gcode_M108() { wait_for_heatup = false; }
  7105. /**
  7106. * M112: Emergency Stop
  7107. */
  7108. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  7109. /**
  7110. * M410: Quickstop - Abort all planned moves
  7111. *
  7112. * This will stop the carriages mid-move, so most likely they
  7113. * will be out of sync with the stepper position after this.
  7114. */
  7115. inline void gcode_M410() { quickstop_stepper(); }
  7116. #endif
  7117. /**
  7118. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  7119. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  7120. */
  7121. #ifndef MIN_COOLING_SLOPE_DEG
  7122. #define MIN_COOLING_SLOPE_DEG 1.50
  7123. #endif
  7124. #ifndef MIN_COOLING_SLOPE_TIME
  7125. #define MIN_COOLING_SLOPE_TIME 60
  7126. #endif
  7127. inline void gcode_M109() {
  7128. if (get_target_extruder_from_command(109)) return;
  7129. if (DEBUGGING(DRYRUN)) return;
  7130. #if ENABLED(SINGLENOZZLE)
  7131. if (target_extruder != active_extruder) return;
  7132. #endif
  7133. const bool no_wait_for_cooling = parser.seenval('S'),
  7134. set_temp = no_wait_for_cooling || parser.seenval('R');
  7135. if (set_temp) {
  7136. const int16_t temp = parser.value_celsius();
  7137. thermalManager.setTargetHotend(temp, target_extruder);
  7138. #if ENABLED(DUAL_X_CARRIAGE)
  7139. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  7140. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  7141. #endif
  7142. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  7143. /**
  7144. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  7145. * standby mode, (e.g., in a dual extruder setup) without affecting
  7146. * the running print timer.
  7147. */
  7148. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  7149. print_job_timer.stop();
  7150. lcd_reset_status();
  7151. }
  7152. else
  7153. print_job_timer.start();
  7154. #endif
  7155. #if ENABLED(ULTRA_LCD)
  7156. const bool heating = thermalManager.isHeatingHotend(target_extruder);
  7157. if (heating || !no_wait_for_cooling)
  7158. #if HOTENDS > 1
  7159. lcd_status_printf_P(0, heating ? PSTR("E%i " MSG_HEATING) : PSTR("E%i " MSG_COOLING), target_extruder + 1);
  7160. #else
  7161. lcd_setstatusPGM(heating ? PSTR("E " MSG_HEATING) : PSTR("E " MSG_COOLING));
  7162. #endif
  7163. #endif
  7164. }
  7165. #if ENABLED(AUTOTEMP)
  7166. planner.autotemp_M104_M109();
  7167. #endif
  7168. if (!set_temp) return;
  7169. #if TEMP_RESIDENCY_TIME > 0
  7170. millis_t residency_start_ms = 0;
  7171. // Loop until the temperature has stabilized
  7172. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  7173. #else
  7174. // Loop until the temperature is very close target
  7175. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  7176. #endif
  7177. float target_temp = -1, old_temp = 9999;
  7178. bool wants_to_cool = false;
  7179. wait_for_heatup = true;
  7180. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  7181. #if DISABLED(BUSY_WHILE_HEATING)
  7182. KEEPALIVE_STATE(NOT_BUSY);
  7183. #endif
  7184. #if ENABLED(PRINTER_EVENT_LEDS)
  7185. const float start_temp = thermalManager.degHotend(target_extruder);
  7186. uint8_t old_blue = 0;
  7187. #endif
  7188. do {
  7189. // Target temperature might be changed during the loop
  7190. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  7191. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  7192. target_temp = thermalManager.degTargetHotend(target_extruder);
  7193. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  7194. if (no_wait_for_cooling && wants_to_cool) break;
  7195. }
  7196. now = millis();
  7197. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  7198. next_temp_ms = now + 1000UL;
  7199. thermalManager.print_heaterstates();
  7200. #if TEMP_RESIDENCY_TIME > 0
  7201. SERIAL_PROTOCOLPGM(" W:");
  7202. if (residency_start_ms)
  7203. SERIAL_PROTOCOL(long((((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  7204. else
  7205. SERIAL_PROTOCOLCHAR('?');
  7206. #endif
  7207. SERIAL_EOL();
  7208. }
  7209. idle();
  7210. reset_stepper_timeout(); // Keep steppers powered
  7211. const float temp = thermalManager.degHotend(target_extruder);
  7212. #if ENABLED(PRINTER_EVENT_LEDS)
  7213. // Gradually change LED strip from violet to red as nozzle heats up
  7214. if (!wants_to_cool) {
  7215. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  7216. if (blue != old_blue) {
  7217. old_blue = blue;
  7218. leds.set_color(
  7219. MakeLEDColor(255, 0, blue, 0, pixels.getBrightness())
  7220. #if ENABLED(NEOPIXEL_IS_SEQUENTIAL)
  7221. , true
  7222. #endif
  7223. );
  7224. }
  7225. }
  7226. #endif
  7227. #if TEMP_RESIDENCY_TIME > 0
  7228. const float temp_diff = ABS(target_temp - temp);
  7229. if (!residency_start_ms) {
  7230. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  7231. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  7232. }
  7233. else if (temp_diff > TEMP_HYSTERESIS) {
  7234. // Restart the timer whenever the temperature falls outside the hysteresis.
  7235. residency_start_ms = now;
  7236. }
  7237. #endif
  7238. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  7239. if (wants_to_cool) {
  7240. // break after MIN_COOLING_SLOPE_TIME seconds
  7241. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  7242. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  7243. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG)) break;
  7244. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  7245. old_temp = temp;
  7246. }
  7247. }
  7248. } while (wait_for_heatup && TEMP_CONDITIONS);
  7249. if (wait_for_heatup) {
  7250. lcd_reset_status();
  7251. #if ENABLED(PRINTER_EVENT_LEDS)
  7252. leds.set_white();
  7253. #endif
  7254. }
  7255. #if DISABLED(BUSY_WHILE_HEATING)
  7256. KEEPALIVE_STATE(IN_HANDLER);
  7257. #endif
  7258. }
  7259. #if HAS_HEATED_BED
  7260. /**
  7261. * M140: Set bed temperature
  7262. */
  7263. inline void gcode_M140() {
  7264. if (DEBUGGING(DRYRUN)) return;
  7265. if (parser.seenval('S')) thermalManager.setTargetBed(parser.value_celsius());
  7266. }
  7267. #ifndef MIN_COOLING_SLOPE_DEG_BED
  7268. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  7269. #endif
  7270. #ifndef MIN_COOLING_SLOPE_TIME_BED
  7271. #define MIN_COOLING_SLOPE_TIME_BED 60
  7272. #endif
  7273. /**
  7274. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  7275. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  7276. */
  7277. inline void gcode_M190() {
  7278. if (DEBUGGING(DRYRUN)) return;
  7279. const bool no_wait_for_cooling = parser.seenval('S');
  7280. if (no_wait_for_cooling || parser.seenval('R')) {
  7281. thermalManager.setTargetBed(parser.value_celsius());
  7282. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  7283. if (parser.value_celsius() > BED_MINTEMP)
  7284. print_job_timer.start();
  7285. #endif
  7286. }
  7287. else return;
  7288. lcd_setstatusPGM(thermalManager.isHeatingBed() ? PSTR(MSG_BED_HEATING) : PSTR(MSG_BED_COOLING));
  7289. #if TEMP_BED_RESIDENCY_TIME > 0
  7290. millis_t residency_start_ms = 0;
  7291. // Loop until the temperature has stabilized
  7292. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  7293. #else
  7294. // Loop until the temperature is very close target
  7295. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  7296. #endif
  7297. float target_temp = -1.0, old_temp = 9999.0;
  7298. bool wants_to_cool = false;
  7299. wait_for_heatup = true;
  7300. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  7301. #if DISABLED(BUSY_WHILE_HEATING)
  7302. KEEPALIVE_STATE(NOT_BUSY);
  7303. #endif
  7304. target_extruder = active_extruder; // for print_heaterstates
  7305. #if ENABLED(PRINTER_EVENT_LEDS)
  7306. const float start_temp = thermalManager.degBed();
  7307. uint8_t old_red = 127;
  7308. #endif
  7309. do {
  7310. // Target temperature might be changed during the loop
  7311. if (target_temp != thermalManager.degTargetBed()) {
  7312. wants_to_cool = thermalManager.isCoolingBed();
  7313. target_temp = thermalManager.degTargetBed();
  7314. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  7315. if (no_wait_for_cooling && wants_to_cool) break;
  7316. }
  7317. now = millis();
  7318. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  7319. next_temp_ms = now + 1000UL;
  7320. thermalManager.print_heaterstates();
  7321. #if TEMP_BED_RESIDENCY_TIME > 0
  7322. SERIAL_PROTOCOLPGM(" W:");
  7323. if (residency_start_ms)
  7324. SERIAL_PROTOCOL(long((((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  7325. else
  7326. SERIAL_PROTOCOLCHAR('?');
  7327. #endif
  7328. SERIAL_EOL();
  7329. }
  7330. idle();
  7331. reset_stepper_timeout(); // Keep steppers powered
  7332. const float temp = thermalManager.degBed();
  7333. #if ENABLED(PRINTER_EVENT_LEDS)
  7334. // Gradually change LED strip from blue to violet as bed heats up
  7335. if (!wants_to_cool) {
  7336. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  7337. if (red != old_red) {
  7338. old_red = red;
  7339. leds.set_color(
  7340. MakeLEDColor(red, 0, 255, 0, pixels.getBrightness())
  7341. #if ENABLED(NEOPIXEL_IS_SEQUENTIAL)
  7342. , true
  7343. #endif
  7344. );
  7345. }
  7346. }
  7347. #endif
  7348. #if TEMP_BED_RESIDENCY_TIME > 0
  7349. const float temp_diff = ABS(target_temp - temp);
  7350. if (!residency_start_ms) {
  7351. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  7352. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  7353. }
  7354. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  7355. // Restart the timer whenever the temperature falls outside the hysteresis.
  7356. residency_start_ms = now;
  7357. }
  7358. #endif // TEMP_BED_RESIDENCY_TIME > 0
  7359. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  7360. if (wants_to_cool) {
  7361. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  7362. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  7363. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  7364. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG_BED)) break;
  7365. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  7366. old_temp = temp;
  7367. }
  7368. }
  7369. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  7370. if (wait_for_heatup) lcd_reset_status();
  7371. #if DISABLED(BUSY_WHILE_HEATING)
  7372. KEEPALIVE_STATE(IN_HANDLER);
  7373. #endif
  7374. }
  7375. #endif // HAS_HEATED_BED
  7376. /**
  7377. * M110: Set Current Line Number
  7378. */
  7379. inline void gcode_M110() {
  7380. if (parser.seenval('N')) gcode_LastN = parser.value_long();
  7381. }
  7382. /**
  7383. * M111: Set the debug level
  7384. */
  7385. inline void gcode_M111() {
  7386. if (parser.seen('S')) marlin_debug_flags = parser.byteval('S');
  7387. static const char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO,
  7388. str_debug_2[] PROGMEM = MSG_DEBUG_INFO,
  7389. str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS,
  7390. str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN,
  7391. str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION
  7392. #if ENABLED(DEBUG_LEVELING_FEATURE)
  7393. , str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING
  7394. #endif
  7395. ;
  7396. static const char* const debug_strings[] PROGMEM = {
  7397. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  7398. #if ENABLED(DEBUG_LEVELING_FEATURE)
  7399. , str_debug_32
  7400. #endif
  7401. };
  7402. SERIAL_ECHO_START();
  7403. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  7404. if (marlin_debug_flags) {
  7405. uint8_t comma = 0;
  7406. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  7407. if (TEST(marlin_debug_flags, i)) {
  7408. if (comma++) SERIAL_CHAR(',');
  7409. serialprintPGM((char*)pgm_read_ptr(&debug_strings[i]));
  7410. }
  7411. }
  7412. }
  7413. else {
  7414. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  7415. #if !defined(__AVR__) || !defined(USBCON)
  7416. #if ENABLED(SERIAL_STATS_RX_BUFFER_OVERRUNS)
  7417. SERIAL_ECHOPAIR("\nBuffer Overruns: ", customizedSerial.buffer_overruns());
  7418. #endif
  7419. #if ENABLED(SERIAL_STATS_RX_FRAMING_ERRORS)
  7420. SERIAL_ECHOPAIR("\nFraming Errors: ", customizedSerial.framing_errors());
  7421. #endif
  7422. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  7423. SERIAL_ECHOPAIR("\nDropped bytes: ", customizedSerial.dropped());
  7424. #endif
  7425. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  7426. SERIAL_ECHOPAIR("\nMax RX Queue Size: ", customizedSerial.rxMaxEnqueued());
  7427. #endif
  7428. #endif // !__AVR__ || !USBCON
  7429. }
  7430. SERIAL_EOL();
  7431. }
  7432. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  7433. /**
  7434. * M113: Get or set Host Keepalive interval (0 to disable)
  7435. *
  7436. * S<seconds> Optional. Set the keepalive interval.
  7437. */
  7438. inline void gcode_M113() {
  7439. if (parser.seenval('S')) {
  7440. host_keepalive_interval = parser.value_byte();
  7441. NOMORE(host_keepalive_interval, 60);
  7442. }
  7443. else {
  7444. SERIAL_ECHO_START();
  7445. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  7446. }
  7447. }
  7448. #endif
  7449. #if ENABLED(BARICUDA)
  7450. #if HAS_HEATER_1
  7451. /**
  7452. * M126: Heater 1 valve open
  7453. */
  7454. inline void gcode_M126() { baricuda_valve_pressure = parser.byteval('S', 255); }
  7455. /**
  7456. * M127: Heater 1 valve close
  7457. */
  7458. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  7459. #endif
  7460. #if HAS_HEATER_2
  7461. /**
  7462. * M128: Heater 2 valve open
  7463. */
  7464. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.byteval('S', 255); }
  7465. /**
  7466. * M129: Heater 2 valve close
  7467. */
  7468. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  7469. #endif
  7470. #endif // BARICUDA
  7471. #if ENABLED(ULTIPANEL)
  7472. /**
  7473. * M145: Set the heatup state for a material in the LCD menu
  7474. *
  7475. * S<material> (0=PLA, 1=ABS)
  7476. * H<hotend temp>
  7477. * B<bed temp>
  7478. * F<fan speed>
  7479. */
  7480. inline void gcode_M145() {
  7481. const uint8_t material = (uint8_t)parser.intval('S');
  7482. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  7483. SERIAL_ERROR_START();
  7484. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  7485. }
  7486. else {
  7487. int v;
  7488. if (parser.seenval('H')) {
  7489. v = parser.value_int();
  7490. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  7491. }
  7492. if (parser.seenval('F')) {
  7493. v = parser.value_int();
  7494. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  7495. }
  7496. #if TEMP_SENSOR_BED != 0
  7497. if (parser.seenval('B')) {
  7498. v = parser.value_int();
  7499. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  7500. }
  7501. #endif
  7502. }
  7503. }
  7504. #endif // ULTIPANEL
  7505. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  7506. /**
  7507. * M149: Set temperature units
  7508. */
  7509. inline void gcode_M149() {
  7510. if (parser.seenval('C')) parser.set_input_temp_units(TEMPUNIT_C);
  7511. else if (parser.seenval('K')) parser.set_input_temp_units(TEMPUNIT_K);
  7512. else if (parser.seenval('F')) parser.set_input_temp_units(TEMPUNIT_F);
  7513. }
  7514. #endif
  7515. #if HAS_POWER_SWITCH
  7516. /**
  7517. * M80 : Turn on the Power Supply
  7518. * M80 S : Report the current state and exit
  7519. */
  7520. inline void gcode_M80() {
  7521. // S: Report the current power supply state and exit
  7522. if (parser.seen('S')) {
  7523. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  7524. return;
  7525. }
  7526. PSU_ON();
  7527. /**
  7528. * If you have a switch on suicide pin, this is useful
  7529. * if you want to start another print with suicide feature after
  7530. * a print without suicide...
  7531. */
  7532. #if HAS_SUICIDE
  7533. OUT_WRITE(SUICIDE_PIN, HIGH);
  7534. #endif
  7535. #if DISABLED(AUTO_POWER_CONTROL)
  7536. delay(100); // Wait for power to settle
  7537. restore_stepper_drivers();
  7538. #endif
  7539. #if ENABLED(ULTIPANEL)
  7540. lcd_reset_status();
  7541. #endif
  7542. }
  7543. #endif // HAS_POWER_SWITCH
  7544. /**
  7545. * M81: Turn off Power, including Power Supply, if there is one.
  7546. *
  7547. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  7548. */
  7549. inline void gcode_M81() {
  7550. thermalManager.disable_all_heaters();
  7551. planner.finish_and_disable();
  7552. #if FAN_COUNT > 0
  7553. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  7554. #if ENABLED(PROBING_FANS_OFF)
  7555. fans_paused = false;
  7556. ZERO(paused_fanSpeeds);
  7557. #endif
  7558. #endif
  7559. safe_delay(1000); // Wait 1 second before switching off
  7560. #if HAS_SUICIDE
  7561. suicide();
  7562. #elif HAS_POWER_SWITCH
  7563. PSU_OFF();
  7564. #endif
  7565. #if ENABLED(ULTIPANEL)
  7566. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  7567. #endif
  7568. }
  7569. /**
  7570. * M82: Set E codes absolute (default)
  7571. */
  7572. inline void gcode_M82() { axis_relative_modes[E_CART] = false; }
  7573. /**
  7574. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  7575. */
  7576. inline void gcode_M83() { axis_relative_modes[E_CART] = true; }
  7577. /**
  7578. * M18, M84: Disable stepper motors
  7579. */
  7580. inline void gcode_M18_M84() {
  7581. if (parser.seenval('S')) {
  7582. stepper_inactive_time = parser.value_millis_from_seconds();
  7583. }
  7584. else {
  7585. bool all_axis = !(parser.seen('X') || parser.seen('Y') || parser.seen('Z') || parser.seen('E'));
  7586. if (all_axis) {
  7587. planner.finish_and_disable();
  7588. }
  7589. else {
  7590. planner.synchronize();
  7591. if (parser.seen('X')) disable_X();
  7592. if (parser.seen('Y')) disable_Y();
  7593. if (parser.seen('Z')) disable_Z();
  7594. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN // Only disable on boards that have separate ENABLE_PINS
  7595. if (parser.seen('E')) disable_e_steppers();
  7596. #endif
  7597. }
  7598. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTIPANEL) // Only needed with an LCD
  7599. if (ubl.lcd_map_control) ubl.lcd_map_control = defer_return_to_status = false;
  7600. #endif
  7601. }
  7602. }
  7603. /**
  7604. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  7605. */
  7606. inline void gcode_M85() {
  7607. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  7608. }
  7609. /**
  7610. * Multi-stepper support for M92, M201, M203
  7611. */
  7612. #if ENABLED(DISTINCT_E_FACTORS)
  7613. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  7614. #define TARGET_EXTRUDER target_extruder
  7615. #else
  7616. #define GET_TARGET_EXTRUDER(CMD) NOOP
  7617. #define TARGET_EXTRUDER 0
  7618. #endif
  7619. /**
  7620. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  7621. * (for Hangprinter: A, B, C, D, and E)
  7622. * (Follows the same syntax as G92)
  7623. *
  7624. * With multiple extruders use T to specify which one.
  7625. */
  7626. inline void gcode_M92() {
  7627. GET_TARGET_EXTRUDER(92);
  7628. LOOP_NUM_AXIS(i) {
  7629. if (parser.seen(RAW_AXIS_CODES(i))) {
  7630. if (i == E_AXIS) {
  7631. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  7632. if (value < 20) {
  7633. const float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  7634. #if DISABLED(JUNCTION_DEVIATION)
  7635. planner.max_jerk[E_AXIS] *= factor;
  7636. #endif
  7637. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  7638. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  7639. }
  7640. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  7641. }
  7642. else {
  7643. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  7644. SERIAL_ECHOLNPGM("Warning: "
  7645. "M92 A, B, C, and D only affect acceleration planning "
  7646. "when BUILDUP_COMPENSATION_FEATURE is enabled.");
  7647. #endif
  7648. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  7649. }
  7650. }
  7651. }
  7652. planner.refresh_positioning();
  7653. }
  7654. /**
  7655. * Output the current position to serial
  7656. */
  7657. void report_current_position() {
  7658. SERIAL_PROTOCOLPAIR("X:", LOGICAL_X_POSITION(current_position[X_AXIS]));
  7659. SERIAL_PROTOCOLPAIR(" Y:", LOGICAL_Y_POSITION(current_position[Y_AXIS]));
  7660. SERIAL_PROTOCOLPAIR(" Z:", LOGICAL_Z_POSITION(current_position[Z_AXIS]));
  7661. SERIAL_PROTOCOLPAIR(" E:", current_position[E_CART]);
  7662. #if ENABLED(HANGPRINTER)
  7663. SERIAL_EOL();
  7664. SERIAL_PROTOCOLPAIR("A:", line_lengths[A_AXIS]);
  7665. SERIAL_PROTOCOLPAIR(" B:", line_lengths[B_AXIS]);
  7666. SERIAL_PROTOCOLPAIR(" C:", line_lengths[C_AXIS]);
  7667. SERIAL_PROTOCOLLNPAIR(" D:", line_lengths[D_AXIS]);
  7668. #endif
  7669. stepper.report_positions();
  7670. #if IS_SCARA
  7671. SERIAL_PROTOCOLPAIR("SCARA Theta:", planner.get_axis_position_degrees(A_AXIS));
  7672. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", planner.get_axis_position_degrees(B_AXIS));
  7673. SERIAL_EOL();
  7674. #endif
  7675. }
  7676. #ifdef M114_DETAIL
  7677. void report_xyze(const float pos[], const uint8_t n = 4, const uint8_t precision = 3) {
  7678. char str[12];
  7679. for (uint8_t i = 0; i < n; i++) {
  7680. SERIAL_CHAR(' ');
  7681. SERIAL_CHAR(axis_codes[i]);
  7682. SERIAL_CHAR(':');
  7683. SERIAL_PROTOCOL(dtostrf(pos[i], 8, precision, str));
  7684. }
  7685. SERIAL_EOL();
  7686. }
  7687. inline void report_xyz(const float pos[]) { report_xyze(pos, 3); }
  7688. void report_current_position_detail() {
  7689. SERIAL_PROTOCOLPGM("\nLogical:");
  7690. const float logical[XYZ] = {
  7691. LOGICAL_X_POSITION(current_position[X_AXIS]),
  7692. LOGICAL_Y_POSITION(current_position[Y_AXIS]),
  7693. LOGICAL_Z_POSITION(current_position[Z_AXIS])
  7694. };
  7695. report_xyz(logical);
  7696. SERIAL_PROTOCOLPGM("Raw: ");
  7697. report_xyz(current_position);
  7698. float leveled[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  7699. #if PLANNER_LEVELING
  7700. SERIAL_PROTOCOLPGM("Leveled:");
  7701. planner.apply_leveling(leveled);
  7702. report_xyz(leveled);
  7703. SERIAL_PROTOCOLPGM("UnLevel:");
  7704. float unleveled[XYZ] = { leveled[X_AXIS], leveled[Y_AXIS], leveled[Z_AXIS] };
  7705. planner.unapply_leveling(unleveled);
  7706. report_xyz(unleveled);
  7707. #endif
  7708. #if IS_KINEMATIC
  7709. #if IS_SCARA
  7710. SERIAL_PROTOCOLPGM("ScaraK: ");
  7711. #else
  7712. SERIAL_PROTOCOLPGM("DeltaK: ");
  7713. #endif
  7714. inverse_kinematics(leveled); // writes delta[]
  7715. report_xyz(delta);
  7716. #endif
  7717. planner.synchronize();
  7718. SERIAL_PROTOCOLPGM("Stepper:");
  7719. LOOP_NUM_AXIS(i) {
  7720. SERIAL_CHAR(' ');
  7721. SERIAL_CHAR(RAW_AXIS_CODES(i));
  7722. SERIAL_CHAR(':');
  7723. SERIAL_PROTOCOL(stepper.position((AxisEnum)i));
  7724. }
  7725. SERIAL_EOL();
  7726. #if IS_SCARA
  7727. const float deg[XYZ] = {
  7728. planner.get_axis_position_degrees(A_AXIS),
  7729. planner.get_axis_position_degrees(B_AXIS)
  7730. };
  7731. SERIAL_PROTOCOLPGM("Degrees:");
  7732. report_xyze(deg, 2);
  7733. #endif
  7734. SERIAL_PROTOCOLPGM("FromStp:");
  7735. get_cartesian_from_steppers(); // writes cartes[XYZ] (with forward kinematics)
  7736. const float from_steppers[XYZE] = { cartes[X_AXIS], cartes[Y_AXIS], cartes[Z_AXIS], planner.get_axis_position_mm(E_AXIS) };
  7737. report_xyze(from_steppers);
  7738. const float diff[XYZE] = {
  7739. from_steppers[X_AXIS] - leveled[X_AXIS],
  7740. from_steppers[Y_AXIS] - leveled[Y_AXIS],
  7741. from_steppers[Z_AXIS] - leveled[Z_AXIS],
  7742. from_steppers[E_CART] - current_position[E_CART]
  7743. };
  7744. SERIAL_PROTOCOLPGM("Differ: ");
  7745. report_xyze(diff);
  7746. }
  7747. #endif // M114_DETAIL
  7748. /**
  7749. * M114: Report current position to host
  7750. */
  7751. inline void gcode_M114() {
  7752. #ifdef M114_DETAIL
  7753. if (parser.seen('D')) return report_current_position_detail();
  7754. #endif
  7755. planner.synchronize();
  7756. const uint16_t sval = parser.ushortval('S');
  7757. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  7758. if (sval == 1) return report_axis_position_from_encoder_data();
  7759. #endif
  7760. if (sval == 2) return report_xyz_from_stepper_position();
  7761. report_current_position();
  7762. }
  7763. /**
  7764. * M115: Capabilities string
  7765. */
  7766. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  7767. static void cap_line(const char * const name, bool ena=false) {
  7768. SERIAL_PROTOCOLPGM("Cap:");
  7769. serialprintPGM(name);
  7770. SERIAL_PROTOCOLPGM(":");
  7771. SERIAL_PROTOCOLLN(int(ena ? 1 : 0));
  7772. }
  7773. #endif
  7774. inline void gcode_M115() {
  7775. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  7776. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  7777. // SERIAL_XON_XOFF
  7778. cap_line(PSTR("SERIAL_XON_XOFF")
  7779. #if ENABLED(SERIAL_XON_XOFF)
  7780. , true
  7781. #endif
  7782. );
  7783. // EEPROM (M500, M501)
  7784. cap_line(PSTR("EEPROM")
  7785. #if ENABLED(EEPROM_SETTINGS)
  7786. , true
  7787. #endif
  7788. );
  7789. // Volumetric Extrusion (M200)
  7790. cap_line(PSTR("VOLUMETRIC")
  7791. #if DISABLED(NO_VOLUMETRICS)
  7792. , true
  7793. #endif
  7794. );
  7795. // AUTOREPORT_TEMP (M155)
  7796. cap_line(PSTR("AUTOREPORT_TEMP")
  7797. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  7798. , true
  7799. #endif
  7800. );
  7801. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  7802. cap_line(PSTR("PROGRESS"));
  7803. // Print Job timer M75, M76, M77
  7804. cap_line(PSTR("PRINT_JOB"), true);
  7805. // AUTOLEVEL (G29)
  7806. cap_line(PSTR("AUTOLEVEL")
  7807. #if HAS_AUTOLEVEL
  7808. , true
  7809. #endif
  7810. );
  7811. // Z_PROBE (G30)
  7812. cap_line(PSTR("Z_PROBE")
  7813. #if HAS_BED_PROBE
  7814. , true
  7815. #endif
  7816. );
  7817. // MESH_REPORT (M420 V)
  7818. cap_line(PSTR("LEVELING_DATA")
  7819. #if HAS_LEVELING
  7820. , true
  7821. #endif
  7822. );
  7823. // BUILD_PERCENT (M73)
  7824. cap_line(PSTR("BUILD_PERCENT")
  7825. #if ENABLED(LCD_SET_PROGRESS_MANUALLY)
  7826. , true
  7827. #endif
  7828. );
  7829. // SOFTWARE_POWER (M80, M81)
  7830. cap_line(PSTR("SOFTWARE_POWER")
  7831. #if HAS_POWER_SWITCH
  7832. , true
  7833. #endif
  7834. );
  7835. // CASE LIGHTS (M355)
  7836. cap_line(PSTR("TOGGLE_LIGHTS")
  7837. #if HAS_CASE_LIGHT
  7838. , true
  7839. #endif
  7840. );
  7841. cap_line(PSTR("CASE_LIGHT_BRIGHTNESS")
  7842. #if HAS_CASE_LIGHT
  7843. , USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)
  7844. #endif
  7845. );
  7846. // EMERGENCY_PARSER (M108, M112, M410)
  7847. cap_line(PSTR("EMERGENCY_PARSER")
  7848. #if ENABLED(EMERGENCY_PARSER)
  7849. , true
  7850. #endif
  7851. );
  7852. // AUTOREPORT_SD_STATUS (M27 extension)
  7853. cap_line(PSTR("AUTOREPORT_SD_STATUS")
  7854. #if ENABLED(AUTO_REPORT_SD_STATUS)
  7855. , true
  7856. #endif
  7857. );
  7858. // THERMAL_PROTECTION
  7859. cap_line(PSTR("THERMAL_PROTECTION")
  7860. #if ENABLED(THERMAL_PROTECTION_HOTENDS) && ENABLED(THERMAL_PROTECTION_BED)
  7861. , true
  7862. #endif
  7863. );
  7864. #endif // EXTENDED_CAPABILITIES_REPORT
  7865. }
  7866. /**
  7867. * M117: Set LCD Status Message
  7868. */
  7869. inline void gcode_M117() {
  7870. if (parser.string_arg[0])
  7871. lcd_setstatus(parser.string_arg);
  7872. else
  7873. lcd_reset_status();
  7874. }
  7875. /**
  7876. * M118: Display a message in the host console.
  7877. *
  7878. * A1 Prepend '// ' for an action command, as in OctoPrint
  7879. * E1 Have the host 'echo:' the text
  7880. */
  7881. inline void gcode_M118() {
  7882. bool hasE = false, hasA = false;
  7883. char *p = parser.string_arg;
  7884. for (uint8_t i = 2; i--;)
  7885. if ((p[0] == 'A' || p[0] == 'E') && p[1] == '1') {
  7886. if (p[0] == 'A') hasA = true;
  7887. if (p[0] == 'E') hasE = true;
  7888. p += 2;
  7889. while (*p == ' ') ++p;
  7890. }
  7891. if (hasE) SERIAL_ECHO_START();
  7892. if (hasA) SERIAL_ECHOPGM("// ");
  7893. SERIAL_ECHOLN(p);
  7894. }
  7895. /**
  7896. * M119: Output endstop states to serial output
  7897. */
  7898. inline void gcode_M119() { endstops.M119(); }
  7899. /**
  7900. * M120: Enable endstops and set non-homing endstop state to "enabled"
  7901. */
  7902. inline void gcode_M120() { endstops.enable_globally(true); }
  7903. /**
  7904. * M121: Disable endstops and set non-homing endstop state to "disabled"
  7905. */
  7906. inline void gcode_M121() { endstops.enable_globally(false); }
  7907. #if ENABLED(PARK_HEAD_ON_PAUSE)
  7908. /**
  7909. * M125: Store current position and move to filament change position.
  7910. * Called on pause (by M25) to prevent material leaking onto the
  7911. * object. On resume (M24) the head will be moved back and the
  7912. * print will resume.
  7913. *
  7914. * If Marlin is compiled without SD Card support, M125 can be
  7915. * used directly to pause the print and move to park position,
  7916. * resuming with a button click or M108.
  7917. *
  7918. * L = override retract length
  7919. * X = override X
  7920. * Y = override Y
  7921. * Z = override Z raise
  7922. */
  7923. inline void gcode_M125() {
  7924. // Initial retract before move to filament change position
  7925. const float retract = -ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  7926. #ifdef PAUSE_PARK_RETRACT_LENGTH
  7927. + (PAUSE_PARK_RETRACT_LENGTH)
  7928. #endif
  7929. );
  7930. point_t park_point = NOZZLE_PARK_POINT;
  7931. // Move XY axes to filament change position or given position
  7932. if (parser.seenval('X')) park_point.x = parser.linearval('X');
  7933. if (parser.seenval('Y')) park_point.y = parser.linearval('Y');
  7934. // Lift Z axis
  7935. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  7936. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE) && DISABLED(DELTA)
  7937. park_point.x += (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0);
  7938. park_point.y += (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0);
  7939. #endif
  7940. #if DISABLED(SDSUPPORT)
  7941. const bool job_running = print_job_timer.isRunning();
  7942. #endif
  7943. if (pause_print(retract, park_point)) {
  7944. #if DISABLED(SDSUPPORT)
  7945. // Wait for lcd click or M108
  7946. wait_for_filament_reload();
  7947. // Return to print position and continue
  7948. resume_print();
  7949. if (job_running) print_job_timer.start();
  7950. #endif
  7951. }
  7952. }
  7953. #endif // PARK_HEAD_ON_PAUSE
  7954. #if HAS_COLOR_LEDS
  7955. /**
  7956. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  7957. * and Brightness - Use P (for NEOPIXEL only)
  7958. *
  7959. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  7960. * If brightness is left out, no value changed
  7961. *
  7962. * Examples:
  7963. *
  7964. * M150 R255 ; Turn LED red
  7965. * M150 R255 U127 ; Turn LED orange (PWM only)
  7966. * M150 ; Turn LED off
  7967. * M150 R U B ; Turn LED white
  7968. * M150 W ; Turn LED white using a white LED
  7969. * M150 P127 ; Set LED 50% brightness
  7970. * M150 P ; Set LED full brightness
  7971. */
  7972. inline void gcode_M150() {
  7973. leds.set_color(MakeLEDColor(
  7974. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  7975. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  7976. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  7977. parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  7978. parser.seen('P') ? (parser.has_value() ? parser.value_byte() : 255) : pixels.getBrightness()
  7979. ));
  7980. }
  7981. #endif // HAS_COLOR_LEDS
  7982. #if DISABLED(NO_VOLUMETRICS)
  7983. /**
  7984. * M200: Set filament diameter and set E axis units to cubic units
  7985. *
  7986. * T<extruder> - Optional extruder number. Current extruder if omitted.
  7987. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  7988. */
  7989. inline void gcode_M200() {
  7990. if (get_target_extruder_from_command(200)) return;
  7991. if (parser.seen('D')) {
  7992. // setting any extruder filament size disables volumetric on the assumption that
  7993. // slicers either generate in extruder values as cubic mm or as as filament feeds
  7994. // for all extruders
  7995. if ( (parser.volumetric_enabled = (parser.value_linear_units() != 0)) )
  7996. planner.set_filament_size(target_extruder, parser.value_linear_units());
  7997. }
  7998. planner.calculate_volumetric_multipliers();
  7999. }
  8000. #endif // !NO_VOLUMETRICS
  8001. /**
  8002. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  8003. *
  8004. * With multiple extruders use T to specify which one.
  8005. */
  8006. inline void gcode_M201() {
  8007. GET_TARGET_EXTRUDER(201);
  8008. LOOP_NUM_AXIS(i) {
  8009. if (parser.seen(RAW_AXIS_CODES(i))) {
  8010. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  8011. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  8012. }
  8013. }
  8014. // 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)
  8015. planner.reset_acceleration_rates();
  8016. }
  8017. #if 0 // Not used for Sprinter/grbl gen6
  8018. inline void gcode_M202() {
  8019. LOOP_XYZE(i) {
  8020. if (parser.seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = parser.value_axis_units((AxisEnum)i) * planner.axis_steps_per_mm[i];
  8021. }
  8022. }
  8023. #endif
  8024. /**
  8025. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  8026. *
  8027. * With multiple extruders use T to specify which one.
  8028. */
  8029. inline void gcode_M203() {
  8030. GET_TARGET_EXTRUDER(203);
  8031. LOOP_NUM_AXIS(i)
  8032. if (parser.seen(RAW_AXIS_CODES(i))) {
  8033. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  8034. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  8035. }
  8036. }
  8037. /**
  8038. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  8039. *
  8040. * P = Printing moves
  8041. * R = Retract only (no X, Y, Z) moves
  8042. * T = Travel (non printing) moves
  8043. */
  8044. inline void gcode_M204() {
  8045. bool report = true;
  8046. if (parser.seenval('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  8047. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  8048. report = false;
  8049. }
  8050. if (parser.seenval('P')) {
  8051. planner.acceleration = parser.value_linear_units();
  8052. report = false;
  8053. }
  8054. if (parser.seenval('R')) {
  8055. planner.retract_acceleration = parser.value_linear_units();
  8056. report = false;
  8057. }
  8058. if (parser.seenval('T')) {
  8059. planner.travel_acceleration = parser.value_linear_units();
  8060. report = false;
  8061. }
  8062. if (report) {
  8063. SERIAL_ECHOPAIR("Acceleration: P", planner.acceleration);
  8064. SERIAL_ECHOPAIR(" R", planner.retract_acceleration);
  8065. SERIAL_ECHOLNPAIR(" T", planner.travel_acceleration);
  8066. }
  8067. }
  8068. /**
  8069. * M205: Set Advanced Settings
  8070. *
  8071. * Q = Min Segment Time (µs)
  8072. * S = Min Feed Rate (units/s)
  8073. * T = Min Travel Feed Rate (units/s)
  8074. * X = Max X Jerk (units/sec^2)
  8075. * Y = Max Y Jerk (units/sec^2)
  8076. * Z = Max Z Jerk (units/sec^2)
  8077. * E = Max E Jerk (units/sec^2)
  8078. * J = Junction Deviation (mm) (Requires JUNCTION_DEVIATION)
  8079. */
  8080. inline void gcode_M205() {
  8081. if (parser.seen('Q')) planner.min_segment_time_us = parser.value_ulong();
  8082. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  8083. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  8084. #if ENABLED(JUNCTION_DEVIATION)
  8085. if (parser.seen('J')) {
  8086. const float junc_dev = parser.value_linear_units();
  8087. if (WITHIN(junc_dev, 0.01f, 0.3f)) {
  8088. planner.junction_deviation_mm = junc_dev;
  8089. planner.recalculate_max_e_jerk();
  8090. }
  8091. else {
  8092. SERIAL_ERROR_START();
  8093. SERIAL_ERRORLNPGM("?J out of range (0.01 to 0.3)");
  8094. }
  8095. }
  8096. #else
  8097. #if ENABLED(HANGPRINTER)
  8098. if (parser.seen('A')) planner.max_jerk[A_AXIS] = parser.value_linear_units();
  8099. if (parser.seen('B')) planner.max_jerk[B_AXIS] = parser.value_linear_units();
  8100. if (parser.seen('C')) planner.max_jerk[C_AXIS] = parser.value_linear_units();
  8101. if (parser.seen('D')) planner.max_jerk[D_AXIS] = parser.value_linear_units();
  8102. #else
  8103. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  8104. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  8105. if (parser.seen('Z')) {
  8106. planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  8107. #if HAS_MESH
  8108. if (planner.max_jerk[Z_AXIS] <= 0.1f)
  8109. SERIAL_ECHOLNPGM("WARNING! Low Z Jerk may lead to unwanted pauses.");
  8110. #endif
  8111. }
  8112. #endif
  8113. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  8114. #endif
  8115. }
  8116. #if HAS_M206_COMMAND
  8117. /**
  8118. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  8119. *
  8120. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  8121. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  8122. * *** In the next 1.2 release, it will simply be disabled by default.
  8123. */
  8124. inline void gcode_M206() {
  8125. LOOP_XYZ(i)
  8126. if (parser.seen(axis_codes[i]))
  8127. set_home_offset((AxisEnum)i, parser.value_linear_units());
  8128. #if ENABLED(MORGAN_SCARA)
  8129. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_float()); // Theta
  8130. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_float()); // Psi
  8131. #endif
  8132. report_current_position();
  8133. }
  8134. #endif // HAS_M206_COMMAND
  8135. #if ENABLED(DELTA)
  8136. /**
  8137. * M665: Set delta configurations
  8138. *
  8139. * H = delta height
  8140. * L = diagonal rod
  8141. * R = delta radius
  8142. * S = segments per second
  8143. * B = delta calibration radius
  8144. * X = Alpha (Tower 1) angle trim
  8145. * Y = Beta (Tower 2) angle trim
  8146. * Z = Gamma (Tower 3) angle trim
  8147. */
  8148. inline void gcode_M665() {
  8149. if (parser.seen('H')) delta_height = parser.value_linear_units();
  8150. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  8151. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  8152. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8153. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  8154. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  8155. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  8156. if (parser.seen('Z')) delta_tower_angle_trim[C_AXIS] = parser.value_float();
  8157. recalc_delta_settings();
  8158. }
  8159. /**
  8160. * M666: Set delta endstop adjustment
  8161. */
  8162. inline void gcode_M666() {
  8163. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8164. if (DEBUGGING(LEVELING)) {
  8165. SERIAL_ECHOLNPGM(">>> gcode_M666");
  8166. }
  8167. #endif
  8168. LOOP_XYZ(i) {
  8169. if (parser.seen(axis_codes[i])) {
  8170. if (parser.value_linear_units() * Z_HOME_DIR <= 0)
  8171. delta_endstop_adj[i] = parser.value_linear_units();
  8172. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8173. if (DEBUGGING(LEVELING)) {
  8174. SERIAL_ECHOPAIR("delta_endstop_adj[", axis_codes[i]);
  8175. SERIAL_ECHOLNPAIR("] = ", delta_endstop_adj[i]);
  8176. }
  8177. #endif
  8178. }
  8179. }
  8180. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8181. if (DEBUGGING(LEVELING)) {
  8182. SERIAL_ECHOLNPGM("<<< gcode_M666");
  8183. }
  8184. #endif
  8185. }
  8186. #elif IS_SCARA
  8187. /**
  8188. * M665: Set SCARA settings
  8189. *
  8190. * Parameters:
  8191. *
  8192. * S[segments-per-second] - Segments-per-second
  8193. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  8194. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  8195. *
  8196. * A, P, and X are all aliases for the shoulder angle
  8197. * B, T, and Y are all aliases for the elbow angle
  8198. */
  8199. inline void gcode_M665() {
  8200. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8201. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  8202. const uint8_t sumAPX = hasA + hasP + hasX;
  8203. if (sumAPX == 1)
  8204. home_offset[A_AXIS] = parser.value_float();
  8205. else if (sumAPX > 1) {
  8206. SERIAL_ERROR_START();
  8207. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  8208. return;
  8209. }
  8210. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  8211. const uint8_t sumBTY = hasB + hasT + hasY;
  8212. if (sumBTY == 1)
  8213. home_offset[B_AXIS] = parser.value_float();
  8214. else if (sumBTY > 1) {
  8215. SERIAL_ERROR_START();
  8216. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  8217. return;
  8218. }
  8219. }
  8220. #elif ENABLED(HANGPRINTER)
  8221. /**
  8222. * M665: Set HANGPRINTER settings
  8223. *
  8224. * Parameters:
  8225. *
  8226. * W[anchor_A_y] - A-anchor's y coordinate (see note)
  8227. * E[anchor_A_z] - A-anchor's z coordinate (see note)
  8228. * R[anchor_B_x] - B-anchor's x coordinate (see note)
  8229. * T[anchor_B_y] - B-anchor's y coordinate (see note)
  8230. * Y[anchor_B_z] - B-anchor's z coordinate (see note)
  8231. * U[anchor_C_x] - C-anchor's x coordinate (see note)
  8232. * I[anchor_C_y] - C-anchor's y coordinate (see note)
  8233. * O[anchor_C_z] - C-anchor's z coordinate (see note)
  8234. * P[anchor_D_z] - D-anchor's z coordinate (see note)
  8235. * S[segments-per-second] - Segments-per-second
  8236. *
  8237. * Note: All xyz coordinates are measured relative to the line's pivot point in the mover,
  8238. * when it is at its home position (nozzle in (0,0,0), and lines tight).
  8239. * The y-axis is defined to be horizontal right above/below the A-lines when mover is at home.
  8240. * The z-axis is along the vertical direction.
  8241. */
  8242. inline void gcode_M665() {
  8243. if (parser.seen('W')) anchor_A_y = parser.value_float();
  8244. if (parser.seen('E')) anchor_A_z = parser.value_float();
  8245. if (parser.seen('R')) anchor_B_x = parser.value_float();
  8246. if (parser.seen('T')) anchor_B_y = parser.value_float();
  8247. if (parser.seen('Y')) anchor_B_z = parser.value_float();
  8248. if (parser.seen('U')) anchor_C_x = parser.value_float();
  8249. if (parser.seen('I')) anchor_C_y = parser.value_float();
  8250. if (parser.seen('O')) anchor_C_z = parser.value_float();
  8251. if (parser.seen('P')) anchor_D_z = parser.value_float();
  8252. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8253. recalc_hangprinter_settings();
  8254. }
  8255. #elif ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  8256. /**
  8257. * M666: Set Dual Endstops offsets for X, Y, and/or Z.
  8258. * With no parameters report current offsets.
  8259. */
  8260. inline void gcode_M666() {
  8261. bool report = true;
  8262. #if ENABLED(X_DUAL_ENDSTOPS)
  8263. if (parser.seenval('X')) {
  8264. endstops.x_endstop_adj = parser.value_linear_units();
  8265. report = false;
  8266. }
  8267. #endif
  8268. #if ENABLED(Y_DUAL_ENDSTOPS)
  8269. if (parser.seenval('Y')) {
  8270. endstops.y_endstop_adj = parser.value_linear_units();
  8271. report = false;
  8272. }
  8273. #endif
  8274. #if ENABLED(Z_DUAL_ENDSTOPS)
  8275. if (parser.seenval('Z')) {
  8276. endstops.z_endstop_adj = parser.value_linear_units();
  8277. report = false;
  8278. }
  8279. #endif
  8280. if (report) {
  8281. SERIAL_ECHOPGM("Dual Endstop Adjustment (mm): ");
  8282. #if ENABLED(X_DUAL_ENDSTOPS)
  8283. SERIAL_ECHOPAIR(" X", endstops.x_endstop_adj);
  8284. #endif
  8285. #if ENABLED(Y_DUAL_ENDSTOPS)
  8286. SERIAL_ECHOPAIR(" Y", endstops.y_endstop_adj);
  8287. #endif
  8288. #if ENABLED(Z_DUAL_ENDSTOPS)
  8289. SERIAL_ECHOPAIR(" Z", endstops.z_endstop_adj);
  8290. #endif
  8291. SERIAL_EOL();
  8292. }
  8293. }
  8294. #endif // X_DUAL_ENDSTOPS || Y_DUAL_ENDSTOPS || Z_DUAL_ENDSTOPS
  8295. #if ENABLED(FWRETRACT)
  8296. /**
  8297. * M207: Set firmware retraction values
  8298. *
  8299. * S[+units] retract_length
  8300. * W[+units] swap_retract_length (multi-extruder)
  8301. * F[units/min] retract_feedrate_mm_s
  8302. * Z[units] retract_zlift
  8303. */
  8304. inline void gcode_M207() {
  8305. if (parser.seen('S')) fwretract.retract_length = parser.value_axis_units(E_AXIS);
  8306. if (parser.seen('F')) fwretract.retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8307. if (parser.seen('Z')) fwretract.retract_zlift = parser.value_linear_units();
  8308. if (parser.seen('W')) fwretract.swap_retract_length = parser.value_axis_units(E_AXIS);
  8309. }
  8310. /**
  8311. * M208: Set firmware un-retraction values
  8312. *
  8313. * S[+units] retract_recover_length (in addition to M207 S*)
  8314. * W[+units] swap_retract_recover_length (multi-extruder)
  8315. * F[units/min] retract_recover_feedrate_mm_s
  8316. * R[units/min] swap_retract_recover_feedrate_mm_s
  8317. */
  8318. inline void gcode_M208() {
  8319. if (parser.seen('S')) fwretract.retract_recover_length = parser.value_axis_units(E_AXIS);
  8320. if (parser.seen('F')) fwretract.retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8321. if (parser.seen('R')) fwretract.swap_retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8322. if (parser.seen('W')) fwretract.swap_retract_recover_length = parser.value_axis_units(E_AXIS);
  8323. }
  8324. /**
  8325. * M209: Enable automatic retract (M209 S1)
  8326. * For slicers that don't support G10/11, reversed extrude-only
  8327. * moves will be classified as retraction.
  8328. */
  8329. inline void gcode_M209() {
  8330. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) {
  8331. if (parser.seen('S')) {
  8332. fwretract.autoretract_enabled = parser.value_bool();
  8333. for (uint8_t i = 0; i < EXTRUDERS; i++) fwretract.retracted[i] = false;
  8334. }
  8335. }
  8336. }
  8337. #endif // FWRETRACT
  8338. /**
  8339. * M211: Enable, Disable, and/or Report software endstops
  8340. *
  8341. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  8342. */
  8343. inline void gcode_M211() {
  8344. SERIAL_ECHO_START();
  8345. #if HAS_SOFTWARE_ENDSTOPS
  8346. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  8347. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  8348. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  8349. #else
  8350. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  8351. SERIAL_ECHOPGM(MSG_OFF);
  8352. #endif
  8353. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  8354. SERIAL_ECHOPAIR( MSG_X, LOGICAL_X_POSITION(soft_endstop_min[X_AXIS]));
  8355. SERIAL_ECHOPAIR(" " MSG_Y, LOGICAL_Y_POSITION(soft_endstop_min[Y_AXIS]));
  8356. SERIAL_ECHOPAIR(" " MSG_Z, LOGICAL_Z_POSITION(soft_endstop_min[Z_AXIS]));
  8357. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  8358. SERIAL_ECHOPAIR( MSG_X, LOGICAL_X_POSITION(soft_endstop_max[X_AXIS]));
  8359. SERIAL_ECHOPAIR(" " MSG_Y, LOGICAL_Y_POSITION(soft_endstop_max[Y_AXIS]));
  8360. SERIAL_ECHOLNPAIR(" " MSG_Z, LOGICAL_Z_POSITION(soft_endstop_max[Z_AXIS]));
  8361. }
  8362. #if HOTENDS > 1
  8363. /**
  8364. * M218 - Set/get hotend offset (in linear units)
  8365. *
  8366. * T<tool>
  8367. * X<xoffset>
  8368. * Y<yoffset>
  8369. * Z<zoffset> - Available with DUAL_X_CARRIAGE, SWITCHING_NOZZLE, and PARKING_EXTRUDER
  8370. */
  8371. inline void gcode_M218() {
  8372. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  8373. bool report = true;
  8374. if (parser.seenval('X')) {
  8375. hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  8376. report = false;
  8377. }
  8378. if (parser.seenval('Y')) {
  8379. hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  8380. report = false;
  8381. }
  8382. #if HAS_HOTEND_OFFSET_Z
  8383. if (parser.seenval('Z')) {
  8384. hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  8385. report = false;
  8386. }
  8387. #endif
  8388. if (report) {
  8389. SERIAL_ECHO_START();
  8390. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  8391. HOTEND_LOOP() {
  8392. SERIAL_CHAR(' ');
  8393. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  8394. SERIAL_CHAR(',');
  8395. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  8396. #if HAS_HOTEND_OFFSET_Z
  8397. SERIAL_CHAR(',');
  8398. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  8399. #endif
  8400. }
  8401. SERIAL_EOL();
  8402. }
  8403. #if ENABLED(DELTA)
  8404. if (target_extruder == active_extruder)
  8405. do_blocking_move_to_xy(current_position[X_AXIS], current_position[Y_AXIS], planner.max_feedrate_mm_s[X_AXIS]);
  8406. #endif
  8407. }
  8408. #endif // HOTENDS > 1
  8409. /**
  8410. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  8411. */
  8412. inline void gcode_M220() {
  8413. if (parser.seenval('S')) feedrate_percentage = parser.value_int();
  8414. }
  8415. /**
  8416. * M221: Set extrusion percentage (M221 T0 S95)
  8417. */
  8418. inline void gcode_M221() {
  8419. if (get_target_extruder_from_command(221)) return;
  8420. if (parser.seenval('S')) {
  8421. planner.flow_percentage[target_extruder] = parser.value_int();
  8422. planner.refresh_e_factor(target_extruder);
  8423. }
  8424. else {
  8425. SERIAL_ECHO_START();
  8426. SERIAL_CHAR('E');
  8427. SERIAL_CHAR('0' + target_extruder);
  8428. SERIAL_ECHOPAIR(" Flow: ", planner.flow_percentage[target_extruder]);
  8429. SERIAL_CHAR('%');
  8430. SERIAL_EOL();
  8431. }
  8432. }
  8433. /**
  8434. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  8435. */
  8436. inline void gcode_M226() {
  8437. if (parser.seen('P')) {
  8438. const int pin = parser.value_int(), pin_state = parser.intval('S', -1);
  8439. if (WITHIN(pin_state, -1, 1) && pin > -1) {
  8440. if (pin_is_protected(pin))
  8441. protected_pin_err();
  8442. else {
  8443. int target = LOW;
  8444. planner.synchronize();
  8445. pinMode(pin, INPUT);
  8446. switch (pin_state) {
  8447. case 1: target = HIGH; break;
  8448. case 0: target = LOW; break;
  8449. case -1: target = !digitalRead(pin); break;
  8450. }
  8451. while (digitalRead(pin) != target) idle();
  8452. }
  8453. } // pin_state -1 0 1 && pin > -1
  8454. } // parser.seen('P')
  8455. }
  8456. #if ENABLED(EXPERIMENTAL_I2CBUS)
  8457. /**
  8458. * M260: Send data to a I2C slave device
  8459. *
  8460. * This is a PoC, the formating and arguments for the GCODE will
  8461. * change to be more compatible, the current proposal is:
  8462. *
  8463. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  8464. *
  8465. * M260 B<byte-1 value in base 10>
  8466. * M260 B<byte-2 value in base 10>
  8467. * M260 B<byte-3 value in base 10>
  8468. *
  8469. * M260 S1 ; Send the buffered data and reset the buffer
  8470. * M260 R1 ; Reset the buffer without sending data
  8471. *
  8472. */
  8473. inline void gcode_M260() {
  8474. // Set the target address
  8475. if (parser.seen('A')) i2c.address(parser.value_byte());
  8476. // Add a new byte to the buffer
  8477. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  8478. // Flush the buffer to the bus
  8479. if (parser.seen('S')) i2c.send();
  8480. // Reset and rewind the buffer
  8481. else if (parser.seen('R')) i2c.reset();
  8482. }
  8483. /**
  8484. * M261: Request X bytes from I2C slave device
  8485. *
  8486. * Usage: M261 A<slave device address base 10> B<number of bytes>
  8487. */
  8488. inline void gcode_M261() {
  8489. if (parser.seen('A')) i2c.address(parser.value_byte());
  8490. uint8_t bytes = parser.byteval('B', 1);
  8491. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  8492. i2c.relay(bytes);
  8493. }
  8494. else {
  8495. SERIAL_ERROR_START();
  8496. SERIAL_ERRORLNPGM("Bad i2c request");
  8497. }
  8498. }
  8499. #endif // EXPERIMENTAL_I2CBUS
  8500. #if HAS_SERVOS
  8501. /**
  8502. * M280: Get or set servo position. P<index> [S<angle>]
  8503. */
  8504. inline void gcode_M280() {
  8505. if (!parser.seen('P')) return;
  8506. const int servo_index = parser.value_int();
  8507. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  8508. if (parser.seen('S'))
  8509. MOVE_SERVO(servo_index, parser.value_int());
  8510. else {
  8511. SERIAL_ECHO_START();
  8512. SERIAL_ECHOPAIR(" Servo ", servo_index);
  8513. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  8514. }
  8515. }
  8516. else {
  8517. SERIAL_ERROR_START();
  8518. SERIAL_ECHOPAIR("Servo ", servo_index);
  8519. SERIAL_ECHOLNPGM(" out of range");
  8520. }
  8521. }
  8522. #endif // HAS_SERVOS
  8523. #if ENABLED(BABYSTEPPING)
  8524. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8525. FORCE_INLINE void mod_zprobe_zoffset(const float &offs) {
  8526. zprobe_zoffset += offs;
  8527. SERIAL_ECHO_START();
  8528. SERIAL_ECHOLNPAIR(MSG_PROBE_Z_OFFSET ": ", zprobe_zoffset);
  8529. }
  8530. #endif
  8531. /**
  8532. * M290: Babystepping
  8533. */
  8534. inline void gcode_M290() {
  8535. #if ENABLED(BABYSTEP_XY)
  8536. for (uint8_t a = X_AXIS; a <= Z_AXIS; a++)
  8537. if (parser.seenval(axis_codes[a]) || (a == Z_AXIS && parser.seenval('S'))) {
  8538. const float offs = constrain(parser.value_axis_units((AxisEnum)a), -2, 2);
  8539. thermalManager.babystep_axis((AxisEnum)a, offs * planner.axis_steps_per_mm[a]);
  8540. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8541. if (a == Z_AXIS && (!parser.seen('P') || parser.value_bool())) mod_zprobe_zoffset(offs);
  8542. #endif
  8543. }
  8544. #else
  8545. if (parser.seenval('Z') || parser.seenval('S')) {
  8546. const float offs = constrain(parser.value_axis_units(Z_AXIS), -2, 2);
  8547. thermalManager.babystep_axis(Z_AXIS, offs * planner.axis_steps_per_mm[Z_AXIS]);
  8548. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8549. if (!parser.seen('P') || parser.value_bool()) mod_zprobe_zoffset(offs);
  8550. #endif
  8551. }
  8552. #endif
  8553. }
  8554. #endif // BABYSTEPPING
  8555. #if HAS_BUZZER
  8556. /**
  8557. * M300: Play beep sound S<frequency Hz> P<duration ms>
  8558. */
  8559. inline void gcode_M300() {
  8560. uint16_t const frequency = parser.ushortval('S', 260);
  8561. uint16_t duration = parser.ushortval('P', 1000);
  8562. // Limits the tone duration to 0-5 seconds.
  8563. NOMORE(duration, 5000);
  8564. BUZZ(duration, frequency);
  8565. }
  8566. #endif // HAS_BUZZER
  8567. #if ENABLED(PIDTEMP)
  8568. /**
  8569. * M301: Set PID parameters P I D (and optionally C, L)
  8570. *
  8571. * P[float] Kp term
  8572. * I[float] Ki term (unscaled)
  8573. * D[float] Kd term (unscaled)
  8574. *
  8575. * With PID_EXTRUSION_SCALING:
  8576. *
  8577. * C[float] Kc term
  8578. * L[int] LPQ length
  8579. */
  8580. inline void gcode_M301() {
  8581. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  8582. // default behaviour (omitting E parameter) is to update for extruder 0 only
  8583. const uint8_t e = parser.byteval('E'); // extruder being updated
  8584. if (e < HOTENDS) { // catch bad input value
  8585. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  8586. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  8587. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  8588. #if ENABLED(PID_EXTRUSION_SCALING)
  8589. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  8590. if (parser.seen('L')) thermalManager.lpq_len = parser.value_float();
  8591. NOMORE(thermalManager.lpq_len, LPQ_MAX_LEN);
  8592. NOLESS(thermalManager.lpq_len, 0);
  8593. #endif
  8594. thermalManager.updatePID();
  8595. SERIAL_ECHO_START();
  8596. #if ENABLED(PID_PARAMS_PER_HOTEND)
  8597. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  8598. #endif // PID_PARAMS_PER_HOTEND
  8599. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  8600. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  8601. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  8602. #if ENABLED(PID_EXTRUSION_SCALING)
  8603. //Kc does not have scaling applied above, or in resetting defaults
  8604. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  8605. #endif
  8606. SERIAL_EOL();
  8607. }
  8608. else {
  8609. SERIAL_ERROR_START();
  8610. SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER);
  8611. }
  8612. }
  8613. #endif // PIDTEMP
  8614. #if ENABLED(PIDTEMPBED)
  8615. inline void gcode_M304() {
  8616. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  8617. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  8618. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  8619. SERIAL_ECHO_START();
  8620. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  8621. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  8622. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  8623. }
  8624. #endif // PIDTEMPBED
  8625. #if defined(CHDK) || HAS_PHOTOGRAPH
  8626. /**
  8627. * M240: Trigger a camera by emulating a Canon RC-1
  8628. * See http://www.doc-diy.net/photo/rc-1_hacked/
  8629. */
  8630. inline void gcode_M240() {
  8631. #ifdef CHDK
  8632. OUT_WRITE(CHDK, HIGH);
  8633. chdkHigh = millis();
  8634. chdkActive = true;
  8635. #elif HAS_PHOTOGRAPH
  8636. const uint8_t NUM_PULSES = 16;
  8637. const float PULSE_LENGTH = 0.01524;
  8638. for (int i = 0; i < NUM_PULSES; i++) {
  8639. WRITE(PHOTOGRAPH_PIN, HIGH);
  8640. _delay_ms(PULSE_LENGTH);
  8641. WRITE(PHOTOGRAPH_PIN, LOW);
  8642. _delay_ms(PULSE_LENGTH);
  8643. }
  8644. delay(7.33);
  8645. for (int i = 0; i < NUM_PULSES; i++) {
  8646. WRITE(PHOTOGRAPH_PIN, HIGH);
  8647. _delay_ms(PULSE_LENGTH);
  8648. WRITE(PHOTOGRAPH_PIN, LOW);
  8649. _delay_ms(PULSE_LENGTH);
  8650. }
  8651. #endif // !CHDK && HAS_PHOTOGRAPH
  8652. }
  8653. #endif // CHDK || PHOTOGRAPH_PIN
  8654. #if HAS_LCD_CONTRAST
  8655. /**
  8656. * M250: Read and optionally set the LCD contrast
  8657. */
  8658. inline void gcode_M250() {
  8659. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  8660. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  8661. SERIAL_PROTOCOL(lcd_contrast);
  8662. SERIAL_EOL();
  8663. }
  8664. #endif // HAS_LCD_CONTRAST
  8665. #if ENABLED(PREVENT_COLD_EXTRUSION)
  8666. /**
  8667. * M302: Allow cold extrudes, or set the minimum extrude temperature
  8668. *
  8669. * S<temperature> sets the minimum extrude temperature
  8670. * P<bool> enables (1) or disables (0) cold extrusion
  8671. *
  8672. * Examples:
  8673. *
  8674. * M302 ; report current cold extrusion state
  8675. * M302 P0 ; enable cold extrusion checking
  8676. * M302 P1 ; disables cold extrusion checking
  8677. * M302 S0 ; always allow extrusion (disables checking)
  8678. * M302 S170 ; only allow extrusion above 170
  8679. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  8680. */
  8681. inline void gcode_M302() {
  8682. const bool seen_S = parser.seen('S');
  8683. if (seen_S) {
  8684. thermalManager.extrude_min_temp = parser.value_celsius();
  8685. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  8686. }
  8687. if (parser.seen('P'))
  8688. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  8689. else if (!seen_S) {
  8690. // Report current state
  8691. SERIAL_ECHO_START();
  8692. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  8693. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  8694. SERIAL_ECHOLNPGM("C)");
  8695. }
  8696. }
  8697. #endif // PREVENT_COLD_EXTRUSION
  8698. /**
  8699. * M303: PID relay autotune
  8700. *
  8701. * S<temperature> sets the target temperature. (default 150C / 70C)
  8702. * E<extruder> (-1 for the bed) (default 0)
  8703. * C<cycles>
  8704. * U<bool> with a non-zero value will apply the result to current settings
  8705. */
  8706. inline void gcode_M303() {
  8707. #if HAS_PID_HEATING
  8708. const int e = parser.intval('E'), c = parser.intval('C', 5);
  8709. const bool u = parser.boolval('U');
  8710. int16_t temp = parser.celsiusval('S', e < 0 ? 70 : 150);
  8711. if (WITHIN(e, 0, HOTENDS - 1))
  8712. target_extruder = e;
  8713. #if DISABLED(BUSY_WHILE_HEATING)
  8714. KEEPALIVE_STATE(NOT_BUSY);
  8715. #endif
  8716. thermalManager.PID_autotune(temp, e, c, u);
  8717. #if DISABLED(BUSY_WHILE_HEATING)
  8718. KEEPALIVE_STATE(IN_HANDLER);
  8719. #endif
  8720. #else
  8721. SERIAL_ERROR_START();
  8722. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  8723. #endif
  8724. }
  8725. #if ENABLED(MORGAN_SCARA)
  8726. bool SCARA_move_to_cal(const uint8_t delta_a, const uint8_t delta_b) {
  8727. if (IsRunning()) {
  8728. forward_kinematics_SCARA(delta_a, delta_b);
  8729. destination[X_AXIS] = cartes[X_AXIS];
  8730. destination[Y_AXIS] = cartes[Y_AXIS];
  8731. destination[Z_AXIS] = current_position[Z_AXIS];
  8732. prepare_move_to_destination();
  8733. return true;
  8734. }
  8735. return false;
  8736. }
  8737. /**
  8738. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  8739. */
  8740. inline bool gcode_M360() {
  8741. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  8742. return SCARA_move_to_cal(0, 120);
  8743. }
  8744. /**
  8745. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  8746. */
  8747. inline bool gcode_M361() {
  8748. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  8749. return SCARA_move_to_cal(90, 130);
  8750. }
  8751. /**
  8752. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  8753. */
  8754. inline bool gcode_M362() {
  8755. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  8756. return SCARA_move_to_cal(60, 180);
  8757. }
  8758. /**
  8759. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  8760. */
  8761. inline bool gcode_M363() {
  8762. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  8763. return SCARA_move_to_cal(50, 90);
  8764. }
  8765. /**
  8766. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  8767. */
  8768. inline bool gcode_M364() {
  8769. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  8770. return SCARA_move_to_cal(45, 135);
  8771. }
  8772. #endif // SCARA
  8773. #if ENABLED(EXT_SOLENOID)
  8774. void enable_solenoid(const uint8_t num) {
  8775. switch (num) {
  8776. case 0:
  8777. OUT_WRITE(SOL0_PIN, HIGH);
  8778. break;
  8779. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  8780. case 1:
  8781. OUT_WRITE(SOL1_PIN, HIGH);
  8782. break;
  8783. #endif
  8784. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  8785. case 2:
  8786. OUT_WRITE(SOL2_PIN, HIGH);
  8787. break;
  8788. #endif
  8789. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  8790. case 3:
  8791. OUT_WRITE(SOL3_PIN, HIGH);
  8792. break;
  8793. #endif
  8794. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  8795. case 4:
  8796. OUT_WRITE(SOL4_PIN, HIGH);
  8797. break;
  8798. #endif
  8799. default:
  8800. SERIAL_ECHO_START();
  8801. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  8802. break;
  8803. }
  8804. }
  8805. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  8806. void disable_all_solenoids() {
  8807. OUT_WRITE(SOL0_PIN, LOW);
  8808. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  8809. OUT_WRITE(SOL1_PIN, LOW);
  8810. #endif
  8811. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  8812. OUT_WRITE(SOL2_PIN, LOW);
  8813. #endif
  8814. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  8815. OUT_WRITE(SOL3_PIN, LOW);
  8816. #endif
  8817. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  8818. OUT_WRITE(SOL4_PIN, LOW);
  8819. #endif
  8820. }
  8821. /**
  8822. * M380: Enable solenoid on the active extruder
  8823. */
  8824. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  8825. /**
  8826. * M381: Disable all solenoids
  8827. */
  8828. inline void gcode_M381() { disable_all_solenoids(); }
  8829. #endif // EXT_SOLENOID
  8830. /**
  8831. * M400: Finish all moves
  8832. */
  8833. inline void gcode_M400() { planner.synchronize(); }
  8834. #if HAS_BED_PROBE
  8835. /**
  8836. * M401: Deploy and activate the Z probe
  8837. */
  8838. inline void gcode_M401() {
  8839. DEPLOY_PROBE();
  8840. report_current_position();
  8841. }
  8842. /**
  8843. * M402: Deactivate and stow the Z probe
  8844. */
  8845. inline void gcode_M402() {
  8846. STOW_PROBE();
  8847. #ifdef Z_AFTER_PROBING
  8848. move_z_after_probing();
  8849. #endif
  8850. report_current_position();
  8851. }
  8852. #endif // HAS_BED_PROBE
  8853. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  8854. /**
  8855. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  8856. */
  8857. inline void gcode_M404() {
  8858. if (parser.seen('W')) {
  8859. filament_width_nominal = parser.value_linear_units();
  8860. planner.volumetric_area_nominal = CIRCLE_AREA(filament_width_nominal * 0.5);
  8861. }
  8862. else {
  8863. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  8864. SERIAL_PROTOCOLLN(filament_width_nominal);
  8865. }
  8866. }
  8867. /**
  8868. * M405: Turn on filament sensor for control
  8869. */
  8870. inline void gcode_M405() {
  8871. // This is technically a linear measurement, but since it's quantized to centimeters and is a different
  8872. // unit than everything else, it uses parser.value_byte() instead of parser.value_linear_units().
  8873. if (parser.seen('D')) {
  8874. meas_delay_cm = parser.value_byte();
  8875. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  8876. }
  8877. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  8878. const int8_t temp_ratio = thermalManager.widthFil_to_size_ratio();
  8879. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  8880. measurement_delay[i] = temp_ratio;
  8881. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  8882. }
  8883. filament_sensor = true;
  8884. }
  8885. /**
  8886. * M406: Turn off filament sensor for control
  8887. */
  8888. inline void gcode_M406() {
  8889. filament_sensor = false;
  8890. planner.calculate_volumetric_multipliers(); // Restore correct 'volumetric_multiplier' value
  8891. }
  8892. /**
  8893. * M407: Get measured filament diameter on serial output
  8894. */
  8895. inline void gcode_M407() {
  8896. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  8897. SERIAL_PROTOCOLLN(filament_width_meas);
  8898. }
  8899. #endif // FILAMENT_WIDTH_SENSOR
  8900. void quickstop_stepper() {
  8901. planner.quick_stop();
  8902. planner.synchronize();
  8903. set_current_from_steppers_for_axis(ALL_AXES);
  8904. SYNC_PLAN_POSITION_KINEMATIC();
  8905. }
  8906. #if HAS_LEVELING
  8907. //#define M420_C_USE_MEAN
  8908. /**
  8909. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  8910. *
  8911. * S[bool] Turns leveling on or off
  8912. * Z[height] Sets the Z fade height (0 or none to disable)
  8913. * V[bool] Verbose - Print the leveling grid
  8914. *
  8915. * With AUTO_BED_LEVELING_UBL only:
  8916. *
  8917. * L[index] Load UBL mesh from index (0 is default)
  8918. * T[map] 0:Human-readable 1:CSV 2:"LCD" 4:Compact
  8919. *
  8920. * With mesh-based leveling only:
  8921. *
  8922. * C Center mesh on the mean of the lowest and highest
  8923. */
  8924. inline void gcode_M420() {
  8925. const bool seen_S = parser.seen('S');
  8926. bool to_enable = seen_S ? parser.value_bool() : planner.leveling_active;
  8927. // If disabling leveling do it right away
  8928. // (Don't disable for just M420 or M420 V)
  8929. if (seen_S && !to_enable) set_bed_leveling_enabled(false);
  8930. const float oldpos[] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  8931. #if ENABLED(AUTO_BED_LEVELING_UBL)
  8932. // L to load a mesh from the EEPROM
  8933. if (parser.seen('L')) {
  8934. set_bed_leveling_enabled(false);
  8935. #if ENABLED(EEPROM_SETTINGS)
  8936. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.storage_slot;
  8937. const int16_t a = settings.calc_num_meshes();
  8938. if (!a) {
  8939. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  8940. return;
  8941. }
  8942. if (!WITHIN(storage_slot, 0, a - 1)) {
  8943. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  8944. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  8945. return;
  8946. }
  8947. settings.load_mesh(storage_slot);
  8948. ubl.storage_slot = storage_slot;
  8949. #else
  8950. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  8951. return;
  8952. #endif
  8953. }
  8954. // L or V display the map info
  8955. if (parser.seen('L') || parser.seen('V')) {
  8956. ubl.display_map(parser.byteval('T'));
  8957. SERIAL_ECHOPGM("Mesh is ");
  8958. if (!ubl.mesh_is_valid()) SERIAL_ECHOPGM("in");
  8959. SERIAL_ECHOLNPAIR("valid\nStorage slot: ", ubl.storage_slot);
  8960. }
  8961. #endif // AUTO_BED_LEVELING_UBL
  8962. #if HAS_MESH
  8963. #if ENABLED(MESH_BED_LEVELING)
  8964. #define Z_VALUES(X,Y) mbl.z_values[X][Y]
  8965. #else
  8966. #define Z_VALUES(X,Y) z_values[X][Y]
  8967. #endif
  8968. // Subtract the given value or the mean from all mesh values
  8969. if (leveling_is_valid() && parser.seen('C')) {
  8970. const float cval = parser.value_float();
  8971. #if ENABLED(AUTO_BED_LEVELING_UBL)
  8972. set_bed_leveling_enabled(false);
  8973. ubl.adjust_mesh_to_mean(true, cval);
  8974. #else
  8975. #if ENABLED(M420_C_USE_MEAN)
  8976. // Get the sum and average of all mesh values
  8977. float mesh_sum = 0;
  8978. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  8979. for (uint8_t y = GRID_MAX_POINTS_Y; y--;)
  8980. mesh_sum += Z_VALUES(x, y);
  8981. const float zmean = mesh_sum / float(GRID_MAX_POINTS);
  8982. #else
  8983. // Find the low and high mesh values
  8984. float lo_val = 100, hi_val = -100;
  8985. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  8986. for (uint8_t y = GRID_MAX_POINTS_Y; y--;) {
  8987. const float z = Z_VALUES(x, y);
  8988. NOMORE(lo_val, z);
  8989. NOLESS(hi_val, z);
  8990. }
  8991. // Take the mean of the lowest and highest
  8992. const float zmean = (lo_val + hi_val) / 2.0 + cval;
  8993. #endif
  8994. // If not very close to 0, adjust the mesh
  8995. if (!NEAR_ZERO(zmean)) {
  8996. set_bed_leveling_enabled(false);
  8997. // Subtract the mean from all values
  8998. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  8999. for (uint8_t y = GRID_MAX_POINTS_Y; y--;)
  9000. Z_VALUES(x, y) -= zmean;
  9001. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9002. bed_level_virt_interpolate();
  9003. #endif
  9004. }
  9005. #endif
  9006. }
  9007. #endif // HAS_MESH
  9008. // V to print the matrix or mesh
  9009. if (parser.seen('V')) {
  9010. #if ABL_PLANAR
  9011. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  9012. #else
  9013. if (leveling_is_valid()) {
  9014. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9015. print_bilinear_leveling_grid();
  9016. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9017. print_bilinear_leveling_grid_virt();
  9018. #endif
  9019. #elif ENABLED(MESH_BED_LEVELING)
  9020. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  9021. mbl.report_mesh();
  9022. #endif
  9023. }
  9024. #endif
  9025. }
  9026. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  9027. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units(), false);
  9028. #endif
  9029. // Enable leveling if specified, or if previously active
  9030. set_bed_leveling_enabled(to_enable);
  9031. // Error if leveling failed to enable or reenable
  9032. if (to_enable && !planner.leveling_active) {
  9033. SERIAL_ERROR_START();
  9034. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  9035. }
  9036. SERIAL_ECHO_START();
  9037. SERIAL_ECHOLNPAIR("Bed Leveling ", planner.leveling_active ? MSG_ON : MSG_OFF);
  9038. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  9039. SERIAL_ECHO_START();
  9040. SERIAL_ECHOPGM("Fade Height ");
  9041. if (planner.z_fade_height > 0.0)
  9042. SERIAL_ECHOLN(planner.z_fade_height);
  9043. else
  9044. SERIAL_ECHOLNPGM(MSG_OFF);
  9045. #endif
  9046. // Report change in position
  9047. if (memcmp(oldpos, current_position, sizeof(oldpos)))
  9048. report_current_position();
  9049. }
  9050. #endif // HAS_LEVELING
  9051. #if ENABLED(MESH_BED_LEVELING)
  9052. /**
  9053. * M421: Set a single Mesh Bed Leveling Z coordinate
  9054. *
  9055. * Usage:
  9056. * M421 X<linear> Y<linear> Z<linear>
  9057. * M421 X<linear> Y<linear> Q<offset>
  9058. * M421 I<xindex> J<yindex> Z<linear>
  9059. * M421 I<xindex> J<yindex> Q<offset>
  9060. */
  9061. inline void gcode_M421() {
  9062. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  9063. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(parser.value_linear_units()) : -1;
  9064. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  9065. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(parser.value_linear_units()) : -1;
  9066. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  9067. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  9068. SERIAL_ERROR_START();
  9069. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9070. }
  9071. else if (ix < 0 || iy < 0) {
  9072. SERIAL_ERROR_START();
  9073. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9074. }
  9075. else
  9076. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  9077. }
  9078. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9079. /**
  9080. * M421: Set a single Mesh Bed Leveling Z coordinate
  9081. *
  9082. * Usage:
  9083. * M421 I<xindex> J<yindex> Z<linear>
  9084. * M421 I<xindex> J<yindex> Q<offset>
  9085. */
  9086. inline void gcode_M421() {
  9087. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  9088. const bool hasI = ix >= 0,
  9089. hasJ = iy >= 0,
  9090. hasZ = parser.seen('Z'),
  9091. hasQ = !hasZ && parser.seen('Q');
  9092. if (!hasI || !hasJ || !(hasZ || hasQ)) {
  9093. SERIAL_ERROR_START();
  9094. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9095. }
  9096. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  9097. SERIAL_ERROR_START();
  9098. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9099. }
  9100. else {
  9101. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  9102. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9103. bed_level_virt_interpolate();
  9104. #endif
  9105. }
  9106. }
  9107. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  9108. /**
  9109. * M421: Set a single Mesh Bed Leveling Z coordinate
  9110. *
  9111. * Usage:
  9112. * M421 I<xindex> J<yindex> Z<linear>
  9113. * M421 I<xindex> J<yindex> Q<offset>
  9114. * M421 I<xindex> J<yindex> N
  9115. * M421 C Z<linear>
  9116. * M421 C Q<offset>
  9117. */
  9118. inline void gcode_M421() {
  9119. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  9120. const bool hasI = ix >= 0,
  9121. hasJ = iy >= 0,
  9122. hasC = parser.seen('C'),
  9123. hasN = parser.seen('N'),
  9124. hasZ = parser.seen('Z'),
  9125. hasQ = !hasZ && parser.seen('Q');
  9126. if (hasC) {
  9127. const mesh_index_pair location = ubl.find_closest_mesh_point_of_type(REAL, current_position[X_AXIS], current_position[Y_AXIS], USE_NOZZLE_AS_REFERENCE, NULL);
  9128. ix = location.x_index;
  9129. iy = location.y_index;
  9130. }
  9131. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ || hasN)) {
  9132. SERIAL_ERROR_START();
  9133. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9134. }
  9135. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  9136. SERIAL_ERROR_START();
  9137. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9138. }
  9139. else
  9140. ubl.z_values[ix][iy] = hasN ? NAN : parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  9141. }
  9142. #endif // AUTO_BED_LEVELING_UBL
  9143. #if HAS_M206_COMMAND
  9144. /**
  9145. * M428: Set home_offset based on the distance between the
  9146. * current_position and the nearest "reference point."
  9147. * If an axis is past center its endstop position
  9148. * is the reference-point. Otherwise it uses 0. This allows
  9149. * the Z offset to be set near the bed when using a max endstop.
  9150. *
  9151. * M428 can't be used more than 2cm away from 0 or an endstop.
  9152. *
  9153. * Use M206 to set these values directly.
  9154. */
  9155. inline void gcode_M428() {
  9156. if (axis_unhomed_error()) return;
  9157. float diff[XYZ];
  9158. LOOP_XYZ(i) {
  9159. diff[i] = base_home_pos((AxisEnum)i) - current_position[i];
  9160. if (!WITHIN(diff[i], -20, 20) && home_dir((AxisEnum)i) > 0)
  9161. diff[i] = -current_position[i];
  9162. if (!WITHIN(diff[i], -20, 20)) {
  9163. SERIAL_ERROR_START();
  9164. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  9165. LCD_ALERTMESSAGEPGM("Err: Too far!");
  9166. BUZZ(200, 40);
  9167. return;
  9168. }
  9169. }
  9170. LOOP_XYZ(i) set_home_offset((AxisEnum)i, diff[i]);
  9171. report_current_position();
  9172. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  9173. BUZZ(100, 659);
  9174. BUZZ(100, 698);
  9175. }
  9176. #endif // HAS_M206_COMMAND
  9177. /**
  9178. * M500: Store settings in EEPROM
  9179. */
  9180. inline void gcode_M500() {
  9181. (void)settings.save();
  9182. }
  9183. /**
  9184. * M501: Read settings from EEPROM
  9185. */
  9186. inline void gcode_M501() {
  9187. (void)settings.load();
  9188. }
  9189. /**
  9190. * M502: Revert to default settings
  9191. */
  9192. inline void gcode_M502() {
  9193. (void)settings.reset();
  9194. }
  9195. #if DISABLED(DISABLE_M503)
  9196. /**
  9197. * M503: print settings currently in memory
  9198. */
  9199. inline void gcode_M503() {
  9200. (void)settings.report(parser.seen('S') && !parser.value_bool());
  9201. }
  9202. #endif
  9203. #if ENABLED(EEPROM_SETTINGS)
  9204. /**
  9205. * M504: Validate EEPROM Contents
  9206. */
  9207. inline void gcode_M504() {
  9208. if (settings.validate()) {
  9209. SERIAL_ECHO_START();
  9210. SERIAL_ECHOLNPGM("EEPROM OK");
  9211. }
  9212. }
  9213. #endif
  9214. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  9215. /**
  9216. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  9217. */
  9218. inline void gcode_M540() {
  9219. if (parser.seen('S')) planner.abort_on_endstop_hit = parser.value_bool();
  9220. }
  9221. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  9222. #if HAS_BED_PROBE
  9223. inline void gcode_M851() {
  9224. if (parser.seenval('Z')) {
  9225. const float value = parser.value_linear_units();
  9226. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX))
  9227. zprobe_zoffset = value;
  9228. else {
  9229. SERIAL_ERROR_START();
  9230. SERIAL_ERRORLNPGM("?Z out of range (" STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " to " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX) ")");
  9231. }
  9232. return;
  9233. }
  9234. SERIAL_ECHO_START();
  9235. SERIAL_ECHOPGM(MSG_PROBE_Z_OFFSET);
  9236. SERIAL_ECHOLNPAIR(": ", zprobe_zoffset);
  9237. }
  9238. #endif // HAS_BED_PROBE
  9239. #if ENABLED(SKEW_CORRECTION_GCODE)
  9240. /**
  9241. * M852: Get or set the machine skew factors. Reports current values with no arguments.
  9242. *
  9243. * S[xy_factor] - Alias for 'I'
  9244. * I[xy_factor] - New XY skew factor
  9245. * J[xz_factor] - New XZ skew factor
  9246. * K[yz_factor] - New YZ skew factor
  9247. */
  9248. inline void gcode_M852() {
  9249. uint8_t ijk = 0, badval = 0, setval = 0;
  9250. if (parser.seen('I') || parser.seen('S')) {
  9251. ++ijk;
  9252. const float value = parser.value_linear_units();
  9253. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9254. if (planner.xy_skew_factor != value) {
  9255. planner.xy_skew_factor = value;
  9256. ++setval;
  9257. }
  9258. }
  9259. else
  9260. ++badval;
  9261. }
  9262. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  9263. if (parser.seen('J')) {
  9264. ++ijk;
  9265. const float value = parser.value_linear_units();
  9266. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9267. if (planner.xz_skew_factor != value) {
  9268. planner.xz_skew_factor = value;
  9269. ++setval;
  9270. }
  9271. }
  9272. else
  9273. ++badval;
  9274. }
  9275. if (parser.seen('K')) {
  9276. ++ijk;
  9277. const float value = parser.value_linear_units();
  9278. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9279. if (planner.yz_skew_factor != value) {
  9280. planner.yz_skew_factor = value;
  9281. ++setval;
  9282. }
  9283. }
  9284. else
  9285. ++badval;
  9286. }
  9287. #endif
  9288. if (badval)
  9289. SERIAL_ECHOLNPGM(MSG_SKEW_MIN " " STRINGIFY(SKEW_FACTOR_MIN) " " MSG_SKEW_MAX " " STRINGIFY(SKEW_FACTOR_MAX));
  9290. // When skew is changed the current position changes
  9291. if (setval) {
  9292. set_current_from_steppers_for_axis(ALL_AXES);
  9293. SYNC_PLAN_POSITION_KINEMATIC();
  9294. report_current_position();
  9295. }
  9296. if (!ijk) {
  9297. SERIAL_ECHO_START();
  9298. SERIAL_ECHOPGM(MSG_SKEW_FACTOR " XY: ");
  9299. SERIAL_ECHO_F(planner.xy_skew_factor, 6);
  9300. SERIAL_EOL();
  9301. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  9302. SERIAL_ECHOPAIR(" XZ: ", planner.xz_skew_factor);
  9303. SERIAL_ECHOLNPAIR(" YZ: ", planner.yz_skew_factor);
  9304. #else
  9305. SERIAL_EOL();
  9306. #endif
  9307. }
  9308. }
  9309. #endif // SKEW_CORRECTION_GCODE
  9310. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  9311. /**
  9312. * M600: Pause for filament change
  9313. *
  9314. * E[distance] - Retract the filament this far
  9315. * Z[distance] - Move the Z axis by this distance
  9316. * X[position] - Move to this X position, with Y
  9317. * Y[position] - Move to this Y position, with X
  9318. * U[distance] - Retract distance for removal (manual reload)
  9319. * L[distance] - Extrude distance for insertion (manual reload)
  9320. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  9321. * T[toolhead] - Select extruder for filament change
  9322. *
  9323. * Default values are used for omitted arguments.
  9324. */
  9325. inline void gcode_M600() {
  9326. point_t park_point = NOZZLE_PARK_POINT;
  9327. if (get_target_extruder_from_command(600)) return;
  9328. // Show initial message
  9329. #if ENABLED(ULTIPANEL)
  9330. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT, ADVANCED_PAUSE_MODE_PAUSE_PRINT, target_extruder);
  9331. #endif
  9332. #if ENABLED(HOME_BEFORE_FILAMENT_CHANGE)
  9333. // Don't allow filament change without homing first
  9334. if (axis_unhomed_error()) home_all_axes();
  9335. #endif
  9336. #if EXTRUDERS > 1
  9337. // Change toolhead if specified
  9338. uint8_t active_extruder_before_filament_change = active_extruder;
  9339. if (active_extruder != target_extruder)
  9340. tool_change(target_extruder, 0, true);
  9341. #endif
  9342. // Initial retract before move to filament change position
  9343. const float retract = -ABS(parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  9344. #ifdef PAUSE_PARK_RETRACT_LENGTH
  9345. + (PAUSE_PARK_RETRACT_LENGTH)
  9346. #endif
  9347. );
  9348. // Lift Z axis
  9349. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9350. // Move XY axes to filament change position or given position
  9351. if (parser.seenval('X')) park_point.x = parser.linearval('X');
  9352. if (parser.seenval('Y')) park_point.y = parser.linearval('Y');
  9353. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE) && DISABLED(DELTA)
  9354. park_point.x += (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0);
  9355. park_point.y += (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0);
  9356. #endif
  9357. // Unload filament
  9358. const float unload_length = -ABS(parser.seen('U') ? parser.value_axis_units(E_AXIS) :
  9359. filament_change_unload_length[active_extruder]);
  9360. // Slow load filament
  9361. constexpr float slow_load_length = FILAMENT_CHANGE_SLOW_LOAD_LENGTH;
  9362. // Fast load filament
  9363. const float fast_load_length = ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) :
  9364. filament_change_load_length[active_extruder]);
  9365. const int beep_count = parser.intval('B',
  9366. #ifdef FILAMENT_CHANGE_ALERT_BEEPS
  9367. FILAMENT_CHANGE_ALERT_BEEPS
  9368. #else
  9369. -1
  9370. #endif
  9371. );
  9372. const bool job_running = print_job_timer.isRunning();
  9373. if (pause_print(retract, park_point, unload_length, true)) {
  9374. wait_for_filament_reload(beep_count);
  9375. resume_print(slow_load_length, fast_load_length, ADVANCED_PAUSE_PURGE_LENGTH, beep_count);
  9376. }
  9377. #if EXTRUDERS > 1
  9378. // Restore toolhead if it was changed
  9379. if (active_extruder_before_filament_change != active_extruder)
  9380. tool_change(active_extruder_before_filament_change, 0, true);
  9381. #endif
  9382. // Resume the print job timer if it was running
  9383. if (job_running) print_job_timer.start();
  9384. }
  9385. /**
  9386. * M603: Configure filament change
  9387. *
  9388. * T[toolhead] - Select extruder to configure, active extruder if not specified
  9389. * U[distance] - Retract distance for removal, for the specified extruder
  9390. * L[distance] - Extrude distance for insertion, for the specified extruder
  9391. *
  9392. */
  9393. inline void gcode_M603() {
  9394. if (get_target_extruder_from_command(603)) return;
  9395. // Unload length
  9396. if (parser.seen('U')) {
  9397. filament_change_unload_length[target_extruder] = ABS(parser.value_axis_units(E_AXIS));
  9398. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9399. NOMORE(filament_change_unload_length[target_extruder], EXTRUDE_MAXLENGTH);
  9400. #endif
  9401. }
  9402. // Load length
  9403. if (parser.seen('L')) {
  9404. filament_change_load_length[target_extruder] = ABS(parser.value_axis_units(E_AXIS));
  9405. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9406. NOMORE(filament_change_load_length[target_extruder], EXTRUDE_MAXLENGTH);
  9407. #endif
  9408. }
  9409. }
  9410. #endif // ADVANCED_PAUSE_FEATURE
  9411. #if ENABLED(MK2_MULTIPLEXER)
  9412. inline void select_multiplexed_stepper(const uint8_t e) {
  9413. planner.synchronize();
  9414. disable_e_steppers();
  9415. WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  9416. WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  9417. WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW);
  9418. safe_delay(100);
  9419. }
  9420. #endif // MK2_MULTIPLEXER
  9421. #if ENABLED(DUAL_X_CARRIAGE)
  9422. /**
  9423. * M605: Set dual x-carriage movement mode
  9424. *
  9425. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  9426. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  9427. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  9428. * units x-offset and an optional differential hotend temperature of
  9429. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  9430. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  9431. *
  9432. * Note: the X axis should be homed after changing dual x-carriage mode.
  9433. */
  9434. inline void gcode_M605() {
  9435. planner.synchronize();
  9436. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  9437. switch (dual_x_carriage_mode) {
  9438. case DXC_FULL_CONTROL_MODE:
  9439. case DXC_AUTO_PARK_MODE:
  9440. break;
  9441. case DXC_DUPLICATION_MODE:
  9442. if (parser.seen('X')) duplicate_extruder_x_offset = MAX(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  9443. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  9444. SERIAL_ECHO_START();
  9445. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  9446. SERIAL_CHAR(' ');
  9447. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  9448. SERIAL_CHAR(',');
  9449. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  9450. SERIAL_CHAR(' ');
  9451. SERIAL_ECHO(duplicate_extruder_x_offset);
  9452. SERIAL_CHAR(',');
  9453. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  9454. break;
  9455. default:
  9456. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  9457. break;
  9458. }
  9459. active_extruder_parked = false;
  9460. extruder_duplication_enabled = false;
  9461. delayed_move_time = 0;
  9462. }
  9463. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  9464. inline void gcode_M605() {
  9465. planner.synchronize();
  9466. extruder_duplication_enabled = parser.intval('S') == int(DXC_DUPLICATION_MODE);
  9467. SERIAL_ECHO_START();
  9468. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  9469. }
  9470. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  9471. #if ENABLED(FILAMENT_LOAD_UNLOAD_GCODES)
  9472. /**
  9473. * M701: Load filament
  9474. *
  9475. * T<extruder> - Optional extruder number. Current extruder if omitted.
  9476. * Z<distance> - Move the Z axis by this distance
  9477. * L<distance> - Extrude distance for insertion (positive value) (manual reload)
  9478. *
  9479. * Default values are used for omitted arguments.
  9480. */
  9481. inline void gcode_M701() {
  9482. point_t park_point = NOZZLE_PARK_POINT;
  9483. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  9484. // Only raise Z if the machine is homed
  9485. if (axis_unhomed_error()) park_point.z = 0;
  9486. #endif
  9487. if (get_target_extruder_from_command(701)) return;
  9488. // Z axis lift
  9489. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9490. // Show initial "wait for load" message
  9491. #if ENABLED(ULTIPANEL)
  9492. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD, ADVANCED_PAUSE_MODE_LOAD_FILAMENT, target_extruder);
  9493. #endif
  9494. #if EXTRUDERS > 1
  9495. // Change toolhead if specified
  9496. uint8_t active_extruder_before_filament_change = active_extruder;
  9497. if (active_extruder != target_extruder)
  9498. tool_change(target_extruder, 0, true);
  9499. #endif
  9500. // Lift Z axis
  9501. if (park_point.z > 0)
  9502. do_blocking_move_to_z(MIN(current_position[Z_AXIS] + park_point.z, Z_MAX_POS), NOZZLE_PARK_Z_FEEDRATE);
  9503. constexpr float slow_load_length = FILAMENT_CHANGE_SLOW_LOAD_LENGTH;
  9504. const float fast_load_length = ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : filament_change_load_length[active_extruder]);
  9505. load_filament(slow_load_length, fast_load_length, ADVANCED_PAUSE_PURGE_LENGTH, FILAMENT_CHANGE_ALERT_BEEPS,
  9506. true, thermalManager.wait_for_heating(target_extruder), ADVANCED_PAUSE_MODE_LOAD_FILAMENT);
  9507. // Restore Z axis
  9508. if (park_point.z > 0)
  9509. do_blocking_move_to_z(MAX(current_position[Z_AXIS] - park_point.z, 0), NOZZLE_PARK_Z_FEEDRATE);
  9510. #if EXTRUDERS > 1
  9511. // Restore toolhead if it was changed
  9512. if (active_extruder_before_filament_change != active_extruder)
  9513. tool_change(active_extruder_before_filament_change, 0, true);
  9514. #endif
  9515. // Show status screen
  9516. #if ENABLED(ULTIPANEL)
  9517. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  9518. #endif
  9519. }
  9520. /**
  9521. * M702: Unload filament
  9522. *
  9523. * T<extruder> - Optional extruder number. If omitted, current extruder
  9524. * (or ALL extruders with FILAMENT_UNLOAD_ALL_EXTRUDERS).
  9525. * Z<distance> - Move the Z axis by this distance
  9526. * U<distance> - Retract distance for removal (manual reload)
  9527. *
  9528. * Default values are used for omitted arguments.
  9529. */
  9530. inline void gcode_M702() {
  9531. point_t park_point = NOZZLE_PARK_POINT;
  9532. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  9533. // Only raise Z if the machine is homed
  9534. if (axis_unhomed_error()) park_point.z = 0;
  9535. #endif
  9536. if (get_target_extruder_from_command(702)) return;
  9537. // Z axis lift
  9538. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9539. // Show initial message
  9540. #if ENABLED(ULTIPANEL)
  9541. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT, target_extruder);
  9542. #endif
  9543. #if EXTRUDERS > 1
  9544. // Change toolhead if specified
  9545. uint8_t active_extruder_before_filament_change = active_extruder;
  9546. if (active_extruder != target_extruder)
  9547. tool_change(target_extruder, 0, true);
  9548. #endif
  9549. // Lift Z axis
  9550. if (park_point.z > 0)
  9551. do_blocking_move_to_z(MIN(current_position[Z_AXIS] + park_point.z, Z_MAX_POS), NOZZLE_PARK_Z_FEEDRATE);
  9552. // Unload filament
  9553. #if EXTRUDERS > 1 && ENABLED(FILAMENT_UNLOAD_ALL_EXTRUDERS)
  9554. if (!parser.seenval('T')) {
  9555. HOTEND_LOOP() {
  9556. if (e != active_extruder) tool_change(e, 0, true);
  9557. unload_filament(-filament_change_unload_length[e], true, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT);
  9558. }
  9559. }
  9560. else
  9561. #endif
  9562. {
  9563. // Unload length
  9564. const float unload_length = -ABS(parser.seen('U') ? parser.value_axis_units(E_AXIS) :
  9565. filament_change_unload_length[target_extruder]);
  9566. unload_filament(unload_length, true, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT);
  9567. }
  9568. // Restore Z axis
  9569. if (park_point.z > 0)
  9570. do_blocking_move_to_z(MAX(current_position[Z_AXIS] - park_point.z, 0), NOZZLE_PARK_Z_FEEDRATE);
  9571. #if EXTRUDERS > 1
  9572. // Restore toolhead if it was changed
  9573. if (active_extruder_before_filament_change != active_extruder)
  9574. tool_change(active_extruder_before_filament_change, 0, true);
  9575. #endif
  9576. // Show status screen
  9577. #if ENABLED(ULTIPANEL)
  9578. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  9579. #endif
  9580. }
  9581. #endif // FILAMENT_LOAD_UNLOAD_GCODES
  9582. #if ENABLED(MAX7219_GCODE)
  9583. /**
  9584. * M7219: Control the Max7219 LED matrix
  9585. *
  9586. * I - Initialize (clear) the matrix
  9587. * F - Fill the matrix (set all bits)
  9588. * P - Dump the LEDs[] array values
  9589. * C<column> - Set a column to the 8-bit value V
  9590. * R<row> - Set a row to the 8-bit value V
  9591. * X<pos> - X position of an LED to set or toggle
  9592. * Y<pos> - Y position of an LED to set or toggle
  9593. * V<value> - The potentially 32-bit value or on/off state to set
  9594. * (for example: a chain of 4 Max7219 devices can have 32 bit
  9595. * rows or columns depending upon rotation)
  9596. */
  9597. inline void gcode_M7219() {
  9598. if (parser.seen('I')) {
  9599. max7219.register_setup();
  9600. max7219.clear();
  9601. }
  9602. if (parser.seen('F')) max7219.fill();
  9603. const uint32_t v = parser.ulongval('V');
  9604. if (parser.seenval('R')) {
  9605. const uint8_t r = parser.value_byte();
  9606. max7219.set_row(r, v);
  9607. }
  9608. else if (parser.seenval('C')) {
  9609. const uint8_t c = parser.value_byte();
  9610. max7219.set_column(c, v);
  9611. }
  9612. else if (parser.seenval('X') || parser.seenval('Y')) {
  9613. const uint8_t x = parser.byteval('X'), y = parser.byteval('Y');
  9614. if (parser.seenval('V'))
  9615. max7219.led_set(x, y, parser.boolval('V'));
  9616. else
  9617. max7219.led_toggle(x, y);
  9618. }
  9619. else if (parser.seen('D')) {
  9620. const uint8_t line = parser.byteval('D') + (parser.byteval('U') << 3);
  9621. if (line < MAX7219_LINES) {
  9622. max7219.led_line[line] = v;
  9623. return max7219.refresh_line(line);
  9624. }
  9625. }
  9626. if (parser.seen('P')) {
  9627. for (uint8_t r = 0; r < MAX7219_LINES; r++) {
  9628. SERIAL_ECHOPGM("led_line[");
  9629. if (r < 10) SERIAL_CHAR(' ');
  9630. SERIAL_ECHO(int(r));
  9631. SERIAL_ECHOPGM("]=");
  9632. for (uint8_t b = 8; b--;) SERIAL_CHAR('0' + TEST(max7219.led_line[r], b));
  9633. SERIAL_EOL();
  9634. }
  9635. }
  9636. }
  9637. #endif // MAX7219_GCODE
  9638. #if ENABLED(LIN_ADVANCE)
  9639. /**
  9640. * M900: Get or Set Linear Advance K-factor
  9641. *
  9642. * K<factor> Set advance K factor
  9643. */
  9644. inline void gcode_M900() {
  9645. if (parser.seenval('K')) {
  9646. const float newK = parser.floatval('K');
  9647. if (WITHIN(newK, 0, 10)) {
  9648. planner.synchronize();
  9649. planner.extruder_advance_K = newK;
  9650. }
  9651. else
  9652. SERIAL_PROTOCOLLNPGM("?K value out of range (0-10).");
  9653. }
  9654. else {
  9655. SERIAL_ECHO_START();
  9656. SERIAL_ECHOLNPAIR("Advance K=", planner.extruder_advance_K);
  9657. }
  9658. }
  9659. #endif // LIN_ADVANCE
  9660. #if HAS_TRINAMIC
  9661. #if ENABLED(TMC_DEBUG)
  9662. inline void gcode_M122() {
  9663. if (parser.seen('S'))
  9664. tmc_set_report_status(parser.value_bool());
  9665. else
  9666. tmc_report_all();
  9667. }
  9668. #endif // TMC_DEBUG
  9669. /**
  9670. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  9671. * Uses axis codes A, B, C, D, E for Hangprinter
  9672. * Report driver currents when no axis specified
  9673. */
  9674. inline void gcode_M906() {
  9675. #define TMC_SAY_CURRENT(Q) tmc_get_current(stepper##Q, TMC_##Q)
  9676. #define TMC_SET_CURRENT(Q) tmc_set_current(stepper##Q, value)
  9677. bool report = true;
  9678. const uint8_t index = parser.byteval('I');
  9679. LOOP_NUM_AXIS(i) if (uint16_t value = parser.intval(RAW_AXIS_CODES(i))) {
  9680. report = false;
  9681. switch (i) {
  9682. // Assumes {A_AXIS, B_AXIS, C_AXIS} == {X_AXIS, Y_AXIS, Z_AXIS}
  9683. case X_AXIS:
  9684. #if AXIS_IS_TMC(X)
  9685. if (index < 2) TMC_SET_CURRENT(X);
  9686. #endif
  9687. #if AXIS_IS_TMC(X2)
  9688. if (!(index & 1)) TMC_SET_CURRENT(X2);
  9689. #endif
  9690. break;
  9691. case Y_AXIS:
  9692. #if AXIS_IS_TMC(Y)
  9693. if (index < 2) TMC_SET_CURRENT(Y);
  9694. #endif
  9695. #if AXIS_IS_TMC(Y2)
  9696. if (!(index & 1)) TMC_SET_CURRENT(Y2);
  9697. #endif
  9698. break;
  9699. case Z_AXIS:
  9700. #if AXIS_IS_TMC(Z)
  9701. if (index < 2) TMC_SET_CURRENT(Z);
  9702. #endif
  9703. #if AXIS_IS_TMC(Z2)
  9704. if (!(index & 1)) TMC_SET_CURRENT(Z2);
  9705. #endif
  9706. break;
  9707. case E_AXIS: {
  9708. if (get_target_extruder_from_command(906)) return;
  9709. switch (target_extruder) {
  9710. #if AXIS_IS_TMC(E0)
  9711. case 0: TMC_SET_CURRENT(E0); break;
  9712. #endif
  9713. #if ENABLED(HANGPRINTER)
  9714. // Avoid setting the D-current
  9715. #if AXIS_IS_TMC(E1) && EXTRUDERS > 1
  9716. case 1: TMC_SET_CURRENT(E1); break;
  9717. #endif
  9718. #if AXIS_IS_TMC(E2) && EXTRUDERS > 2
  9719. case 2: TMC_SET_CURRENT(E2); break;
  9720. #endif
  9721. #if AXIS_IS_TMC(E3) && EXTRUDERS > 3
  9722. case 3: TMC_SET_CURRENT(E3); break;
  9723. #endif
  9724. #if AXIS_IS_TMC(E4) && EXTRUDERS > 4
  9725. case 4: TMC_SET_CURRENT(E4); break;
  9726. #endif
  9727. #else
  9728. #if AXIS_IS_TMC(E1)
  9729. case 1: TMC_SET_CURRENT(E1); break;
  9730. #endif
  9731. #if AXIS_IS_TMC(E2)
  9732. case 2: TMC_SET_CURRENT(E2); break;
  9733. #endif
  9734. #if AXIS_IS_TMC(E3)
  9735. case 3: TMC_SET_CURRENT(E3); break;
  9736. #endif
  9737. #if AXIS_IS_TMC(E4)
  9738. case 4: TMC_SET_CURRENT(E4); break;
  9739. #endif
  9740. #endif
  9741. }
  9742. } break;
  9743. #if ENABLED(HANGPRINTER)
  9744. case D_AXIS:
  9745. // D is connected on the first of E1, E2, E3, E4 output that is not an extruder
  9746. #if AXIS_IS_TMC(E1) && EXTRUDERS == 1
  9747. TMC_SET_CURRENT(E1); break;
  9748. #endif
  9749. #if AXIS_IS_TMC(E2) && EXTRUDERS == 2
  9750. TMC_SET_CURRENT(E2); break;
  9751. #endif
  9752. #if AXIS_IS_TMC(E3) && EXTRUDERS == 3
  9753. TMC_SET_CURRENT(E3); break;
  9754. #endif
  9755. #if AXIS_IS_TMC(E4) && EXTRUDERS == 4
  9756. TMC_SET_CURRENT(E4); break;
  9757. #endif
  9758. #endif
  9759. }
  9760. }
  9761. if (report) {
  9762. #if AXIS_IS_TMC(X)
  9763. TMC_SAY_CURRENT(X);
  9764. #endif
  9765. #if AXIS_IS_TMC(X2)
  9766. TMC_SAY_CURRENT(X2);
  9767. #endif
  9768. #if AXIS_IS_TMC(Y)
  9769. TMC_SAY_CURRENT(Y);
  9770. #endif
  9771. #if AXIS_IS_TMC(Y2)
  9772. TMC_SAY_CURRENT(Y2);
  9773. #endif
  9774. #if AXIS_IS_TMC(Z)
  9775. TMC_SAY_CURRENT(Z);
  9776. #endif
  9777. #if AXIS_IS_TMC(Z2)
  9778. TMC_SAY_CURRENT(Z2);
  9779. #endif
  9780. #if AXIS_IS_TMC(E0)
  9781. TMC_SAY_CURRENT(E0);
  9782. #endif
  9783. #if ENABLED(HANGPRINTER)
  9784. // D is connected on the first of E1, E2, E3, E4 output that is not an extruder
  9785. #if AXIS_IS_TMC(E1) && EXTRUDERS == 1
  9786. TMC_SAY_CURRENT(E1);
  9787. #endif
  9788. #if AXIS_IS_TMC(E2) && EXTRUDERS == 2
  9789. TMC_SAY_CURRENT(E2);
  9790. #endif
  9791. #if AXIS_IS_TMC(E3) && EXTRUDERS == 3
  9792. TMC_SAY_CURRENT(E3);
  9793. #endif
  9794. #if AXIS_IS_TMC(E4) && EXTRUDERS == 4
  9795. TMC_SAY_CURRENT(E4);
  9796. #endif
  9797. #else
  9798. #if AXIS_IS_TMC(E1)
  9799. TMC_SAY_CURRENT(E1);
  9800. #endif
  9801. #if AXIS_IS_TMC(E2)
  9802. TMC_SAY_CURRENT(E2);
  9803. #endif
  9804. #if AXIS_IS_TMC(E3)
  9805. TMC_SAY_CURRENT(E3);
  9806. #endif
  9807. #if AXIS_IS_TMC(E4)
  9808. TMC_SAY_CURRENT(E4);
  9809. #endif
  9810. #endif
  9811. }
  9812. }
  9813. #define M91x_USE(ST) (AXIS_DRIVER_TYPE(ST, TMC2130) || (AXIS_DRIVER_TYPE(ST, TMC2208) && PIN_EXISTS(ST##_SERIAL_RX)))
  9814. #define M91x_USE_E(N) (E_STEPPERS > N && M91x_USE(E##N))
  9815. /**
  9816. * M911: Report TMC stepper driver overtemperature pre-warn flag
  9817. * This flag is held by the library, persisting until cleared by M912
  9818. */
  9819. inline void gcode_M911() {
  9820. #if M91x_USE(X)
  9821. tmc_report_otpw(stepperX, TMC_X);
  9822. #endif
  9823. #if M91x_USE(X2)
  9824. tmc_report_otpw(stepperX2, TMC_X2);
  9825. #endif
  9826. #if M91x_USE(Y)
  9827. tmc_report_otpw(stepperY, TMC_Y);
  9828. #endif
  9829. #if M91x_USE(Y2)
  9830. tmc_report_otpw(stepperY2, TMC_Y2);
  9831. #endif
  9832. #if M91x_USE(Z)
  9833. tmc_report_otpw(stepperZ, TMC_Z);
  9834. #endif
  9835. #if M91x_USE(Z2)
  9836. tmc_report_otpw(stepperZ2, TMC_Z2);
  9837. #endif
  9838. #if M91x_USE_E(0)
  9839. tmc_report_otpw(stepperE0, TMC_E0);
  9840. #endif
  9841. #if M91x_USE_E(1)
  9842. tmc_report_otpw(stepperE1, TMC_E1);
  9843. #endif
  9844. #if M91x_USE_E(2)
  9845. tmc_report_otpw(stepperE2, TMC_E2);
  9846. #endif
  9847. #if M91x_USE_E(3)
  9848. tmc_report_otpw(stepperE3, TMC_E3);
  9849. #endif
  9850. #if M91x_USE_E(4)
  9851. tmc_report_otpw(stepperE4, TMC_E4);
  9852. #endif
  9853. }
  9854. /**
  9855. * M912: Clear TMC stepper driver overtemperature pre-warn flag held by the library
  9856. * Specify one or more axes with X, Y, Z, X1, Y1, Z1, X2, Y2, Z2, and E[index].
  9857. * If no axes are given, clear all.
  9858. *
  9859. * Examples:
  9860. * M912 X ; clear X and X2
  9861. * M912 X1 ; clear X1 only
  9862. * M912 X2 ; clear X2 only
  9863. * M912 X E ; clear X, X2, and all E
  9864. * M912 E1 ; clear E1 only
  9865. */
  9866. inline void gcode_M912() {
  9867. const bool hasX = parser.seen(axis_codes[X_AXIS]),
  9868. hasY = parser.seen(axis_codes[Y_AXIS]),
  9869. hasZ = parser.seen(axis_codes[Z_AXIS]),
  9870. hasE = parser.seen(axis_codes[E_CART]),
  9871. hasNone = !hasX && !hasY && !hasZ && !hasE;
  9872. #if M91x_USE(X) || M91x_USE(X2)
  9873. const uint8_t xval = parser.byteval(axis_codes[X_AXIS], 10);
  9874. #if M91x_USE(X)
  9875. if (hasNone || xval == 1 || (hasX && xval == 10)) tmc_clear_otpw(stepperX, TMC_X);
  9876. #endif
  9877. #if M91x_USE(X2)
  9878. if (hasNone || xval == 2 || (hasX && xval == 10)) tmc_clear_otpw(stepperX2, TMC_X2);
  9879. #endif
  9880. #endif
  9881. #if M91x_USE(Y) || M91x_USE(Y2)
  9882. const uint8_t yval = parser.byteval(axis_codes[Y_AXIS], 10);
  9883. #if M91x_USE(Y)
  9884. if (hasNone || yval == 1 || (hasY && yval == 10)) tmc_clear_otpw(stepperY, TMC_Y);
  9885. #endif
  9886. #if M91x_USE(Y2)
  9887. if (hasNone || yval == 2 || (hasY && yval == 10)) tmc_clear_otpw(stepperY2, TMC_Y2);
  9888. #endif
  9889. #endif
  9890. #if M91x_USE(Z) || M91x_USE(Z2)
  9891. const uint8_t zval = parser.byteval(axis_codes[Z_AXIS], 10);
  9892. #if M91x_USE(Z)
  9893. if (hasNone || zval == 1 || (hasZ && zval == 10)) tmc_clear_otpw(stepperZ, TMC_Z);
  9894. #endif
  9895. #if M91x_USE(Z2)
  9896. if (hasNone || zval == 2 || (hasZ && zval == 10)) tmc_clear_otpw(stepperZ2, TMC_Z2);
  9897. #endif
  9898. #endif
  9899. // TODO: If this is a Hangprinter, E_AXIS will not correspond to E0, E1, etc in this way
  9900. #if M91x_USE_E(0) || M91x_USE_E(1) || M91x_USE_E(2) || M91x_USE_E(3) || M91x_USE_E(4)
  9901. const uint8_t eval = parser.byteval(axis_codes[E_AXIS], 10);
  9902. #if M91x_USE_E(0)
  9903. if (hasNone || eval == 0 || (hasE && eval == 10)) tmc_clear_otpw(stepperE0, TMC_E0);
  9904. #endif
  9905. #if M91x_USE_E(1)
  9906. if (hasNone || eval == 1 || (hasE && eval == 10)) tmc_clear_otpw(stepperE1, TMC_E1);
  9907. #endif
  9908. #if M91x_USE_E(2)
  9909. if (hasNone || eval == 2 || (hasE && eval == 10)) tmc_clear_otpw(stepperE2, TMC_E2);
  9910. #endif
  9911. #if M91x_USE_E(3)
  9912. if (hasNone || eval == 3 || (hasE && eval == 10)) tmc_clear_otpw(stepperE3, TMC_E3);
  9913. #endif
  9914. #if M91x_USE_E(4)
  9915. if (hasNone || eval == 4 || (hasE && eval == 10)) tmc_clear_otpw(stepperE4, TMC_E4);
  9916. #endif
  9917. #endif
  9918. }
  9919. /**
  9920. * M913: Set HYBRID_THRESHOLD speed.
  9921. */
  9922. #if ENABLED(HYBRID_THRESHOLD)
  9923. inline void gcode_M913() {
  9924. #define TMC_SAY_PWMTHRS(A,Q) tmc_get_pwmthrs(stepper##Q, TMC_##Q, planner.axis_steps_per_mm[_AXIS(A)])
  9925. #define TMC_SET_PWMTHRS(A,Q) tmc_set_pwmthrs(stepper##Q, value, planner.axis_steps_per_mm[_AXIS(A)])
  9926. #define TMC_SAY_PWMTHRS_E(E) do{ const uint8_t extruder = E; tmc_get_pwmthrs(stepperE##E, TMC_E##E, planner.axis_steps_per_mm[E_AXIS_N]); }while(0)
  9927. #define TMC_SET_PWMTHRS_E(E) do{ const uint8_t extruder = E; tmc_set_pwmthrs(stepperE##E, value, planner.axis_steps_per_mm[E_AXIS_N]); }while(0)
  9928. bool report = true;
  9929. const uint8_t index = parser.byteval('I');
  9930. LOOP_XYZE(i) if (int32_t value = parser.longval(axis_codes[i])) {
  9931. report = false;
  9932. switch (i) {
  9933. case X_AXIS:
  9934. #if AXIS_HAS_STEALTHCHOP(X)
  9935. if (index < 2) TMC_SET_PWMTHRS(X,X);
  9936. #endif
  9937. #if AXIS_HAS_STEALTHCHOP(X2)
  9938. if (!(index & 1)) TMC_SET_PWMTHRS(X,X2);
  9939. #endif
  9940. break;
  9941. case Y_AXIS:
  9942. #if AXIS_HAS_STEALTHCHOP(Y)
  9943. if (index < 2) TMC_SET_PWMTHRS(Y,Y);
  9944. #endif
  9945. #if AXIS_HAS_STEALTHCHOP(Y2)
  9946. if (!(index & 1)) TMC_SET_PWMTHRS(Y,Y2);
  9947. #endif
  9948. break;
  9949. case Z_AXIS:
  9950. #if AXIS_HAS_STEALTHCHOP(Z)
  9951. if (index < 2) TMC_SET_PWMTHRS(Z,Z);
  9952. #endif
  9953. #if AXIS_HAS_STEALTHCHOP(Z2)
  9954. if (!(index & 1)) TMC_SET_PWMTHRS(Z,Z2);
  9955. #endif
  9956. break;
  9957. case E_CART: {
  9958. if (get_target_extruder_from_command(913)) return;
  9959. switch (target_extruder) {
  9960. #if AXIS_HAS_STEALTHCHOP(E0)
  9961. case 0: TMC_SET_PWMTHRS_E(0); break;
  9962. #endif
  9963. #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1)
  9964. case 1: TMC_SET_PWMTHRS_E(1); break;
  9965. #endif
  9966. #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2)
  9967. case 2: TMC_SET_PWMTHRS_E(2); break;
  9968. #endif
  9969. #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3)
  9970. case 3: TMC_SET_PWMTHRS_E(3); break;
  9971. #endif
  9972. #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4)
  9973. case 4: TMC_SET_PWMTHRS_E(4); break;
  9974. #endif
  9975. }
  9976. } break;
  9977. }
  9978. }
  9979. if (report) {
  9980. #if AXIS_HAS_STEALTHCHOP(X)
  9981. TMC_SAY_PWMTHRS(X,X);
  9982. #endif
  9983. #if AXIS_HAS_STEALTHCHOP(X2)
  9984. TMC_SAY_PWMTHRS(X,X2);
  9985. #endif
  9986. #if AXIS_HAS_STEALTHCHOP(Y)
  9987. TMC_SAY_PWMTHRS(Y,Y);
  9988. #endif
  9989. #if AXIS_HAS_STEALTHCHOP(Y2)
  9990. TMC_SAY_PWMTHRS(Y,Y2);
  9991. #endif
  9992. #if AXIS_HAS_STEALTHCHOP(Z)
  9993. TMC_SAY_PWMTHRS(Z,Z);
  9994. #endif
  9995. #if AXIS_HAS_STEALTHCHOP(Z2)
  9996. TMC_SAY_PWMTHRS(Z,Z2);
  9997. #endif
  9998. #if AXIS_HAS_STEALTHCHOP(E0)
  9999. TMC_SAY_PWMTHRS_E(0);
  10000. #endif
  10001. #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1)
  10002. TMC_SAY_PWMTHRS_E(1);
  10003. #endif
  10004. #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2)
  10005. TMC_SAY_PWMTHRS_E(2);
  10006. #endif
  10007. #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3)
  10008. TMC_SAY_PWMTHRS_E(3);
  10009. #endif
  10010. #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4)
  10011. TMC_SAY_PWMTHRS_E(4);
  10012. #endif
  10013. }
  10014. }
  10015. #endif // HYBRID_THRESHOLD
  10016. /**
  10017. * M914: Set SENSORLESS_HOMING sensitivity.
  10018. */
  10019. #if ENABLED(SENSORLESS_HOMING)
  10020. inline void gcode_M914() {
  10021. #define TMC_SAY_SGT(Q) tmc_get_sgt(stepper##Q, TMC_##Q)
  10022. #define TMC_SET_SGT(Q) tmc_set_sgt(stepper##Q, value)
  10023. bool report = true;
  10024. const uint8_t index = parser.byteval('I');
  10025. LOOP_XYZ(i) if (parser.seen(axis_codes[i])) {
  10026. const int8_t value = (int8_t)constrain(parser.value_int(), -64, 63);
  10027. report = false;
  10028. switch (i) {
  10029. #if X_SENSORLESS
  10030. case X_AXIS:
  10031. #if AXIS_HAS_STALLGUARD(X)
  10032. if (index < 2) TMC_SET_SGT(X);
  10033. #endif
  10034. #if AXIS_HAS_STALLGUARD(X2)
  10035. if (!(index & 1)) TMC_SET_SGT(X2);
  10036. #endif
  10037. break;
  10038. #endif
  10039. #if Y_SENSORLESS
  10040. case Y_AXIS:
  10041. #if AXIS_HAS_STALLGUARD(Y)
  10042. if (index < 2) TMC_SET_SGT(Y);
  10043. #endif
  10044. #if AXIS_HAS_STALLGUARD(Y2)
  10045. if (!(index & 1)) TMC_SET_SGT(Y2);
  10046. #endif
  10047. break;
  10048. #endif
  10049. #if Z_SENSORLESS
  10050. case Z_AXIS:
  10051. #if AXIS_HAS_STALLGUARD(Z)
  10052. if (index < 2) TMC_SET_SGT(Z);
  10053. #endif
  10054. #if AXIS_HAS_STALLGUARD(Z2)
  10055. if (!(index & 1)) TMC_SET_SGT(Z2);
  10056. #endif
  10057. break;
  10058. #endif
  10059. }
  10060. }
  10061. if (report) {
  10062. #if X_SENSORLESS
  10063. #if AXIS_HAS_STALLGUARD(X)
  10064. TMC_SAY_SGT(X);
  10065. #endif
  10066. #if AXIS_HAS_STALLGUARD(X2)
  10067. TMC_SAY_SGT(X2);
  10068. #endif
  10069. #endif
  10070. #if Y_SENSORLESS
  10071. #if AXIS_HAS_STALLGUARD(Y)
  10072. TMC_SAY_SGT(Y);
  10073. #endif
  10074. #if AXIS_HAS_STALLGUARD(Y2)
  10075. TMC_SAY_SGT(Y2);
  10076. #endif
  10077. #endif
  10078. #if Z_SENSORLESS
  10079. #if AXIS_HAS_STALLGUARD(Z)
  10080. TMC_SAY_SGT(Z);
  10081. #endif
  10082. #if AXIS_HAS_STALLGUARD(Z2)
  10083. TMC_SAY_SGT(Z2);
  10084. #endif
  10085. #endif
  10086. }
  10087. }
  10088. #endif // SENSORLESS_HOMING
  10089. /**
  10090. * TMC Z axis calibration routine
  10091. */
  10092. #if ENABLED(TMC_Z_CALIBRATION)
  10093. inline void gcode_M915() {
  10094. const uint16_t _rms = parser.seenval('S') ? parser.value_int() : CALIBRATION_CURRENT,
  10095. _z = parser.seenval('Z') ? parser.value_linear_units() : CALIBRATION_EXTRA_HEIGHT;
  10096. if (!TEST(axis_known_position, Z_AXIS)) {
  10097. SERIAL_ECHOLNPGM("\nPlease home Z axis first");
  10098. return;
  10099. }
  10100. #if AXIS_IS_TMC(Z)
  10101. const uint16_t Z_current_1 = stepperZ.getCurrent();
  10102. stepperZ.setCurrent(_rms, R_SENSE, HOLD_MULTIPLIER);
  10103. #endif
  10104. #if AXIS_IS_TMC(Z2)
  10105. const uint16_t Z2_current_1 = stepperZ2.getCurrent();
  10106. stepperZ2.setCurrent(_rms, R_SENSE, HOLD_MULTIPLIER);
  10107. #endif
  10108. SERIAL_ECHOPAIR("\nCalibration current: Z", _rms);
  10109. soft_endstops_enabled = false;
  10110. do_blocking_move_to_z(Z_MAX_POS+_z);
  10111. #if AXIS_IS_TMC(Z)
  10112. stepperZ.setCurrent(Z_current_1, R_SENSE, HOLD_MULTIPLIER);
  10113. #endif
  10114. #if AXIS_IS_TMC(Z2)
  10115. stepperZ2.setCurrent(Z2_current_1, R_SENSE, HOLD_MULTIPLIER);
  10116. #endif
  10117. do_blocking_move_to_z(Z_MAX_POS);
  10118. soft_endstops_enabled = true;
  10119. SERIAL_ECHOLNPGM("\nHoming Z due to lost steps");
  10120. enqueue_and_echo_commands_P(PSTR("G28 Z"));
  10121. }
  10122. #endif
  10123. #endif // HAS_TRINAMIC
  10124. /**
  10125. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  10126. */
  10127. inline void gcode_M907() {
  10128. #if HAS_DIGIPOTSS
  10129. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  10130. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  10131. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  10132. #elif HAS_MOTOR_CURRENT_PWM
  10133. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  10134. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  10135. #endif
  10136. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  10137. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  10138. #endif
  10139. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  10140. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  10141. #endif
  10142. #endif
  10143. #if ENABLED(DIGIPOT_I2C)
  10144. // this one uses actual amps in floating point
  10145. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  10146. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  10147. for (uint8_t i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (parser.seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, parser.value_float());
  10148. #endif
  10149. #if ENABLED(DAC_STEPPER_CURRENT)
  10150. if (parser.seen('S')) {
  10151. const float dac_percent = parser.value_float();
  10152. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  10153. }
  10154. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  10155. #endif
  10156. }
  10157. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  10158. /**
  10159. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  10160. */
  10161. inline void gcode_M908() {
  10162. #if HAS_DIGIPOTSS
  10163. stepper.digitalPotWrite(
  10164. parser.intval('P'),
  10165. parser.intval('S')
  10166. );
  10167. #endif
  10168. #ifdef DAC_STEPPER_CURRENT
  10169. dac_current_raw(
  10170. parser.byteval('P', -1),
  10171. parser.ushortval('S', 0)
  10172. );
  10173. #endif
  10174. }
  10175. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  10176. inline void gcode_M909() { dac_print_values(); }
  10177. inline void gcode_M910() { dac_commit_eeprom(); }
  10178. #endif
  10179. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  10180. #if HAS_MICROSTEPS
  10181. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  10182. inline void gcode_M350() {
  10183. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  10184. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  10185. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  10186. stepper.microstep_readings();
  10187. }
  10188. /**
  10189. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  10190. * S# determines MS1 or MS2, X# sets the pin high/low.
  10191. */
  10192. inline void gcode_M351() {
  10193. if (parser.seenval('S')) switch (parser.value_byte()) {
  10194. case 1:
  10195. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  10196. if (parser.seenval('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  10197. break;
  10198. case 2:
  10199. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  10200. if (parser.seenval('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  10201. break;
  10202. }
  10203. stepper.microstep_readings();
  10204. }
  10205. #endif // HAS_MICROSTEPS
  10206. #if HAS_CASE_LIGHT
  10207. #ifndef INVERT_CASE_LIGHT
  10208. #define INVERT_CASE_LIGHT false
  10209. #endif
  10210. uint8_t case_light_brightness; // LCD routine wants INT
  10211. bool case_light_on;
  10212. #if ENABLED(CASE_LIGHT_USE_NEOPIXEL)
  10213. LEDColor case_light_color =
  10214. #ifdef CASE_LIGHT_NEOPIXEL_COLOR
  10215. CASE_LIGHT_NEOPIXEL_COLOR
  10216. #else
  10217. { 255, 255, 255, 255 }
  10218. #endif
  10219. ;
  10220. #endif
  10221. void update_case_light() {
  10222. const uint8_t i = case_light_on ? case_light_brightness : 0, n10ct = INVERT_CASE_LIGHT ? 255 - i : i;
  10223. #if ENABLED(CASE_LIGHT_USE_NEOPIXEL)
  10224. leds.set_color(
  10225. MakeLEDColor(case_light_color.r, case_light_color.g, case_light_color.b, case_light_color.w, n10ct),
  10226. false
  10227. );
  10228. #else // !CASE_LIGHT_USE_NEOPIXEL
  10229. SET_OUTPUT(CASE_LIGHT_PIN);
  10230. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN))
  10231. analogWrite(CASE_LIGHT_PIN, n10ct);
  10232. else {
  10233. const bool s = case_light_on ? !INVERT_CASE_LIGHT : INVERT_CASE_LIGHT;
  10234. WRITE(CASE_LIGHT_PIN, s ? HIGH : LOW);
  10235. }
  10236. #endif // !CASE_LIGHT_USE_NEOPIXEL
  10237. }
  10238. #endif // HAS_CASE_LIGHT
  10239. /**
  10240. * M355: Turn case light on/off and set brightness
  10241. *
  10242. * P<byte> Set case light brightness (PWM pin required - ignored otherwise)
  10243. *
  10244. * S<bool> Set case light on/off
  10245. *
  10246. * When S turns on the light on a PWM pin then the current brightness level is used/restored
  10247. *
  10248. * M355 P200 S0 turns off the light & sets the brightness level
  10249. * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin)
  10250. */
  10251. inline void gcode_M355() {
  10252. #if HAS_CASE_LIGHT
  10253. uint8_t args = 0;
  10254. if (parser.seenval('P')) ++args, case_light_brightness = parser.value_byte();
  10255. if (parser.seenval('S')) ++args, case_light_on = parser.value_bool();
  10256. if (args) update_case_light();
  10257. // always report case light status
  10258. SERIAL_ECHO_START();
  10259. if (!case_light_on) {
  10260. SERIAL_ECHOLNPGM("Case light: off");
  10261. }
  10262. else {
  10263. if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLNPGM("Case light: on");
  10264. else SERIAL_ECHOLNPAIR("Case light: ", int(case_light_brightness));
  10265. }
  10266. #else
  10267. SERIAL_ERROR_START();
  10268. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  10269. #endif // HAS_CASE_LIGHT
  10270. }
  10271. #if ENABLED(MIXING_EXTRUDER)
  10272. /**
  10273. * M163: Set a single mix factor for a mixing extruder
  10274. * This is called "weight" by some systems.
  10275. * The 'P' values must sum to 1.0 or must be followed by M164 to normalize them.
  10276. *
  10277. * S[index] The channel index to set
  10278. * P[float] The mix value
  10279. */
  10280. inline void gcode_M163() {
  10281. const int mix_index = parser.intval('S');
  10282. if (mix_index < MIXING_STEPPERS)
  10283. mixing_factor[mix_index] = MAX(parser.floatval('P'), 0.0);
  10284. }
  10285. /**
  10286. * M164: Normalize and commit the mix.
  10287. * If 'S' is given store as a virtual tool. (Requires MIXING_VIRTUAL_TOOLS > 1)
  10288. *
  10289. * S[index] The virtual tool to store
  10290. */
  10291. inline void gcode_M164() {
  10292. normalize_mix();
  10293. #if MIXING_VIRTUAL_TOOLS > 1
  10294. const int tool_index = parser.intval('S', -1);
  10295. if (WITHIN(tool_index, 0, MIXING_VIRTUAL_TOOLS - 1)) {
  10296. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10297. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  10298. }
  10299. #endif
  10300. }
  10301. #if ENABLED(DIRECT_MIXING_IN_G1)
  10302. /**
  10303. * M165: Set multiple mix factors for a mixing extruder.
  10304. * Factors that are left out will be set to 0.
  10305. * All factors should sum to 1.0, but they will be normalized regardless.
  10306. *
  10307. * A[factor] Mix factor for extruder stepper 1
  10308. * B[factor] Mix factor for extruder stepper 2
  10309. * C[factor] Mix factor for extruder stepper 3
  10310. * D[factor] Mix factor for extruder stepper 4
  10311. * H[factor] Mix factor for extruder stepper 5
  10312. * I[factor] Mix factor for extruder stepper 6
  10313. */
  10314. inline void gcode_M165() { gcode_get_mix(); }
  10315. #endif
  10316. #endif // MIXING_EXTRUDER
  10317. /**
  10318. * M999: Restart after being stopped
  10319. *
  10320. * Default behaviour is to flush the serial buffer and request
  10321. * a resend to the host starting on the last N line received.
  10322. *
  10323. * Sending "M999 S1" will resume printing without flushing the
  10324. * existing command buffer.
  10325. *
  10326. */
  10327. inline void gcode_M999() {
  10328. Running = true;
  10329. lcd_reset_alert_level();
  10330. if (parser.boolval('S')) return;
  10331. // gcode_LastN = Stopped_gcode_LastN;
  10332. flush_and_request_resend();
  10333. }
  10334. #if DO_SWITCH_EXTRUDER
  10335. #if EXTRUDERS > 3
  10336. #define REQ_ANGLES 4
  10337. #define _SERVO_NR (e < 2 ? SWITCHING_EXTRUDER_SERVO_NR : SWITCHING_EXTRUDER_E23_SERVO_NR)
  10338. #else
  10339. #define REQ_ANGLES 2
  10340. #define _SERVO_NR SWITCHING_EXTRUDER_SERVO_NR
  10341. #endif
  10342. inline void move_extruder_servo(const uint8_t e) {
  10343. constexpr int16_t angles[] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  10344. static_assert(COUNT(angles) == REQ_ANGLES, "SWITCHING_EXTRUDER_SERVO_ANGLES needs " STRINGIFY(REQ_ANGLES) " angles.");
  10345. planner.synchronize();
  10346. #if EXTRUDERS & 1
  10347. if (e < EXTRUDERS - 1)
  10348. #endif
  10349. {
  10350. MOVE_SERVO(_SERVO_NR, angles[e]);
  10351. safe_delay(500);
  10352. }
  10353. }
  10354. #endif // DO_SWITCH_EXTRUDER
  10355. #if ENABLED(SWITCHING_NOZZLE)
  10356. inline void move_nozzle_servo(const uint8_t e) {
  10357. const int16_t angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  10358. planner.synchronize();
  10359. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  10360. safe_delay(500);
  10361. }
  10362. #endif
  10363. inline void invalid_extruder_error(const uint8_t e) {
  10364. SERIAL_ECHO_START();
  10365. SERIAL_CHAR('T');
  10366. SERIAL_ECHO_F(e, DEC);
  10367. SERIAL_CHAR(' ');
  10368. SERIAL_ECHOLNPGM(MSG_INVALID_EXTRUDER);
  10369. }
  10370. #if ENABLED(PARKING_EXTRUDER)
  10371. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10372. #define PE_MAGNET_ON_STATE !PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE
  10373. #else
  10374. #define PE_MAGNET_ON_STATE PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE
  10375. #endif
  10376. void pe_set_magnet(const uint8_t extruder_num, const uint8_t state) {
  10377. switch (extruder_num) {
  10378. case 1: OUT_WRITE(SOL1_PIN, state); break;
  10379. default: OUT_WRITE(SOL0_PIN, state); break;
  10380. }
  10381. #if PARKING_EXTRUDER_SOLENOIDS_DELAY > 0
  10382. dwell(PARKING_EXTRUDER_SOLENOIDS_DELAY);
  10383. #endif
  10384. }
  10385. inline void pe_activate_magnet(const uint8_t extruder_num) { pe_set_magnet(extruder_num, PE_MAGNET_ON_STATE); }
  10386. inline void pe_deactivate_magnet(const uint8_t extruder_num) { pe_set_magnet(extruder_num, !PE_MAGNET_ON_STATE); }
  10387. #endif // PARKING_EXTRUDER
  10388. #if HAS_FANMUX
  10389. void fanmux_switch(const uint8_t e) {
  10390. WRITE(FANMUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  10391. #if PIN_EXISTS(FANMUX1)
  10392. WRITE(FANMUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  10393. #if PIN_EXISTS(FANMUX2)
  10394. WRITE(FANMUX2, TEST(e, 2) ? HIGH : LOW);
  10395. #endif
  10396. #endif
  10397. }
  10398. FORCE_INLINE void fanmux_init(void) {
  10399. SET_OUTPUT(FANMUX0_PIN);
  10400. #if PIN_EXISTS(FANMUX1)
  10401. SET_OUTPUT(FANMUX1_PIN);
  10402. #if PIN_EXISTS(FANMUX2)
  10403. SET_OUTPUT(FANMUX2_PIN);
  10404. #endif
  10405. #endif
  10406. fanmux_switch(0);
  10407. }
  10408. #endif // HAS_FANMUX
  10409. /**
  10410. * Tool Change functions
  10411. */
  10412. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10413. inline void mixing_tool_change(const uint8_t tmp_extruder) {
  10414. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  10415. return invalid_extruder_error(tmp_extruder);
  10416. // T0-Tnnn: Switch virtual tool by changing the mix
  10417. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  10418. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  10419. }
  10420. #endif // MIXING_EXTRUDER && MIXING_VIRTUAL_TOOLS > 1
  10421. #if ENABLED(DUAL_X_CARRIAGE)
  10422. inline void dualx_tool_change(const uint8_t tmp_extruder, bool &no_move) {
  10423. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10424. if (DEBUGGING(LEVELING)) {
  10425. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  10426. switch (dual_x_carriage_mode) {
  10427. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  10428. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  10429. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  10430. }
  10431. }
  10432. #endif
  10433. const float xhome = x_home_pos(active_extruder);
  10434. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  10435. && IsRunning()
  10436. && (delayed_move_time || current_position[X_AXIS] != xhome)
  10437. ) {
  10438. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  10439. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  10440. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  10441. #endif
  10442. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10443. if (DEBUGGING(LEVELING)) {
  10444. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  10445. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  10446. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  10447. }
  10448. #endif
  10449. // Park old head: 1) raise 2) move to park position 3) lower
  10450. for (uint8_t i = 0; i < 3; i++)
  10451. planner.buffer_line(
  10452. i == 0 ? current_position[X_AXIS] : xhome,
  10453. current_position[Y_AXIS],
  10454. i == 2 ? current_position[Z_AXIS] : raised_z,
  10455. current_position[E_CART],
  10456. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  10457. active_extruder
  10458. );
  10459. planner.synchronize();
  10460. }
  10461. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  10462. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  10463. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10464. // Activate the new extruder ahead of calling set_axis_is_at_home!
  10465. active_extruder = tmp_extruder;
  10466. // This function resets the max/min values - the current position may be overwritten below.
  10467. set_axis_is_at_home(X_AXIS);
  10468. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10469. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  10470. #endif
  10471. // Only when auto-parking are carriages safe to move
  10472. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  10473. switch (dual_x_carriage_mode) {
  10474. case DXC_FULL_CONTROL_MODE:
  10475. // New current position is the position of the activated extruder
  10476. current_position[X_AXIS] = inactive_extruder_x_pos;
  10477. // Save the inactive extruder's position (from the old current_position)
  10478. inactive_extruder_x_pos = destination[X_AXIS];
  10479. break;
  10480. case DXC_AUTO_PARK_MODE:
  10481. // record raised toolhead position for use by unpark
  10482. COPY(raised_parked_position, current_position);
  10483. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  10484. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  10485. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  10486. #endif
  10487. active_extruder_parked = true;
  10488. delayed_move_time = 0;
  10489. break;
  10490. case DXC_DUPLICATION_MODE:
  10491. // If the new extruder is the left one, set it "parked"
  10492. // This triggers the second extruder to move into the duplication position
  10493. active_extruder_parked = (active_extruder == 0);
  10494. current_position[X_AXIS] = active_extruder_parked ? inactive_extruder_x_pos : destination[X_AXIS] + duplicate_extruder_x_offset;
  10495. inactive_extruder_x_pos = destination[X_AXIS];
  10496. extruder_duplication_enabled = false;
  10497. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10498. if (DEBUGGING(LEVELING)) {
  10499. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  10500. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  10501. }
  10502. #endif
  10503. break;
  10504. }
  10505. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10506. if (DEBUGGING(LEVELING)) {
  10507. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  10508. DEBUG_POS("New extruder (parked)", current_position);
  10509. }
  10510. #endif
  10511. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  10512. }
  10513. #endif // DUAL_X_CARRIAGE
  10514. #if ENABLED(PARKING_EXTRUDER)
  10515. inline void parking_extruder_tool_change(const uint8_t tmp_extruder, bool no_move) {
  10516. constexpr float z_raise = PARKING_EXTRUDER_SECURITY_RAISE;
  10517. if (!no_move) {
  10518. const float parkingposx[] = PARKING_EXTRUDER_PARKING_X,
  10519. midpos = (parkingposx[0] + parkingposx[1]) * 0.5 + hotend_offset[X_AXIS][active_extruder],
  10520. grabpos = parkingposx[tmp_extruder] + hotend_offset[X_AXIS][active_extruder]
  10521. + (tmp_extruder == 0 ? -(PARKING_EXTRUDER_GRAB_DISTANCE) : PARKING_EXTRUDER_GRAB_DISTANCE);
  10522. /**
  10523. * Steps:
  10524. * 1. Raise Z-Axis to give enough clearance
  10525. * 2. Move to park position of old extruder
  10526. * 3. Disengage magnetic field, wait for delay
  10527. * 4. Move near new extruder
  10528. * 5. Engage magnetic field for new extruder
  10529. * 6. Move to parking incl. offset of new extruder
  10530. * 7. Lower Z-Axis
  10531. */
  10532. // STEP 1
  10533. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10534. SERIAL_ECHOLNPGM("Starting Autopark");
  10535. if (DEBUGGING(LEVELING)) DEBUG_POS("current position:", current_position);
  10536. #endif
  10537. current_position[Z_AXIS] += z_raise;
  10538. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10539. SERIAL_ECHOLNPGM("(1) Raise Z-Axis ");
  10540. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving to Raised Z-Position", current_position);
  10541. #endif
  10542. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10543. planner.synchronize();
  10544. // STEP 2
  10545. current_position[X_AXIS] = parkingposx[active_extruder] + hotend_offset[X_AXIS][active_extruder];
  10546. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10547. SERIAL_ECHOLNPAIR("(2) Park extruder ", active_extruder);
  10548. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving ParkPos", current_position);
  10549. #endif
  10550. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10551. planner.synchronize();
  10552. // STEP 3
  10553. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10554. SERIAL_ECHOLNPGM("(3) Disengage magnet ");
  10555. #endif
  10556. pe_deactivate_magnet(active_extruder);
  10557. // STEP 4
  10558. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10559. SERIAL_ECHOLNPGM("(4) Move to position near new extruder");
  10560. #endif
  10561. current_position[X_AXIS] += (active_extruder == 0 ? 10 : -10); // move 10mm away from parked extruder
  10562. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10563. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving away from parked extruder", current_position);
  10564. #endif
  10565. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10566. planner.synchronize();
  10567. // STEP 5
  10568. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10569. SERIAL_ECHOLNPGM("(5) Engage magnetic field");
  10570. #endif
  10571. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10572. pe_activate_magnet(active_extruder); //just save power for inverted magnets
  10573. #endif
  10574. pe_activate_magnet(tmp_extruder);
  10575. // STEP 6
  10576. current_position[X_AXIS] = grabpos + (tmp_extruder == 0 ? (+10) : (-10));
  10577. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10578. current_position[X_AXIS] = grabpos;
  10579. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10580. SERIAL_ECHOLNPAIR("(6) Unpark extruder ", tmp_extruder);
  10581. if (DEBUGGING(LEVELING)) DEBUG_POS("Move UnparkPos", current_position);
  10582. #endif
  10583. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS]/2, active_extruder);
  10584. planner.synchronize();
  10585. // Step 7
  10586. current_position[X_AXIS] = midpos - hotend_offset[X_AXIS][tmp_extruder];
  10587. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10588. SERIAL_ECHOLNPGM("(7) Move midway between hotends");
  10589. if (DEBUGGING(LEVELING)) DEBUG_POS("Move midway to new extruder", current_position);
  10590. #endif
  10591. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10592. planner.synchronize();
  10593. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10594. SERIAL_ECHOLNPGM("Autopark done.");
  10595. #endif
  10596. }
  10597. else { // nomove == true
  10598. // Only engage magnetic field for new extruder
  10599. pe_activate_magnet(tmp_extruder);
  10600. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10601. pe_activate_magnet(active_extruder); // Just save power for inverted magnets
  10602. #endif
  10603. }
  10604. current_position[Z_AXIS] += hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10605. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10606. if (DEBUGGING(LEVELING)) DEBUG_POS("Applying Z-offset", current_position);
  10607. #endif
  10608. }
  10609. #endif // PARKING_EXTRUDER
  10610. /**
  10611. * Perform a tool-change, which may result in moving the
  10612. * previous tool out of the way and the new tool into place.
  10613. */
  10614. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  10615. planner.synchronize();
  10616. #if HAS_LEVELING
  10617. // Set current position to the physical position
  10618. const bool leveling_was_active = planner.leveling_active;
  10619. set_bed_leveling_enabled(false);
  10620. #endif
  10621. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10622. mixing_tool_change(tmp_extruder);
  10623. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  10624. if (tmp_extruder >= EXTRUDERS)
  10625. return invalid_extruder_error(tmp_extruder);
  10626. #if HOTENDS > 1
  10627. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  10628. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  10629. if (tmp_extruder != active_extruder) {
  10630. if (!no_move && axis_unhomed_error()) {
  10631. no_move = true;
  10632. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10633. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("No move on toolchange");
  10634. #endif
  10635. }
  10636. #if ENABLED(DUAL_X_CARRIAGE)
  10637. #if HAS_SOFTWARE_ENDSTOPS
  10638. // Update the X software endstops early
  10639. active_extruder = tmp_extruder;
  10640. update_software_endstops(X_AXIS);
  10641. active_extruder = !tmp_extruder;
  10642. #endif
  10643. // Don't move the new extruder out of bounds
  10644. if (!WITHIN(current_position[X_AXIS], soft_endstop_min[X_AXIS], soft_endstop_max[X_AXIS]))
  10645. no_move = true;
  10646. if (!no_move) set_destination_from_current();
  10647. dualx_tool_change(tmp_extruder, no_move); // Can modify no_move
  10648. #else // !DUAL_X_CARRIAGE
  10649. set_destination_from_current();
  10650. #if ENABLED(PARKING_EXTRUDER)
  10651. parking_extruder_tool_change(tmp_extruder, no_move);
  10652. #endif
  10653. #if ENABLED(SWITCHING_NOZZLE)
  10654. // Always raise by at least 1 to avoid workpiece
  10655. const float zdiff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10656. current_position[Z_AXIS] += (zdiff > 0.0 ? zdiff : 0.0) + 1;
  10657. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10658. move_nozzle_servo(tmp_extruder);
  10659. #endif
  10660. const float xdiff = hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  10661. ydiff = hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder];
  10662. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10663. if (DEBUGGING(LEVELING)) {
  10664. SERIAL_ECHOPAIR("Offset Tool XY by { ", xdiff);
  10665. SERIAL_ECHOPAIR(", ", ydiff);
  10666. SERIAL_ECHOLNPGM(" }");
  10667. }
  10668. #endif
  10669. // The newly-selected extruder XY is actually at...
  10670. current_position[X_AXIS] += xdiff;
  10671. current_position[Y_AXIS] += ydiff;
  10672. // Set the new active extruder
  10673. active_extruder = tmp_extruder;
  10674. #endif // !DUAL_X_CARRIAGE
  10675. #if ENABLED(SWITCHING_NOZZLE)
  10676. // The newly-selected extruder Z is actually at...
  10677. current_position[Z_AXIS] -= zdiff;
  10678. #endif
  10679. // Tell the planner the new "current position"
  10680. SYNC_PLAN_POSITION_KINEMATIC();
  10681. #if ENABLED(DELTA)
  10682. //LOOP_XYZ(i) update_software_endstops(i); // or modify the constrain function
  10683. const bool safe_to_move = current_position[Z_AXIS] < delta_clip_start_height - 1;
  10684. #else
  10685. constexpr bool safe_to_move = true;
  10686. #endif
  10687. // Raise, move, and lower again
  10688. if (safe_to_move && !no_move && IsRunning()) {
  10689. #if DISABLED(SWITCHING_NOZZLE)
  10690. // Do a small lift to avoid the workpiece in the move back (below)
  10691. current_position[Z_AXIS] += 1.0;
  10692. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10693. #endif
  10694. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10695. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  10696. #endif
  10697. // Move back to the original (or tweaked) position
  10698. do_blocking_move_to(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS]);
  10699. #if ENABLED(DUAL_X_CARRIAGE)
  10700. active_extruder_parked = false;
  10701. #endif
  10702. }
  10703. #if ENABLED(SWITCHING_NOZZLE)
  10704. else {
  10705. // Move back down. (Including when the new tool is higher.)
  10706. do_blocking_move_to_z(destination[Z_AXIS], planner.max_feedrate_mm_s[Z_AXIS]);
  10707. }
  10708. #endif
  10709. } // (tmp_extruder != active_extruder)
  10710. planner.synchronize();
  10711. #if ENABLED(EXT_SOLENOID) && !ENABLED(PARKING_EXTRUDER)
  10712. disable_all_solenoids();
  10713. enable_solenoid_on_active_extruder();
  10714. #endif
  10715. feedrate_mm_s = old_feedrate_mm_s;
  10716. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(DUAL_X_CARRIAGE)
  10717. update_software_endstops(X_AXIS);
  10718. #endif
  10719. #else // HOTENDS <= 1
  10720. UNUSED(fr_mm_s);
  10721. UNUSED(no_move);
  10722. #if ENABLED(MK2_MULTIPLEXER)
  10723. if (tmp_extruder >= E_STEPPERS)
  10724. return invalid_extruder_error(tmp_extruder);
  10725. select_multiplexed_stepper(tmp_extruder);
  10726. #endif
  10727. // Set the new active extruder
  10728. active_extruder = tmp_extruder;
  10729. #endif // HOTENDS <= 1
  10730. #if DO_SWITCH_EXTRUDER
  10731. planner.synchronize();
  10732. move_extruder_servo(active_extruder);
  10733. #endif
  10734. #if HAS_FANMUX
  10735. fanmux_switch(active_extruder);
  10736. #endif
  10737. #if HAS_LEVELING
  10738. // Restore leveling to re-establish the logical position
  10739. set_bed_leveling_enabled(leveling_was_active);
  10740. #endif
  10741. SERIAL_ECHO_START();
  10742. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(active_extruder));
  10743. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  10744. }
  10745. /**
  10746. * T0-T3: Switch tool, usually switching extruders
  10747. *
  10748. * F[units/min] Set the movement feedrate
  10749. * S1 Don't move the tool in XY after change
  10750. */
  10751. inline void gcode_T(const uint8_t tmp_extruder) {
  10752. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10753. if (DEBUGGING(LEVELING)) {
  10754. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  10755. SERIAL_CHAR(')');
  10756. SERIAL_EOL();
  10757. DEBUG_POS("BEFORE", current_position);
  10758. }
  10759. #endif
  10760. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  10761. tool_change(tmp_extruder);
  10762. #elif HOTENDS > 1
  10763. tool_change(
  10764. tmp_extruder,
  10765. MMM_TO_MMS(parser.linearval('F')),
  10766. (tmp_extruder == active_extruder) || parser.boolval('S')
  10767. );
  10768. #endif
  10769. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10770. if (DEBUGGING(LEVELING)) {
  10771. DEBUG_POS("AFTER", current_position);
  10772. SERIAL_ECHOLNPGM("<<< gcode_T");
  10773. }
  10774. #endif
  10775. }
  10776. /**
  10777. * Process the parsed command and dispatch it to its handler
  10778. */
  10779. void process_parsed_command() {
  10780. KEEPALIVE_STATE(IN_HANDLER);
  10781. // Handle a known G, M, or T
  10782. switch (parser.command_letter) {
  10783. case 'G': switch (parser.codenum) {
  10784. case 0: case 1: gcode_G0_G1( // G0: Fast Move, G1: Linear Move
  10785. #if IS_SCARA
  10786. parser.codenum == 0
  10787. #endif
  10788. ); break;
  10789. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  10790. case 2: case 3: gcode_G2_G3(parser.codenum == 2); break; // G2: CW ARC, G3: CCW ARC
  10791. #endif
  10792. case 4: gcode_G4(); break; // G4: Dwell
  10793. #if ENABLED(BEZIER_CURVE_SUPPORT)
  10794. case 5: gcode_G5(); break; // G5: Cubic B_spline
  10795. #endif
  10796. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  10797. case 6: gcode_G6(); break; // G6: Direct stepper move
  10798. #endif
  10799. #if ENABLED(FWRETRACT)
  10800. case 10: gcode_G10(); break; // G10: Retract
  10801. case 11: gcode_G11(); break; // G11: Prime
  10802. #endif
  10803. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  10804. case 12: gcode_G12(); break; // G12: Clean Nozzle
  10805. #endif
  10806. #if ENABLED(CNC_WORKSPACE_PLANES)
  10807. case 17: gcode_G17(); break; // G17: Select Plane XY
  10808. case 18: gcode_G18(); break; // G18: Select Plane ZX
  10809. case 19: gcode_G19(); break; // G19: Select Plane YZ
  10810. #endif
  10811. #if ENABLED(INCH_MODE_SUPPORT)
  10812. case 20: gcode_G20(); break; // G20: Inch Units
  10813. case 21: gcode_G21(); break; // G21: Millimeter Units
  10814. #endif
  10815. #if ENABLED(G26_MESH_VALIDATION)
  10816. case 26: gcode_G26(); break; // G26: Mesh Validation Pattern
  10817. #endif
  10818. #if ENABLED(NOZZLE_PARK_FEATURE)
  10819. case 27: gcode_G27(); break; // G27: Park Nozzle
  10820. #endif
  10821. case 28: gcode_G28(false); break; // G28: Home one or more axes
  10822. #if HAS_LEVELING
  10823. case 29: gcode_G29(); break; // G29: Detailed Z probe
  10824. #endif
  10825. #if HAS_BED_PROBE
  10826. case 30: gcode_G30(); break; // G30: Single Z probe
  10827. #endif
  10828. #if ENABLED(Z_PROBE_SLED)
  10829. case 31: gcode_G31(); break; // G31: Dock sled
  10830. case 32: gcode_G32(); break; // G32: Undock sled
  10831. #endif
  10832. #if ENABLED(DELTA_AUTO_CALIBRATION)
  10833. case 33: gcode_G33(); break; // G33: Delta Auto-Calibration
  10834. #endif
  10835. #if ENABLED(G38_PROBE_TARGET)
  10836. case 38:
  10837. if (parser.subcode == 2 || parser.subcode == 3)
  10838. gcode_G38(parser.subcode == 2); // G38.2, G38.3: Probe towards object
  10839. break;
  10840. #endif
  10841. #if HAS_MESH
  10842. case 42: gcode_G42(); break; // G42: Move to mesh point
  10843. #endif
  10844. case 90: relative_mode = false; break; // G90: Absolute coordinates
  10845. case 91: relative_mode = true; break; // G91: Relative coordinates
  10846. case 92: gcode_G92(); break; // G92: Set Position
  10847. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  10848. case 95: gcode_G95(); break; // G95: Set torque mode
  10849. case 96: gcode_G96(); break; // G96: Mark encoder reference point
  10850. #endif
  10851. #if ENABLED(DEBUG_GCODE_PARSER)
  10852. case 800: parser.debug(); break; // G800: GCode Parser Test for G
  10853. #endif
  10854. default: parser.unknown_command_error();
  10855. }
  10856. break;
  10857. case 'M': switch (parser.codenum) {
  10858. #if HAS_RESUME_CONTINUE
  10859. case 0: case 1: gcode_M0_M1(); break; // M0: Unconditional stop, M1: Conditional stop
  10860. #endif
  10861. #if ENABLED(SPINDLE_LASER_ENABLE)
  10862. case 3: gcode_M3_M4(true); break; // M3: Laser/CW-Spindle Power
  10863. case 4: gcode_M3_M4(false); break; // M4: Laser/CCW-Spindle Power
  10864. case 5: gcode_M5(); break; // M5: Laser/Spindle OFF
  10865. #endif
  10866. case 17: gcode_M17(); break; // M17: Enable all steppers
  10867. #if ENABLED(SDSUPPORT)
  10868. case 20: gcode_M20(); break; // M20: List SD Card
  10869. case 21: gcode_M21(); break; // M21: Init SD Card
  10870. case 22: gcode_M22(); break; // M22: Release SD Card
  10871. case 23: gcode_M23(); break; // M23: Select File
  10872. case 24: gcode_M24(); break; // M24: Start SD Print
  10873. case 25: gcode_M25(); break; // M25: Pause SD Print
  10874. case 26: gcode_M26(); break; // M26: Set SD Index
  10875. case 27: gcode_M27(); break; // M27: Get SD Status
  10876. case 28: gcode_M28(); break; // M28: Start SD Write
  10877. case 29: gcode_M29(); break; // M29: Stop SD Write
  10878. case 30: gcode_M30(); break; // M30: Delete File
  10879. case 32: gcode_M32(); break; // M32: Select file, Start SD Print
  10880. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  10881. case 33: gcode_M33(); break; // M33: Report longname path
  10882. #endif
  10883. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  10884. case 34: gcode_M34(); break; // M34: Set SD card sorting options
  10885. #endif
  10886. case 928: gcode_M928(); break; // M928: Start SD write
  10887. #endif // SDSUPPORT
  10888. case 31: gcode_M31(); break; // M31: Report print job elapsed time
  10889. case 42: gcode_M42(); break; // M42: Change pin state
  10890. #if ENABLED(PINS_DEBUGGING)
  10891. case 43: gcode_M43(); break; // M43: Read/monitor pin and endstop states
  10892. #endif
  10893. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  10894. case 48: gcode_M48(); break; // M48: Z probe repeatability test
  10895. #endif
  10896. #if ENABLED(G26_MESH_VALIDATION)
  10897. case 49: gcode_M49(); break; // M49: Toggle the G26 Debug Flag
  10898. #endif
  10899. #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY)
  10900. case 73: gcode_M73(); break; // M73: Set Print Progress %
  10901. #endif
  10902. case 75: gcode_M75(); break; // M75: Start Print Job Timer
  10903. case 76: gcode_M76(); break; // M76: Pause Print Job Timer
  10904. case 77: gcode_M77(); break; // M77: Stop Print Job Timer
  10905. #if ENABLED(PRINTCOUNTER)
  10906. case 78: gcode_M78(); break; // M78: Report Print Statistics
  10907. #endif
  10908. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  10909. case 100: gcode_M100(); break; // M100: Free Memory Report
  10910. #endif
  10911. case 104: gcode_M104(); break; // M104: Set Hotend Temperature
  10912. case 110: gcode_M110(); break; // M110: Set Current Line Number
  10913. case 111: gcode_M111(); break; // M111: Set Debug Flags
  10914. #if DISABLED(EMERGENCY_PARSER)
  10915. case 108: gcode_M108(); break; // M108: Cancel Waiting
  10916. case 112: gcode_M112(); break; // M112: Emergency Stop
  10917. case 410: gcode_M410(); break; // M410: Quickstop. Abort all planned moves
  10918. #else
  10919. case 108: case 112: case 410: break; // Silently drop as handled by emergency parser
  10920. #endif
  10921. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  10922. case 113: gcode_M113(); break; // M113: Set Host Keepalive Interval
  10923. #endif
  10924. case 105: gcode_M105(); KEEPALIVE_STATE(NOT_BUSY); return; // M105: Report Temperatures (and say "ok")
  10925. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  10926. case 155: gcode_M155(); break; // M155: Set Temperature Auto-report Interval
  10927. #endif
  10928. case 109: gcode_M109(); break; // M109: Set Hotend Temperature. Wait for target.
  10929. #if HAS_HEATED_BED
  10930. case 140: gcode_M140(); break; // M140: Set Bed Temperature
  10931. case 190: gcode_M190(); break; // M190: Set Bed Temperature. Wait for target.
  10932. #endif
  10933. #if FAN_COUNT > 0
  10934. case 106: gcode_M106(); break; // M106: Set Fan Speed
  10935. case 107: gcode_M107(); break; // M107: Fan Off
  10936. #endif
  10937. #if ENABLED(PARK_HEAD_ON_PAUSE)
  10938. case 125: gcode_M125(); break; // M125: Park (for Filament Change)
  10939. #endif
  10940. #if ENABLED(BARICUDA)
  10941. #if HAS_HEATER_1
  10942. case 126: gcode_M126(); break; // M126: Valve 1 Open
  10943. case 127: gcode_M127(); break; // M127: Valve 1 Closed
  10944. #endif
  10945. #if HAS_HEATER_2
  10946. case 128: gcode_M128(); break; // M128: Valve 2 Open
  10947. case 129: gcode_M129(); break; // M129: Valve 2 Closed
  10948. #endif
  10949. #endif
  10950. #if HAS_POWER_SWITCH
  10951. case 80: gcode_M80(); break; // M80: Turn on Power Supply
  10952. #endif
  10953. case 81: gcode_M81(); break; // M81: Turn off Power and Power Supply
  10954. case 82: gcode_M82(); break; // M82: Disable Relative E-Axis
  10955. case 83: gcode_M83(); break; // M83: Set Relative E-Axis
  10956. case 18: case 84: gcode_M18_M84(); break; // M18/M84: Disable Steppers / Set Timeout
  10957. case 85: gcode_M85(); break; // M85: Set inactivity stepper shutdown timeout
  10958. case 92: gcode_M92(); break; // M92: Set steps-per-unit
  10959. case 114: gcode_M114(); break; // M114: Report Current Position
  10960. case 115: gcode_M115(); break; // M115: Capabilities Report
  10961. case 117: gcode_M117(); break; // M117: Set LCD message text
  10962. case 118: gcode_M118(); break; // M118: Print a message in the host console
  10963. case 119: gcode_M119(); break; // M119: Report Endstop states
  10964. case 120: gcode_M120(); break; // M120: Enable Endstops
  10965. case 121: gcode_M121(); break; // M121: Disable Endstops
  10966. #if ENABLED(ULTIPANEL)
  10967. case 145: gcode_M145(); break; // M145: Set material heatup parameters
  10968. #endif
  10969. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  10970. case 149: gcode_M149(); break; // M149: Set Temperature Units, C F K
  10971. #endif
  10972. #if HAS_COLOR_LEDS
  10973. case 150: gcode_M150(); break; // M150: Set Status LED Color
  10974. #endif
  10975. #if ENABLED(MIXING_EXTRUDER)
  10976. case 163: gcode_M163(); break; // M163: Set Mixing Component
  10977. #if MIXING_VIRTUAL_TOOLS > 1
  10978. case 164: gcode_M164(); break; // M164: Save Current Mix
  10979. #endif
  10980. #if ENABLED(DIRECT_MIXING_IN_G1)
  10981. case 165: gcode_M165(); break; // M165: Set Multiple Mixing Components
  10982. #endif
  10983. #endif
  10984. #if DISABLED(NO_VOLUMETRICS)
  10985. case 200: gcode_M200(); break; // M200: Set Filament Diameter, Volumetric Extrusion
  10986. #endif
  10987. case 201: gcode_M201(); break; // M201: Set Max Printing Acceleration (units/sec^2)
  10988. #if 0
  10989. case 202: gcode_M202(); break; // M202: Not used for Sprinter/grbl gen6
  10990. #endif
  10991. case 203: gcode_M203(); break; // M203: Set Max Feedrate (units/sec)
  10992. case 204: gcode_M204(); break; // M204: Set Acceleration
  10993. case 205: gcode_M205(); break; // M205: Set Advanced settings
  10994. #if HAS_M206_COMMAND
  10995. case 206: gcode_M206(); break; // M206: Set Home Offsets
  10996. case 428: gcode_M428(); break; // M428: Set Home Offsets based on current position
  10997. #endif
  10998. #if ENABLED(FWRETRACT)
  10999. case 207: gcode_M207(); break; // M207: Set Retract Length, Feedrate, Z lift
  11000. case 208: gcode_M208(); break; // M208: Set Additional Prime Length and Feedrate
  11001. case 209:
  11002. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) gcode_M209(); // M209: Turn Auto-Retract on/off
  11003. break;
  11004. #endif
  11005. case 211: gcode_M211(); break; // M211: Enable/Disable/Report Software Endstops
  11006. #if HOTENDS > 1
  11007. case 218: gcode_M218(); break; // M218: Set Tool Offset
  11008. #endif
  11009. case 220: gcode_M220(); break; // M220: Set Feedrate Percentage
  11010. case 221: gcode_M221(); break; // M221: Set Flow Percentage
  11011. case 226: gcode_M226(); break; // M226: Wait for Pin State
  11012. #if defined(CHDK) || HAS_PHOTOGRAPH
  11013. case 240: gcode_M240(); break; // M240: Trigger Camera
  11014. #endif
  11015. #if HAS_LCD_CONTRAST
  11016. case 250: gcode_M250(); break; // M250: Set LCD Contrast
  11017. #endif
  11018. #if ENABLED(EXPERIMENTAL_I2CBUS)
  11019. case 260: gcode_M260(); break; // M260: Send Data to i2c slave
  11020. case 261: gcode_M261(); break; // M261: Request Data from i2c slave
  11021. #endif
  11022. #if HAS_SERVOS
  11023. case 280: gcode_M280(); break; // M280: Set Servo Position
  11024. #endif
  11025. #if ENABLED(BABYSTEPPING)
  11026. case 290: gcode_M290(); break; // M290: Babystepping
  11027. #endif
  11028. #if HAS_BUZZER
  11029. case 300: gcode_M300(); break; // M300: Add Tone/Buzz to Queue
  11030. #endif
  11031. #if ENABLED(PIDTEMP)
  11032. case 301: gcode_M301(); break; // M301: Set Hotend PID parameters
  11033. #endif
  11034. #if ENABLED(PREVENT_COLD_EXTRUSION)
  11035. case 302: gcode_M302(); break; // M302: Set Minimum Extrusion Temp
  11036. #endif
  11037. case 303: gcode_M303(); break; // M303: PID Autotune
  11038. #if ENABLED(PIDTEMPBED)
  11039. case 304: gcode_M304(); break; // M304: Set Bed PID parameters
  11040. #endif
  11041. #if HAS_MICROSTEPS
  11042. case 350: gcode_M350(); break; // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  11043. case 351: gcode_M351(); break; // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  11044. #endif
  11045. case 355: gcode_M355(); break; // M355: Set Case Light brightness
  11046. #if ENABLED(MORGAN_SCARA)
  11047. case 360: if (gcode_M360()) return; break; // M360: SCARA Theta pos1
  11048. case 361: if (gcode_M361()) return; break; // M361: SCARA Theta pos2
  11049. case 362: if (gcode_M362()) return; break; // M362: SCARA Psi pos1
  11050. case 363: if (gcode_M363()) return; break; // M363: SCARA Psi pos2
  11051. case 364: if (gcode_M364()) return; break; // M364: SCARA Psi pos3 (90 deg to Theta)
  11052. #endif
  11053. case 400: gcode_M400(); break; // M400: Synchronize. Wait for moves to finish.
  11054. #if HAS_BED_PROBE
  11055. case 401: gcode_M401(); break; // M401: Deploy Probe
  11056. case 402: gcode_M402(); break; // M402: Stow Probe
  11057. #endif
  11058. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  11059. case 404: gcode_M404(); break; // M404: Set/Report Nominal Filament Width
  11060. case 405: gcode_M405(); break; // M405: Enable Filament Width Sensor
  11061. case 406: gcode_M406(); break; // M406: Disable Filament Width Sensor
  11062. case 407: gcode_M407(); break; // M407: Report Measured Filament Width
  11063. #endif
  11064. #if HAS_LEVELING
  11065. case 420: gcode_M420(); break; // M420: Set Bed Leveling Enabled / Fade
  11066. #endif
  11067. #if HAS_MESH
  11068. case 421: gcode_M421(); break; // M421: Set a Mesh Z value
  11069. #endif
  11070. case 500: gcode_M500(); break; // M500: Store Settings in EEPROM
  11071. case 501: gcode_M501(); break; // M501: Read Settings from EEPROM
  11072. case 502: gcode_M502(); break; // M502: Revert Settings to defaults
  11073. #if DISABLED(DISABLE_M503)
  11074. case 503: gcode_M503(); break; // M503: Report Settings (in SRAM)
  11075. #endif
  11076. #if ENABLED(EEPROM_SETTINGS)
  11077. case 504: gcode_M504(); break; // M504: Validate EEPROM
  11078. #endif
  11079. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  11080. case 540: gcode_M540(); break; // M540: Set Abort on Endstop Hit for SD Printing
  11081. #endif
  11082. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  11083. case 600: gcode_M600(); break; // M600: Pause for Filament Change
  11084. case 603: gcode_M603(); break; // M603: Configure Filament Change
  11085. #endif
  11086. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  11087. case 605: gcode_M605(); break; // M605: Set Dual X Carriage movement mode
  11088. #endif
  11089. #if ENABLED(DELTA) || ENABLED(HANGPRINTER)
  11090. case 665: gcode_M665(); break; // M665: Delta / Hangprinter Configuration
  11091. #endif
  11092. #if ENABLED(DELTA) || ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  11093. case 666: gcode_M666(); break; // M666: DELTA/Dual Endstop Adjustment
  11094. #endif
  11095. #if ENABLED(FILAMENT_LOAD_UNLOAD_GCODES)
  11096. case 701: gcode_M701(); break; // M701: Load Filament
  11097. case 702: gcode_M702(); break; // M702: Unload Filament
  11098. #endif
  11099. #if ENABLED(MAX7219_GCODE)
  11100. case 7219: gcode_M7219(); break; // M7219: Set LEDs, columns, and rows
  11101. #endif
  11102. #if ENABLED(DEBUG_GCODE_PARSER)
  11103. case 800: parser.debug(); break; // M800: GCode Parser Test for M
  11104. #endif
  11105. #if HAS_BED_PROBE
  11106. case 851: gcode_M851(); break; // M851: Set Z Probe Z Offset
  11107. #endif
  11108. #if ENABLED(SKEW_CORRECTION_GCODE)
  11109. case 852: gcode_M852(); break; // M852: Set Skew factors
  11110. #endif
  11111. #if ENABLED(I2C_POSITION_ENCODERS)
  11112. case 860: gcode_M860(); break; // M860: Report encoder module position
  11113. case 861: gcode_M861(); break; // M861: Report encoder module status
  11114. case 862: gcode_M862(); break; // M862: Perform axis test
  11115. case 863: gcode_M863(); break; // M863: Calibrate steps/mm
  11116. case 864: gcode_M864(); break; // M864: Change module address
  11117. case 865: gcode_M865(); break; // M865: Check module firmware version
  11118. case 866: gcode_M866(); break; // M866: Report axis error count
  11119. case 867: gcode_M867(); break; // M867: Toggle error correction
  11120. case 868: gcode_M868(); break; // M868: Set error correction threshold
  11121. case 869: gcode_M869(); break; // M869: Report axis error
  11122. #endif
  11123. #if ENABLED(LIN_ADVANCE)
  11124. case 900: gcode_M900(); break; // M900: Set Linear Advance K factor
  11125. #endif
  11126. case 907: gcode_M907(); break; // M907: Set Digital Trimpot Motor Current using axis codes.
  11127. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  11128. case 908: gcode_M908(); break; // M908: Direct Control Digital Trimpot
  11129. #if ENABLED(DAC_STEPPER_CURRENT)
  11130. case 909: gcode_M909(); break; // M909: Print Digipot/DAC current value (As with Printrbot RevF)
  11131. case 910: gcode_M910(); break; // M910: Commit Digipot/DAC value to External EEPROM (As with Printrbot RevF)
  11132. #endif
  11133. #endif
  11134. #if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC2208)
  11135. #if ENABLED(TMC_DEBUG)
  11136. case 122: gcode_M122(); break; // M122: Debug TMC steppers
  11137. #endif
  11138. case 906: gcode_M906(); break; // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  11139. case 911: gcode_M911(); break; // M911: Report TMC prewarn triggered flags
  11140. case 912: gcode_M912(); break; // M911: Clear TMC prewarn triggered flags
  11141. #if ENABLED(HYBRID_THRESHOLD)
  11142. case 913: gcode_M913(); break; // M913: Set HYBRID_THRESHOLD speed.
  11143. #endif
  11144. #if ENABLED(SENSORLESS_HOMING)
  11145. case 914: gcode_M914(); break; // M914: Set SENSORLESS_HOMING sensitivity.
  11146. #endif
  11147. #if ENABLED(TMC_Z_CALIBRATION)
  11148. case 915: gcode_M915(); break; // M915: TMC Z axis calibration routine
  11149. #endif
  11150. #endif
  11151. case 999: gcode_M999(); break; // M999: Restart after being Stopped
  11152. default: parser.unknown_command_error();
  11153. }
  11154. break;
  11155. case 'T': gcode_T(parser.codenum); break; // T: Tool Select
  11156. default: parser.unknown_command_error();
  11157. }
  11158. KEEPALIVE_STATE(NOT_BUSY);
  11159. ok_to_send();
  11160. }
  11161. void process_next_command() {
  11162. char * const current_command = command_queue[cmd_queue_index_r];
  11163. if (DEBUGGING(ECHO)) {
  11164. SERIAL_ECHO_START();
  11165. SERIAL_ECHOLN(current_command);
  11166. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  11167. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  11168. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  11169. #endif
  11170. }
  11171. // Parse the next command in the queue
  11172. parser.parse(current_command);
  11173. process_parsed_command();
  11174. }
  11175. /**
  11176. * Send a "Resend: nnn" message to the host to
  11177. * indicate that a command needs to be re-sent.
  11178. */
  11179. void flush_and_request_resend() {
  11180. //char command_queue[cmd_queue_index_r][100]="Resend:";
  11181. SERIAL_FLUSH();
  11182. SERIAL_PROTOCOLPGM(MSG_RESEND);
  11183. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  11184. ok_to_send();
  11185. }
  11186. /**
  11187. * Send an "ok" message to the host, indicating
  11188. * that a command was successfully processed.
  11189. *
  11190. * If ADVANCED_OK is enabled also include:
  11191. * N<int> Line number of the command, if any
  11192. * P<int> Planner space remaining
  11193. * B<int> Block queue space remaining
  11194. */
  11195. void ok_to_send() {
  11196. if (!send_ok[cmd_queue_index_r]) return;
  11197. SERIAL_PROTOCOLPGM(MSG_OK);
  11198. #if ENABLED(ADVANCED_OK)
  11199. char* p = command_queue[cmd_queue_index_r];
  11200. if (*p == 'N') {
  11201. SERIAL_PROTOCOL(' ');
  11202. SERIAL_ECHO(*p++);
  11203. while (NUMERIC_SIGNED(*p))
  11204. SERIAL_ECHO(*p++);
  11205. }
  11206. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  11207. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  11208. #endif
  11209. SERIAL_EOL();
  11210. }
  11211. #if HAS_SOFTWARE_ENDSTOPS
  11212. /**
  11213. * Constrain the given coordinates to the software endstops.
  11214. *
  11215. * For DELTA/SCARA the XY constraint is based on the smallest
  11216. * radius within the set software endstops.
  11217. */
  11218. void clamp_to_software_endstops(float target[XYZ]) {
  11219. if (!soft_endstops_enabled) return;
  11220. #if IS_KINEMATIC
  11221. const float dist_2 = HYPOT2(target[X_AXIS], target[Y_AXIS]);
  11222. if (dist_2 > soft_endstop_radius_2) {
  11223. const float ratio = soft_endstop_radius / SQRT(dist_2); // 200 / 300 = 0.66
  11224. target[X_AXIS] *= ratio;
  11225. target[Y_AXIS] *= ratio;
  11226. }
  11227. #else
  11228. #if ENABLED(MIN_SOFTWARE_ENDSTOP_X)
  11229. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  11230. #endif
  11231. #if ENABLED(MIN_SOFTWARE_ENDSTOP_Y)
  11232. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  11233. #endif
  11234. #if ENABLED(MAX_SOFTWARE_ENDSTOP_X)
  11235. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  11236. #endif
  11237. #if ENABLED(MAX_SOFTWARE_ENDSTOP_Y)
  11238. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  11239. #endif
  11240. #endif
  11241. #if ENABLED(MIN_SOFTWARE_ENDSTOP_Z)
  11242. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  11243. #endif
  11244. #if ENABLED(MAX_SOFTWARE_ENDSTOP_Z)
  11245. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  11246. #endif
  11247. }
  11248. #endif
  11249. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  11250. // Get the Z adjustment for non-linear bed leveling
  11251. float bilinear_z_offset(const float raw[XYZ]) {
  11252. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  11253. last_x = -999.999, last_y = -999.999;
  11254. // Whole units for the grid line indices. Constrained within bounds.
  11255. static int8_t gridx, gridy, nextx, nexty,
  11256. last_gridx = -99, last_gridy = -99;
  11257. // XY relative to the probed area
  11258. const float rx = raw[X_AXIS] - bilinear_start[X_AXIS],
  11259. ry = raw[Y_AXIS] - bilinear_start[Y_AXIS];
  11260. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  11261. // Keep using the last grid box
  11262. #define FAR_EDGE_OR_BOX 2
  11263. #else
  11264. // Just use the grid far edge
  11265. #define FAR_EDGE_OR_BOX 1
  11266. #endif
  11267. if (last_x != rx) {
  11268. last_x = rx;
  11269. ratio_x = rx * ABL_BG_FACTOR(X_AXIS);
  11270. const float gx = constrain(FLOOR(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  11271. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  11272. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  11273. // Beyond the grid maintain height at grid edges
  11274. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  11275. #endif
  11276. gridx = gx;
  11277. nextx = MIN(gridx + 1, ABL_BG_POINTS_X - 1);
  11278. }
  11279. if (last_y != ry || last_gridx != gridx) {
  11280. if (last_y != ry) {
  11281. last_y = ry;
  11282. ratio_y = ry * ABL_BG_FACTOR(Y_AXIS);
  11283. const float gy = constrain(FLOOR(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  11284. ratio_y -= gy;
  11285. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  11286. // Beyond the grid maintain height at grid edges
  11287. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  11288. #endif
  11289. gridy = gy;
  11290. nexty = MIN(gridy + 1, ABL_BG_POINTS_Y - 1);
  11291. }
  11292. if (last_gridx != gridx || last_gridy != gridy) {
  11293. last_gridx = gridx;
  11294. last_gridy = gridy;
  11295. // Z at the box corners
  11296. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  11297. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  11298. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  11299. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  11300. }
  11301. // Bilinear interpolate. Needed since ry or gridx has changed.
  11302. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  11303. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  11304. D = R - L;
  11305. }
  11306. const float offset = L + ratio_x * D; // the offset almost always changes
  11307. /*
  11308. static float last_offset = 0;
  11309. if (ABS(last_offset - offset) > 0.2) {
  11310. SERIAL_ECHOPGM("Sudden Shift at ");
  11311. SERIAL_ECHOPAIR("x=", rx);
  11312. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  11313. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  11314. SERIAL_ECHOPAIR(" y=", ry);
  11315. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  11316. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  11317. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  11318. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  11319. SERIAL_ECHOPAIR(" z1=", z1);
  11320. SERIAL_ECHOPAIR(" z2=", z2);
  11321. SERIAL_ECHOPAIR(" z3=", z3);
  11322. SERIAL_ECHOLNPAIR(" z4=", z4);
  11323. SERIAL_ECHOPAIR(" L=", L);
  11324. SERIAL_ECHOPAIR(" R=", R);
  11325. SERIAL_ECHOLNPAIR(" offset=", offset);
  11326. }
  11327. last_offset = offset;
  11328. //*/
  11329. return offset;
  11330. }
  11331. #endif // AUTO_BED_LEVELING_BILINEAR
  11332. #if ENABLED(DELTA)
  11333. /**
  11334. * Recalculate factors used for delta kinematics whenever
  11335. * settings have been changed (e.g., by M665).
  11336. */
  11337. void recalc_delta_settings() {
  11338. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  11339. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  11340. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (delta_radius + trt[A_AXIS]); // front left tower
  11341. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (delta_radius + trt[A_AXIS]);
  11342. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + trt[B_AXIS]); // front right tower
  11343. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + trt[B_AXIS]);
  11344. delta_tower[C_AXIS][X_AXIS] = cos(RADIANS( 90 + delta_tower_angle_trim[C_AXIS])) * (delta_radius + trt[C_AXIS]); // back middle tower
  11345. delta_tower[C_AXIS][Y_AXIS] = sin(RADIANS( 90 + delta_tower_angle_trim[C_AXIS])) * (delta_radius + trt[C_AXIS]);
  11346. delta_diagonal_rod_2_tower[A_AXIS] = sq(delta_diagonal_rod + drt[A_AXIS]);
  11347. delta_diagonal_rod_2_tower[B_AXIS] = sq(delta_diagonal_rod + drt[B_AXIS]);
  11348. delta_diagonal_rod_2_tower[C_AXIS] = sq(delta_diagonal_rod + drt[C_AXIS]);
  11349. update_software_endstops(Z_AXIS);
  11350. axis_homed = 0;
  11351. }
  11352. /**
  11353. * Delta Inverse Kinematics
  11354. *
  11355. * Calculate the tower positions for a given machine
  11356. * position, storing the result in the delta[] array.
  11357. *
  11358. * This is an expensive calculation, requiring 3 square
  11359. * roots per segmented linear move, and strains the limits
  11360. * of a Mega2560 with a Graphical Display.
  11361. *
  11362. * Suggested optimizations include:
  11363. *
  11364. * - Disable the home_offset (M206) and/or position_shift (G92)
  11365. * features to remove up to 12 float additions.
  11366. */
  11367. #define DELTA_DEBUG(VAR) do { \
  11368. SERIAL_ECHOPAIR("cartesian X:", VAR[X_AXIS]); \
  11369. SERIAL_ECHOPAIR(" Y:", VAR[Y_AXIS]); \
  11370. SERIAL_ECHOLNPAIR(" Z:", VAR[Z_AXIS]); \
  11371. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  11372. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  11373. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  11374. }while(0)
  11375. void inverse_kinematics(const float raw[XYZ]) {
  11376. #if HOTENDS > 1
  11377. // Delta hotend offsets must be applied in Cartesian space with no "spoofing"
  11378. const float pos[XYZ] = {
  11379. raw[X_AXIS] - hotend_offset[X_AXIS][active_extruder],
  11380. raw[Y_AXIS] - hotend_offset[Y_AXIS][active_extruder],
  11381. raw[Z_AXIS]
  11382. };
  11383. DELTA_IK(pos);
  11384. //DELTA_DEBUG(pos);
  11385. #else
  11386. DELTA_IK(raw);
  11387. //DELTA_DEBUG(raw);
  11388. #endif
  11389. }
  11390. /**
  11391. * Calculate the highest Z position where the
  11392. * effector has the full range of XY motion.
  11393. */
  11394. float delta_safe_distance_from_top() {
  11395. float cartesian[XYZ] = { 0, 0, 0 };
  11396. inverse_kinematics(cartesian);
  11397. const float centered_extent = delta[A_AXIS];
  11398. cartesian[Y_AXIS] = DELTA_PRINTABLE_RADIUS;
  11399. inverse_kinematics(cartesian);
  11400. return ABS(centered_extent - delta[A_AXIS]);
  11401. }
  11402. /**
  11403. * Delta Forward Kinematics
  11404. *
  11405. * See the Wikipedia article "Trilateration"
  11406. * https://en.wikipedia.org/wiki/Trilateration
  11407. *
  11408. * Establish a new coordinate system in the plane of the
  11409. * three carriage points. This system has its origin at
  11410. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  11411. * plane with a Z component of zero.
  11412. * We will define unit vectors in this coordinate system
  11413. * in our original coordinate system. Then when we calculate
  11414. * the Xnew, Ynew and Znew values, we can translate back into
  11415. * the original system by moving along those unit vectors
  11416. * by the corresponding values.
  11417. *
  11418. * Variable names matched to Marlin, c-version, and avoid the
  11419. * use of any vector library.
  11420. *
  11421. * by Andreas Hardtung 2016-06-07
  11422. * based on a Java function from "Delta Robot Kinematics V3"
  11423. * by Steve Graves
  11424. *
  11425. * The result is stored in the cartes[] array.
  11426. */
  11427. void forward_kinematics_DELTA(const float &z1, const float &z2, const float &z3) {
  11428. // Create a vector in old coordinates along x axis of new coordinate
  11429. const float p12[] = {
  11430. delta_tower[B_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS],
  11431. delta_tower[B_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS],
  11432. z2 - z1
  11433. },
  11434. // Get the reciprocal of Magnitude of vector.
  11435. d2 = sq(p12[0]) + sq(p12[1]) + sq(p12[2]), inv_d = RSQRT(d2),
  11436. // Create unit vector by multiplying by the inverse of the magnitude.
  11437. ex[3] = { p12[0] * inv_d, p12[1] * inv_d, p12[2] * inv_d },
  11438. // Get the vector from the origin of the new system to the third point.
  11439. p13[3] = {
  11440. delta_tower[C_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS],
  11441. delta_tower[C_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS],
  11442. z3 - z1
  11443. },
  11444. // Use the dot product to find the component of this vector on the X axis.
  11445. i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2],
  11446. // Create a vector along the x axis that represents the x component of p13.
  11447. iex[] = { ex[0] * i, ex[1] * i, ex[2] * i };
  11448. // Subtract the X component from the original vector leaving only Y. We use the
  11449. // variable that will be the unit vector after we scale it.
  11450. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  11451. // The magnitude and the inverse of the magnitude of Y component
  11452. const float j2 = sq(ey[0]) + sq(ey[1]) + sq(ey[2]), inv_j = RSQRT(j2);
  11453. // Convert to a unit vector
  11454. ey[0] *= inv_j; ey[1] *= inv_j; ey[2] *= inv_j;
  11455. // The cross product of the unit x and y is the unit z
  11456. // float[] ez = vectorCrossProd(ex, ey);
  11457. const float ez[3] = {
  11458. ex[1] * ey[2] - ex[2] * ey[1],
  11459. ex[2] * ey[0] - ex[0] * ey[2],
  11460. ex[0] * ey[1] - ex[1] * ey[0]
  11461. },
  11462. // We now have the d, i and j values defined in Wikipedia.
  11463. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  11464. Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + d2) * inv_d * 0.5,
  11465. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + sq(i) + j2) * 0.5 - i * Xnew) * inv_j,
  11466. Znew = SQRT(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  11467. // Start from the origin of the old coordinates and add vectors in the
  11468. // old coords that represent the Xnew, Ynew and Znew to find the point
  11469. // in the old system.
  11470. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  11471. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  11472. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  11473. }
  11474. void forward_kinematics_DELTA(const float (&point)[ABC]) {
  11475. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  11476. }
  11477. #endif // DELTA
  11478. #if ENABLED(HANGPRINTER)
  11479. /**
  11480. * Recalculate factors used for hangprinter kinematics whenever
  11481. * settings have been changed (e.g., by M665).
  11482. */
  11483. void recalc_hangprinter_settings(){
  11484. HANGPRINTER_IK_ORIGIN(line_lengths_origin);
  11485. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  11486. const uint8_t mech_adv_tmp[MOV_AXIS] = MECHANICAL_ADVANTAGE,
  11487. actn_pts_tmp[MOV_AXIS] = ACTION_POINTS;
  11488. const uint16_t m_g_t_tmp[MOV_AXIS] = MOTOR_GEAR_TEETH,
  11489. s_g_t_tmp[MOV_AXIS] = SPOOL_GEAR_TEETH;
  11490. const float mnt_l_tmp[MOV_AXIS] = MOUNTED_LINE;
  11491. float s_r2_tmp[MOV_AXIS] = SPOOL_RADII,
  11492. steps_per_unit_times_r_tmp[MOV_AXIS];
  11493. uint8_t nr_lines_dir_tmp[MOV_AXIS];
  11494. LOOP_MOV_AXIS(i){
  11495. steps_per_unit_times_r_tmp[i] = (float(mech_adv_tmp[i])*STEPS_PER_MOTOR_REVOLUTION*s_g_t_tmp[i])/(2*M_PI*m_g_t_tmp[i]);
  11496. nr_lines_dir_tmp[i] = mech_adv_tmp[i]*actn_pts_tmp[i];
  11497. s_r2_tmp[i] *= s_r2_tmp[i];
  11498. planner.k2[i] = -(float)nr_lines_dir_tmp[i]*SPOOL_BUILDUP_FACTOR;
  11499. planner.k0[i] = 2.0*steps_per_unit_times_r_tmp[i]/planner.k2[i];
  11500. }
  11501. // Assumes spools are mounted near D-anchor in ceiling
  11502. #define HYP3D(x,y,z) SQRT(sq(x) + sq(y) + sq(z))
  11503. float line_on_spool_origin_tmp[MOV_AXIS];
  11504. line_on_spool_origin_tmp[A_AXIS] = actn_pts_tmp[A_AXIS] * mnt_l_tmp[A_AXIS]
  11505. - actn_pts_tmp[A_AXIS] * HYPOT(anchor_A_y, anchor_D_z - anchor_A_z)
  11506. - nr_lines_dir_tmp[A_AXIS] * line_lengths_origin[A_AXIS];
  11507. line_on_spool_origin_tmp[B_AXIS] = actn_pts_tmp[B_AXIS] * mnt_l_tmp[B_AXIS]
  11508. - actn_pts_tmp[B_AXIS] * HYP3D(anchor_B_x, anchor_B_y, anchor_D_z - anchor_B_z)
  11509. - nr_lines_dir_tmp[B_AXIS] * line_lengths_origin[B_AXIS];
  11510. line_on_spool_origin_tmp[C_AXIS] = actn_pts_tmp[C_AXIS] * mnt_l_tmp[C_AXIS]
  11511. - actn_pts_tmp[C_AXIS] * HYP3D(anchor_C_x, anchor_C_y, anchor_D_z - anchor_C_z)
  11512. - nr_lines_dir_tmp[C_AXIS] * line_lengths_origin[C_AXIS];
  11513. line_on_spool_origin_tmp[D_AXIS] = actn_pts_tmp[D_AXIS] * mnt_l_tmp[D_AXIS]
  11514. - nr_lines_dir_tmp[D_AXIS] * line_lengths_origin[D_AXIS];
  11515. LOOP_MOV_AXIS(i) {
  11516. planner.axis_steps_per_mm[i] = steps_per_unit_times_r_tmp[i] /
  11517. SQRT((SPOOL_BUILDUP_FACTOR) * line_on_spool_origin_tmp[i] + s_r2_tmp[i]);
  11518. planner.k1[i] = (SPOOL_BUILDUP_FACTOR) *
  11519. (line_on_spool_origin_tmp[i] + nr_lines_dir_tmp[i] * line_lengths_origin[i]) + s_r2_tmp[i];
  11520. planner.sqrtk1[i] = SQRT(planner.k1[i]);
  11521. }
  11522. planner.axis_steps_per_mm[E_AXIS] = DEFAULT_E_AXIS_STEPS_PER_UNIT;
  11523. #endif // LINE_BUILDUP_COMPENSATION_FEATURE
  11524. SYNC_PLAN_POSITION_KINEMATIC(); // recalcs line lengths in case anchor was moved
  11525. }
  11526. /**
  11527. * Hangprinter inverse kinematics
  11528. */
  11529. void inverse_kinematics(const float raw[XYZ]) {
  11530. HANGPRINTER_IK(raw);
  11531. }
  11532. /**
  11533. * Hangprinter forward kinematics
  11534. * Basic idea is to subtract squared line lengths to get linear equations.
  11535. * Subtracting d*d from a*a, b*b, and c*c gives the cleanest derivation:
  11536. *
  11537. * a*a - d*d = k1 + k2*y + k3*z <---- a line (I)
  11538. * b*b - d*d = k4 + k5*x + k6*y + k7*z <---- a plane (II)
  11539. * c*c - d*d = k8 + k9*x + k10*y + k11*z <---- a plane (III)
  11540. *
  11541. * Use (I) to reduce (II) and (III) into lines. Eliminate y, keep z.
  11542. *
  11543. * (II): b*b - d*d = k12 + k13*x + k14*z
  11544. * <=> x = k0b + k1b*z, <---- a line (IV)
  11545. *
  11546. * (III): c*c - d*d = k15 + k16*x + k17*z
  11547. * <=> x = k0c + k1c*z, <---- a line (V)
  11548. *
  11549. * where k1, k2, ..., k17, k0b, k0c, k1b, and k1c are known constants.
  11550. *
  11551. * These two straight lines are not parallel, so they will cross in exactly one point.
  11552. * Find z by setting (IV) = (V)
  11553. * Find x by inserting z into (V)
  11554. * Find y by inserting z into (I)
  11555. *
  11556. * Warning: truncation errors will typically be in the order of a few tens of microns.
  11557. */
  11558. void forward_kinematics_HANGPRINTER(float a, float b, float c, float d){
  11559. const float Asq = sq(anchor_A_y) + sq(anchor_A_z),
  11560. Bsq = sq(anchor_B_x) + sq(anchor_B_y) + sq(anchor_B_z),
  11561. Csq = sq(anchor_C_x) + sq(anchor_C_y) + sq(anchor_C_z),
  11562. Dsq = sq(anchor_D_z),
  11563. aa = sq(a),
  11564. dd = sq(d),
  11565. k0b = (-sq(b) + Bsq - Dsq + dd) / (2.0 * anchor_B_x) + (anchor_B_y / (2.0 * anchor_A_y * anchor_B_x)) * (Dsq - Asq + aa - dd),
  11566. k0c = (-sq(c) + Csq - Dsq + dd) / (2.0 * anchor_C_x) + (anchor_C_y / (2.0 * anchor_A_y * anchor_C_x)) * (Dsq - Asq + aa - dd),
  11567. k1b = (anchor_B_y * (anchor_A_z - anchor_D_z)) / (anchor_A_y * anchor_B_x) + (anchor_D_z - anchor_B_z) / anchor_B_x,
  11568. k1c = (anchor_C_y * (anchor_A_z - anchor_D_z)) / (anchor_A_y * anchor_C_x) + (anchor_D_z - anchor_C_z) / anchor_C_x;
  11569. cartes[Z_AXIS] = (k0b - k0c) / (k1c - k1b);
  11570. cartes[X_AXIS] = k0c + k1c * cartes[Z_AXIS];
  11571. cartes[Y_AXIS] = (Asq - Dsq - aa + dd) / (2.0 * anchor_A_y) + ((anchor_D_z - anchor_A_z) / anchor_A_y) * cartes[Z_AXIS];
  11572. }
  11573. #endif // HANGPRINTER
  11574. /**
  11575. * Get the stepper positions in the cartes[] array.
  11576. * Forward kinematics are applied for DELTA and SCARA.
  11577. *
  11578. * The result is in the current coordinate space with
  11579. * leveling applied. The coordinates need to be run through
  11580. * unapply_leveling to obtain machine coordinates suitable
  11581. * for current_position, etc.
  11582. */
  11583. void get_cartesian_from_steppers() {
  11584. #if ENABLED(DELTA)
  11585. forward_kinematics_DELTA(
  11586. planner.get_axis_position_mm(A_AXIS),
  11587. planner.get_axis_position_mm(B_AXIS),
  11588. planner.get_axis_position_mm(C_AXIS)
  11589. );
  11590. #elif ENABLED(HANGPRINTER)
  11591. forward_kinematics_HANGPRINTER(
  11592. planner.get_axis_position_mm(A_AXIS),
  11593. planner.get_axis_position_mm(B_AXIS),
  11594. planner.get_axis_position_mm(C_AXIS),
  11595. planner.get_axis_position_mm(D_AXIS)
  11596. );
  11597. #else
  11598. #if IS_SCARA
  11599. forward_kinematics_SCARA(
  11600. planner.get_axis_position_degrees(A_AXIS),
  11601. planner.get_axis_position_degrees(B_AXIS)
  11602. );
  11603. #else
  11604. cartes[X_AXIS] = planner.get_axis_position_mm(X_AXIS);
  11605. cartes[Y_AXIS] = planner.get_axis_position_mm(Y_AXIS);
  11606. #endif
  11607. cartes[Z_AXIS] = planner.get_axis_position_mm(Z_AXIS);
  11608. #endif
  11609. }
  11610. /**
  11611. * Set the current_position for an axis based on
  11612. * the stepper positions, removing any leveling that
  11613. * may have been applied.
  11614. *
  11615. * To prevent small shifts in axis position always call
  11616. * SYNC_PLAN_POSITION_KINEMATIC after updating axes with this.
  11617. *
  11618. * To keep hosts in sync, always call report_current_position
  11619. * after updating the current_position.
  11620. */
  11621. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  11622. get_cartesian_from_steppers();
  11623. #if PLANNER_LEVELING
  11624. planner.unapply_leveling(cartes);
  11625. #endif
  11626. if (axis == ALL_AXES)
  11627. COPY(current_position, cartes);
  11628. else
  11629. current_position[axis] = cartes[axis];
  11630. }
  11631. #if IS_CARTESIAN
  11632. #if ENABLED(SEGMENT_LEVELED_MOVES)
  11633. /**
  11634. * Prepare a segmented move on a CARTESIAN setup.
  11635. *
  11636. * This calls planner.buffer_line several times, adding
  11637. * small incremental moves. This allows the planner to
  11638. * apply more detailed bed leveling to the full move.
  11639. */
  11640. inline void segmented_line_to_destination(const float &fr_mm_s, const float segment_size=LEVELED_SEGMENT_LENGTH) {
  11641. const float xdiff = destination[X_AXIS] - current_position[X_AXIS],
  11642. ydiff = destination[Y_AXIS] - current_position[Y_AXIS];
  11643. // If the move is only in Z/E don't split up the move
  11644. if (!xdiff && !ydiff) {
  11645. planner.buffer_line_kinematic(destination, fr_mm_s, active_extruder);
  11646. return;
  11647. }
  11648. // Remaining cartesian distances
  11649. const float zdiff = destination[Z_AXIS] - current_position[Z_AXIS],
  11650. ediff = destination[E_CART] - current_position[E_CART];
  11651. // Get the linear distance in XYZ
  11652. // If the move is very short, check the E move distance
  11653. // No E move either? Game over.
  11654. float cartesian_mm = SQRT(sq(xdiff) + sq(ydiff) + sq(zdiff));
  11655. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(ediff);
  11656. if (UNEAR_ZERO(cartesian_mm)) return;
  11657. // The length divided by the segment size
  11658. // At least one segment is required
  11659. uint16_t segments = cartesian_mm / segment_size;
  11660. NOLESS(segments, 1);
  11661. // The approximate length of each segment
  11662. const float inv_segments = 1.0f / float(segments),
  11663. cartesian_segment_mm = cartesian_mm * inv_segments,
  11664. segment_distance[XYZE] = {
  11665. xdiff * inv_segments,
  11666. ydiff * inv_segments,
  11667. zdiff * inv_segments,
  11668. ediff * inv_segments
  11669. };
  11670. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  11671. // SERIAL_ECHOLNPAIR(" segments=", segments);
  11672. // SERIAL_ECHOLNPAIR(" segment_mm=", cartesian_segment_mm);
  11673. // Get the raw current position as starting point
  11674. float raw[XYZE];
  11675. COPY(raw, current_position);
  11676. // Calculate and execute the segments
  11677. while (--segments) {
  11678. static millis_t next_idle_ms = millis() + 200UL;
  11679. thermalManager.manage_heater(); // This returns immediately if not really needed.
  11680. if (ELAPSED(millis(), next_idle_ms)) {
  11681. next_idle_ms = millis() + 200UL;
  11682. idle();
  11683. }
  11684. LOOP_XYZE(i) raw[i] += segment_distance[i];
  11685. if (!planner.buffer_line_kinematic(raw, fr_mm_s, active_extruder, cartesian_segment_mm))
  11686. break;
  11687. }
  11688. // Since segment_distance is only approximate,
  11689. // the final move must be to the exact destination.
  11690. planner.buffer_line_kinematic(destination, fr_mm_s, active_extruder, cartesian_segment_mm);
  11691. }
  11692. #elif ENABLED(MESH_BED_LEVELING)
  11693. /**
  11694. * Prepare a mesh-leveled linear move in a Cartesian setup,
  11695. * splitting the move where it crosses mesh borders.
  11696. */
  11697. void mesh_line_to_destination(const float fr_mm_s, uint8_t x_splits=0xFF, uint8_t y_splits=0xFF) {
  11698. // Get current and destination cells for this line
  11699. int cx1 = mbl.cell_index_x(current_position[X_AXIS]),
  11700. cy1 = mbl.cell_index_y(current_position[Y_AXIS]),
  11701. cx2 = mbl.cell_index_x(destination[X_AXIS]),
  11702. cy2 = mbl.cell_index_y(destination[Y_AXIS]);
  11703. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  11704. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  11705. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  11706. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  11707. // Start and end in the same cell? No split needed.
  11708. if (cx1 == cx2 && cy1 == cy2) {
  11709. buffer_line_to_destination(fr_mm_s);
  11710. set_current_from_destination();
  11711. return;
  11712. }
  11713. #define MBL_SEGMENT_END(A) (current_position[_AXIS(A)] + (destination[_AXIS(A)] - current_position[_AXIS(A)]) * normalized_dist)
  11714. #define MBL_SEGMENT_END_E (current_position[E_CART] + (destination[E_CART] - current_position[E_CART]) * normalized_dist)
  11715. float normalized_dist, end[XYZE];
  11716. const int8_t gcx = MAX(cx1, cx2), gcy = MAX(cy1, cy2);
  11717. // Crosses on the X and not already split on this X?
  11718. // The x_splits flags are insurance against rounding errors.
  11719. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  11720. // Split on the X grid line
  11721. CBI(x_splits, gcx);
  11722. COPY(end, destination);
  11723. destination[X_AXIS] = mbl.index_to_xpos[gcx];
  11724. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  11725. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  11726. }
  11727. // Crosses on the Y and not already split on this Y?
  11728. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  11729. // Split on the Y grid line
  11730. CBI(y_splits, gcy);
  11731. COPY(end, destination);
  11732. destination[Y_AXIS] = mbl.index_to_ypos[gcy];
  11733. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  11734. destination[X_AXIS] = MBL_SEGMENT_END(X);
  11735. }
  11736. else {
  11737. // Must already have been split on these border(s)
  11738. buffer_line_to_destination(fr_mm_s);
  11739. set_current_from_destination();
  11740. return;
  11741. }
  11742. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  11743. destination[E_CART] = MBL_SEGMENT_END_E;
  11744. // Do the split and look for more borders
  11745. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  11746. // Restore destination from stack
  11747. COPY(destination, end);
  11748. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  11749. }
  11750. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  11751. #define CELL_INDEX(A,V) ((V - bilinear_start[_AXIS(A)]) * ABL_BG_FACTOR(_AXIS(A)))
  11752. /**
  11753. * Prepare a bilinear-leveled linear move on Cartesian,
  11754. * splitting the move where it crosses grid borders.
  11755. */
  11756. void bilinear_line_to_destination(const float fr_mm_s, uint16_t x_splits=0xFFFF, uint16_t y_splits=0xFFFF) {
  11757. // Get current and destination cells for this line
  11758. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  11759. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  11760. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  11761. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  11762. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  11763. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  11764. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  11765. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  11766. // Start and end in the same cell? No split needed.
  11767. if (cx1 == cx2 && cy1 == cy2) {
  11768. buffer_line_to_destination(fr_mm_s);
  11769. set_current_from_destination();
  11770. return;
  11771. }
  11772. #define LINE_SEGMENT_END(A) (current_position[_AXIS(A)] + (destination[_AXIS(A)] - current_position[_AXIS(A)]) * normalized_dist)
  11773. #define LINE_SEGMENT_END_E (current_position[E_CART] + (destination[E_CART] - current_position[E_CART]) * normalized_dist)
  11774. float normalized_dist, end[XYZE];
  11775. const int8_t gcx = MAX(cx1, cx2), gcy = MAX(cy1, cy2);
  11776. // Crosses on the X and not already split on this X?
  11777. // The x_splits flags are insurance against rounding errors.
  11778. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  11779. // Split on the X grid line
  11780. CBI(x_splits, gcx);
  11781. COPY(end, destination);
  11782. destination[X_AXIS] = bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx;
  11783. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  11784. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  11785. }
  11786. // Crosses on the Y and not already split on this Y?
  11787. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  11788. // Split on the Y grid line
  11789. CBI(y_splits, gcy);
  11790. COPY(end, destination);
  11791. destination[Y_AXIS] = bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy;
  11792. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  11793. destination[X_AXIS] = LINE_SEGMENT_END(X);
  11794. }
  11795. else {
  11796. // Must already have been split on these border(s)
  11797. buffer_line_to_destination(fr_mm_s);
  11798. set_current_from_destination();
  11799. return;
  11800. }
  11801. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  11802. destination[E_CART] = LINE_SEGMENT_END_E;
  11803. // Do the split and look for more borders
  11804. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  11805. // Restore destination from stack
  11806. COPY(destination, end);
  11807. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  11808. }
  11809. #endif // AUTO_BED_LEVELING_BILINEAR
  11810. #endif // IS_CARTESIAN
  11811. #if !UBL_SEGMENTED
  11812. #if IS_KINEMATIC
  11813. #if IS_SCARA
  11814. /**
  11815. * Before raising this value, use M665 S[seg_per_sec] to decrease
  11816. * the number of segments-per-second. Default is 200. Some deltas
  11817. * do better with 160 or lower. It would be good to know how many
  11818. * segments-per-second are actually possible for SCARA on AVR.
  11819. *
  11820. * Longer segments result in less kinematic overhead
  11821. * but may produce jagged lines. Try 0.5mm, 1.0mm, and 2.0mm
  11822. * and compare the difference.
  11823. */
  11824. #define SCARA_MIN_SEGMENT_LENGTH 0.5f
  11825. #endif
  11826. /**
  11827. * Prepare a linear move in a DELTA, SCARA or HANGPRINTER setup.
  11828. *
  11829. * This calls planner.buffer_line several times, adding
  11830. * small incremental moves for DELTA, SCARA or HANGPRINTER.
  11831. *
  11832. * For Unified Bed Leveling (Delta or Segmented Cartesian)
  11833. * the ubl.prepare_segmented_line_to method replaces this.
  11834. */
  11835. inline bool prepare_kinematic_move_to(const float (&rtarget)[XYZE]) {
  11836. // Get the top feedrate of the move in the XY plane
  11837. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  11838. const float xdiff = rtarget[X_AXIS] - current_position[X_AXIS],
  11839. ydiff = rtarget[Y_AXIS] - current_position[Y_AXIS]
  11840. #if ENABLED(HANGPRINTER)
  11841. , zdiff = rtarget[Z_AXIS] - current_position[Z_AXIS]
  11842. #endif
  11843. ;
  11844. // If the move is only in Z/E (for Hangprinter only in E) don't split up the move
  11845. if (!xdiff && !ydiff
  11846. #if ENABLED(HANGPRINTER)
  11847. && !zdiff
  11848. #endif
  11849. ) {
  11850. planner.buffer_line_kinematic(rtarget, _feedrate_mm_s, active_extruder);
  11851. return false; // caller will update current_position
  11852. }
  11853. // Fail if attempting move outside printable radius
  11854. if (!position_is_reachable(rtarget[X_AXIS], rtarget[Y_AXIS])) return true;
  11855. // Remaining cartesian distances
  11856. const float
  11857. #if DISABLED(HANGPRINTER)
  11858. zdiff = rtarget[Z_AXIS] - current_position[Z_AXIS],
  11859. #endif
  11860. ediff = rtarget[E_CART] - current_position[E_CART];
  11861. // Get the linear distance in XYZ
  11862. // If the move is very short, check the E move distance
  11863. // No E move either? Game over.
  11864. float cartesian_mm = SQRT(sq(xdiff) + sq(ydiff) + sq(zdiff));
  11865. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(ediff);
  11866. if (UNEAR_ZERO(cartesian_mm)) return true;
  11867. // Minimum number of seconds to move the given distance
  11868. const float seconds = cartesian_mm / _feedrate_mm_s;
  11869. // The number of segments-per-second times the duration
  11870. // gives the number of segments
  11871. uint16_t segments = delta_segments_per_second * seconds;
  11872. // For SCARA enforce a minimum segment size
  11873. #if IS_SCARA
  11874. NOMORE(segments, cartesian_mm * (1.0f / float(SCARA_MIN_SEGMENT_LENGTH)));
  11875. #endif
  11876. // At least one segment is required
  11877. NOLESS(segments, 1);
  11878. // The approximate length of each segment
  11879. const float inv_segments = 1.0f / float(segments),
  11880. segment_distance[XYZE] = {
  11881. xdiff * inv_segments,
  11882. ydiff * inv_segments,
  11883. zdiff * inv_segments,
  11884. ediff * inv_segments
  11885. };
  11886. #if !HAS_FEEDRATE_SCALING
  11887. const float cartesian_segment_mm = cartesian_mm * inv_segments;
  11888. #endif
  11889. /*
  11890. SERIAL_ECHOPAIR("mm=", cartesian_mm);
  11891. SERIAL_ECHOPAIR(" seconds=", seconds);
  11892. SERIAL_ECHOPAIR(" segments=", segments);
  11893. #if !HAS_FEEDRATE_SCALING
  11894. SERIAL_ECHOPAIR(" segment_mm=", cartesian_segment_mm);
  11895. #endif
  11896. SERIAL_EOL();
  11897. //*/
  11898. #if HAS_FEEDRATE_SCALING
  11899. // SCARA needs to scale the feed rate from mm/s to degrees/s
  11900. // i.e., Complete the angular vector in the given time.
  11901. const float segment_length = cartesian_mm * inv_segments,
  11902. inv_segment_length = 1.0f / segment_length, // 1/mm/segs
  11903. inverse_secs = inv_segment_length * _feedrate_mm_s;
  11904. float oldA = planner.position_float[A_AXIS],
  11905. oldB = planner.position_float[B_AXIS]
  11906. #if ENABLED(DELTA_FEEDRATE_SCALING)
  11907. , oldC = planner.position_float[C_AXIS]
  11908. #endif
  11909. ;
  11910. /*
  11911. SERIAL_ECHOPGM("Scaled kinematic move: ");
  11912. SERIAL_ECHOPAIR(" segment_length (inv)=", segment_length);
  11913. SERIAL_ECHOPAIR(" (", inv_segment_length);
  11914. SERIAL_ECHOPAIR(") _feedrate_mm_s=", _feedrate_mm_s);
  11915. SERIAL_ECHOPAIR(" inverse_secs=", inverse_secs);
  11916. SERIAL_ECHOPAIR(" oldA=", oldA);
  11917. SERIAL_ECHOPAIR(" oldB=", oldB);
  11918. #if ENABLED(DELTA_FEEDRATE_SCALING)
  11919. SERIAL_ECHOPAIR(" oldC=", oldC);
  11920. #endif
  11921. SERIAL_EOL();
  11922. safe_delay(5);
  11923. //*/
  11924. #endif
  11925. // Get the current position as starting point
  11926. float raw[XYZE];
  11927. COPY(raw, current_position);
  11928. // Calculate and execute the segments
  11929. while (--segments) {
  11930. static millis_t next_idle_ms = millis() + 200UL;
  11931. thermalManager.manage_heater(); // This returns immediately if not really needed.
  11932. if (ELAPSED(millis(), next_idle_ms)) {
  11933. next_idle_ms = millis() + 200UL;
  11934. idle();
  11935. }
  11936. LOOP_XYZE(i) raw[i] += segment_distance[i];
  11937. #if ENABLED(DELTA) && HOTENDS < 2
  11938. DELTA_IK(raw); // Delta can inline its kinematics
  11939. #elif ENABLED(HANGPRINTER)
  11940. HANGPRINTER_IK(raw); // Modifies line_lengths[ABCD]
  11941. #else
  11942. inverse_kinematics(raw);
  11943. #endif
  11944. ADJUST_DELTA(raw); // Adjust Z if bed leveling is enabled
  11945. #if ENABLED(SCARA_FEEDRATE_SCALING)
  11946. // For SCARA scale the feed rate from mm/s to degrees/s
  11947. // i.e., Complete the angular vector in the given time.
  11948. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], raw[Z_AXIS], raw[E_CART], HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs, active_extruder, segment_length))
  11949. break;
  11950. /*
  11951. SERIAL_ECHO(segments);
  11952. SERIAL_ECHOPAIR(": X=", raw[X_AXIS]); SERIAL_ECHOPAIR(" Y=", raw[Y_AXIS]);
  11953. SERIAL_ECHOPAIR(" A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]);
  11954. SERIAL_ECHOLNPAIR(" F", HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs * 60);
  11955. safe_delay(5);
  11956. //*/
  11957. oldA = delta[A_AXIS]; oldB = delta[B_AXIS];
  11958. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  11959. // For DELTA scale the feed rate from Effector mm/s to Carriage mm/s
  11960. // i.e., Complete the linear vector in the given time.
  11961. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS], SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs, active_extruder, segment_length))
  11962. break;
  11963. /*
  11964. SERIAL_ECHO(segments);
  11965. SERIAL_ECHOPAIR(": X=", raw[X_AXIS]); SERIAL_ECHOPAIR(" Y=", raw[Y_AXIS]);
  11966. SERIAL_ECHOPAIR(" A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" C=", delta[C_AXIS]);
  11967. SERIAL_ECHOLNPAIR(" F", SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs * 60);
  11968. safe_delay(5);
  11969. //*/
  11970. oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; oldC = delta[C_AXIS];
  11971. #elif ENABLED(HANGPRINTER)
  11972. if (!planner.buffer_line(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], raw[E_CART], _feedrate_mm_s, active_extruder, cartesian_segment_mm))
  11973. break;
  11974. #else
  11975. if (!planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_CART], _feedrate_mm_s, active_extruder, cartesian_segment_mm))
  11976. break;
  11977. #endif
  11978. }
  11979. // Ensure last segment arrives at target location.
  11980. #if HAS_FEEDRATE_SCALING
  11981. inverse_kinematics(rtarget);
  11982. ADJUST_DELTA(rtarget);
  11983. #endif
  11984. #if ENABLED(SCARA_FEEDRATE_SCALING)
  11985. const float diff2 = HYPOT2(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB);
  11986. if (diff2) {
  11987. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], rtarget[Z_AXIS], rtarget[E_CART], SQRT(diff2) * inverse_secs, active_extruder, segment_length);
  11988. /*
  11989. SERIAL_ECHOPAIR("final: A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]);
  11990. SERIAL_ECHOPAIR(" adiff=", delta[A_AXIS] - oldA); SERIAL_ECHOPAIR(" bdiff=", delta[B_AXIS] - oldB);
  11991. SERIAL_ECHOLNPAIR(" F", SQRT(diff2) * inverse_secs * 60);
  11992. SERIAL_EOL();
  11993. safe_delay(5);
  11994. //*/
  11995. }
  11996. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  11997. const float diff2 = sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC);
  11998. if (diff2) {
  11999. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], rtarget[E_AXIS], SQRT(diff2) * inverse_secs, active_extruder, segment_length);
  12000. /*
  12001. SERIAL_ECHOPAIR("final: A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" C=", delta[C_AXIS]);
  12002. SERIAL_ECHOPAIR(" adiff=", delta[A_AXIS] - oldA); SERIAL_ECHOPAIR(" bdiff=", delta[B_AXIS] - oldB); SERIAL_ECHOPAIR(" cdiff=", delta[C_AXIS] - oldC);
  12003. SERIAL_ECHOLNPAIR(" F", SQRT(diff2) * inverse_secs * 60);
  12004. SERIAL_EOL();
  12005. safe_delay(5);
  12006. //*/
  12007. }
  12008. #else
  12009. planner.buffer_line_kinematic(rtarget, _feedrate_mm_s, active_extruder, cartesian_segment_mm);
  12010. #endif
  12011. return false; // caller will update current_position
  12012. }
  12013. #else // !IS_KINEMATIC
  12014. /**
  12015. * Prepare a linear move in a Cartesian setup.
  12016. *
  12017. * When a mesh-based leveling system is active, moves are segmented
  12018. * according to the configuration of the leveling system.
  12019. *
  12020. * Returns true if current_position[] was set to destination[]
  12021. */
  12022. inline bool prepare_move_to_destination_cartesian() {
  12023. #if HAS_MESH
  12024. if (planner.leveling_active && planner.leveling_active_at_z(destination[Z_AXIS])) {
  12025. #if ENABLED(AUTO_BED_LEVELING_UBL)
  12026. ubl.line_to_destination_cartesian(MMS_SCALED(feedrate_mm_s), active_extruder); // UBL's motion routine needs to know about
  12027. return true; // all moves, including Z-only moves.
  12028. #elif ENABLED(SEGMENT_LEVELED_MOVES)
  12029. segmented_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12030. return false; // caller will update current_position
  12031. #else
  12032. /**
  12033. * For MBL and ABL-BILINEAR only segment moves when X or Y are involved.
  12034. * Otherwise fall through to do a direct single move.
  12035. */
  12036. if (current_position[X_AXIS] != destination[X_AXIS] || current_position[Y_AXIS] != destination[Y_AXIS]) {
  12037. #if ENABLED(MESH_BED_LEVELING)
  12038. mesh_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12039. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  12040. bilinear_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12041. #endif
  12042. return true;
  12043. }
  12044. #endif
  12045. }
  12046. #endif // HAS_MESH
  12047. buffer_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12048. return false; // caller will update current_position
  12049. }
  12050. #endif // !IS_KINEMATIC
  12051. #endif // !UBL_SEGMENTED
  12052. #if ENABLED(DUAL_X_CARRIAGE)
  12053. /**
  12054. * Unpark the carriage, if needed
  12055. */
  12056. inline bool dual_x_carriage_unpark() {
  12057. if (active_extruder_parked)
  12058. switch (dual_x_carriage_mode) {
  12059. case DXC_FULL_CONTROL_MODE: break;
  12060. case DXC_AUTO_PARK_MODE:
  12061. if (current_position[E_CART] == destination[E_CART]) {
  12062. // This is a travel move (with no extrusion)
  12063. // Skip it, but keep track of the current position
  12064. // (so it can be used as the start of the next non-travel move)
  12065. if (delayed_move_time != 0xFFFFFFFFUL) {
  12066. set_current_from_destination();
  12067. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  12068. delayed_move_time = millis();
  12069. return true;
  12070. }
  12071. }
  12072. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  12073. for (uint8_t i = 0; i < 3; i++)
  12074. if (!planner.buffer_line(
  12075. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  12076. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  12077. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  12078. current_position[E_CART],
  12079. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  12080. active_extruder)
  12081. ) break;
  12082. delayed_move_time = 0;
  12083. active_extruder_parked = false;
  12084. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12085. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  12086. #endif
  12087. break;
  12088. case DXC_DUPLICATION_MODE:
  12089. if (active_extruder == 0) {
  12090. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12091. if (DEBUGGING(LEVELING)) {
  12092. SERIAL_ECHOPAIR("Set planner X", inactive_extruder_x_pos);
  12093. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  12094. }
  12095. #endif
  12096. // move duplicate extruder into correct duplication position.
  12097. planner.set_position_mm(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART]);
  12098. if (!planner.buffer_line(
  12099. current_position[X_AXIS] + duplicate_extruder_x_offset,
  12100. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART],
  12101. planner.max_feedrate_mm_s[X_AXIS], 1)
  12102. ) break;
  12103. planner.synchronize();
  12104. SYNC_PLAN_POSITION_KINEMATIC();
  12105. extruder_duplication_enabled = true;
  12106. active_extruder_parked = false;
  12107. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12108. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  12109. #endif
  12110. }
  12111. else {
  12112. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12113. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  12114. #endif
  12115. }
  12116. break;
  12117. }
  12118. return false;
  12119. }
  12120. #endif // DUAL_X_CARRIAGE
  12121. /**
  12122. * Prepare a single move and get ready for the next one
  12123. *
  12124. * This may result in several calls to planner.buffer_line to
  12125. * do smaller moves for DELTA, SCARA, HANGPRINTER, mesh moves, etc.
  12126. *
  12127. * Make sure current_position[E] and destination[E] are good
  12128. * before calling or cold/lengthy extrusion may get missed.
  12129. */
  12130. void prepare_move_to_destination() {
  12131. clamp_to_software_endstops(destination);
  12132. #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE)
  12133. if (!DEBUGGING(DRYRUN)) {
  12134. if (destination[E_CART] != current_position[E_CART]) {
  12135. #if ENABLED(PREVENT_COLD_EXTRUSION)
  12136. if (thermalManager.tooColdToExtrude(active_extruder)) {
  12137. current_position[E_CART] = destination[E_CART]; // Behave as if the move really took place, but ignore E part
  12138. SERIAL_ECHO_START();
  12139. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  12140. }
  12141. #endif // PREVENT_COLD_EXTRUSION
  12142. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  12143. if (ABS(destination[E_CART] - current_position[E_CART]) * planner.e_factor[active_extruder] > (EXTRUDE_MAXLENGTH)) {
  12144. current_position[E_CART] = destination[E_CART]; // Behave as if the move really took place, but ignore E part
  12145. SERIAL_ECHO_START();
  12146. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  12147. }
  12148. #endif // PREVENT_LENGTHY_EXTRUDE
  12149. }
  12150. }
  12151. #endif
  12152. #if ENABLED(DUAL_X_CARRIAGE)
  12153. if (dual_x_carriage_unpark()) return;
  12154. #endif
  12155. if (
  12156. #if UBL_SEGMENTED
  12157. ubl.prepare_segmented_line_to(destination, MMS_SCALED(feedrate_mm_s))
  12158. #elif IS_KINEMATIC
  12159. prepare_kinematic_move_to(destination)
  12160. #else
  12161. prepare_move_to_destination_cartesian()
  12162. #endif
  12163. ) return;
  12164. set_current_from_destination();
  12165. }
  12166. #if ENABLED(ARC_SUPPORT)
  12167. #if N_ARC_CORRECTION < 1
  12168. #undef N_ARC_CORRECTION
  12169. #define N_ARC_CORRECTION 1
  12170. #endif
  12171. /**
  12172. * Plan an arc in 2 dimensions
  12173. *
  12174. * The arc is approximated by generating many small linear segments.
  12175. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  12176. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  12177. * larger segments will tend to be more efficient. Your slicer should have
  12178. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  12179. */
  12180. void plan_arc(
  12181. const float (&cart)[XYZE], // Destination position
  12182. const float (&offset)[2], // Center of rotation relative to current_position
  12183. const bool clockwise // Clockwise?
  12184. ) {
  12185. #if ENABLED(CNC_WORKSPACE_PLANES)
  12186. AxisEnum p_axis, q_axis, l_axis;
  12187. switch (workspace_plane) {
  12188. default:
  12189. case PLANE_XY: p_axis = X_AXIS; q_axis = Y_AXIS; l_axis = Z_AXIS; break;
  12190. case PLANE_ZX: p_axis = Z_AXIS; q_axis = X_AXIS; l_axis = Y_AXIS; break;
  12191. case PLANE_YZ: p_axis = Y_AXIS; q_axis = Z_AXIS; l_axis = X_AXIS; break;
  12192. }
  12193. #else
  12194. constexpr AxisEnum p_axis = X_AXIS, q_axis = Y_AXIS, l_axis = Z_AXIS;
  12195. #endif
  12196. // Radius vector from center to current location
  12197. float r_P = -offset[0], r_Q = -offset[1];
  12198. const float radius = HYPOT(r_P, r_Q),
  12199. center_P = current_position[p_axis] - r_P,
  12200. center_Q = current_position[q_axis] - r_Q,
  12201. rt_X = cart[p_axis] - center_P,
  12202. rt_Y = cart[q_axis] - center_Q,
  12203. linear_travel = cart[l_axis] - current_position[l_axis],
  12204. extruder_travel = cart[E_CART] - current_position[E_CART];
  12205. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  12206. float angular_travel = ATAN2(r_P * rt_Y - r_Q * rt_X, r_P * rt_X + r_Q * rt_Y);
  12207. if (angular_travel < 0) angular_travel += RADIANS(360);
  12208. if (clockwise) angular_travel -= RADIANS(360);
  12209. // Make a circle if the angular rotation is 0 and the target is current position
  12210. if (angular_travel == 0 && current_position[p_axis] == cart[p_axis] && current_position[q_axis] == cart[q_axis])
  12211. angular_travel = RADIANS(360);
  12212. const float flat_mm = radius * angular_travel,
  12213. mm_of_travel = linear_travel ? HYPOT(flat_mm, linear_travel) : ABS(flat_mm);
  12214. if (mm_of_travel < 0.001f) return;
  12215. uint16_t segments = FLOOR(mm_of_travel / (MM_PER_ARC_SEGMENT));
  12216. NOLESS(segments, 1);
  12217. /**
  12218. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  12219. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  12220. * r_T = [cos(phi) -sin(phi);
  12221. * sin(phi) cos(phi)] * r ;
  12222. *
  12223. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  12224. * defined from the circle center to the initial position. Each line segment is formed by successive
  12225. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  12226. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  12227. * all double numbers are single precision on the Arduino. (True double precision will not have
  12228. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  12229. * tool precision in some cases. Therefore, arc path correction is implemented.
  12230. *
  12231. * Small angle approximation may be used to reduce computation overhead further. This approximation
  12232. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  12233. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  12234. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  12235. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  12236. * issue for CNC machines with the single precision Arduino calculations.
  12237. *
  12238. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  12239. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  12240. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  12241. * This is important when there are successive arc motions.
  12242. */
  12243. // Vector rotation matrix values
  12244. float raw[XYZE];
  12245. const float theta_per_segment = angular_travel / segments,
  12246. linear_per_segment = linear_travel / segments,
  12247. extruder_per_segment = extruder_travel / segments,
  12248. sin_T = theta_per_segment,
  12249. cos_T = 1 - 0.5f * sq(theta_per_segment); // Small angle approximation
  12250. // Initialize the linear axis
  12251. raw[l_axis] = current_position[l_axis];
  12252. // Initialize the extruder axis
  12253. raw[E_CART] = current_position[E_CART];
  12254. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  12255. millis_t next_idle_ms = millis() + 200UL;
  12256. #if HAS_FEEDRATE_SCALING
  12257. // SCARA needs to scale the feed rate from mm/s to degrees/s
  12258. const float inv_segment_length = 1.0f / (MM_PER_ARC_SEGMENT),
  12259. inverse_secs = inv_segment_length * fr_mm_s;
  12260. float oldA = planner.position_float[A_AXIS],
  12261. oldB = planner.position_float[B_AXIS]
  12262. #if ENABLED(DELTA_FEEDRATE_SCALING)
  12263. , oldC = planner.position_float[C_AXIS]
  12264. #endif
  12265. ;
  12266. #endif
  12267. #if N_ARC_CORRECTION > 1
  12268. int8_t arc_recalc_count = N_ARC_CORRECTION;
  12269. #endif
  12270. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  12271. thermalManager.manage_heater();
  12272. if (ELAPSED(millis(), next_idle_ms)) {
  12273. next_idle_ms = millis() + 200UL;
  12274. idle();
  12275. }
  12276. #if N_ARC_CORRECTION > 1
  12277. if (--arc_recalc_count) {
  12278. // Apply vector rotation matrix to previous r_P / 1
  12279. const float r_new_Y = r_P * sin_T + r_Q * cos_T;
  12280. r_P = r_P * cos_T - r_Q * sin_T;
  12281. r_Q = r_new_Y;
  12282. }
  12283. else
  12284. #endif
  12285. {
  12286. #if N_ARC_CORRECTION > 1
  12287. arc_recalc_count = N_ARC_CORRECTION;
  12288. #endif
  12289. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  12290. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  12291. // To reduce stuttering, the sin and cos could be computed at different times.
  12292. // For now, compute both at the same time.
  12293. const float cos_Ti = cos(i * theta_per_segment), sin_Ti = sin(i * theta_per_segment);
  12294. r_P = -offset[0] * cos_Ti + offset[1] * sin_Ti;
  12295. r_Q = -offset[0] * sin_Ti - offset[1] * cos_Ti;
  12296. }
  12297. // Update raw location
  12298. raw[p_axis] = center_P + r_P;
  12299. raw[q_axis] = center_Q + r_Q;
  12300. raw[l_axis] += linear_per_segment;
  12301. raw[E_CART] += extruder_per_segment;
  12302. clamp_to_software_endstops(raw);
  12303. #if HAS_FEEDRATE_SCALING
  12304. inverse_kinematics(raw);
  12305. ADJUST_DELTA(raw);
  12306. #endif
  12307. #if ENABLED(SCARA_FEEDRATE_SCALING)
  12308. // For SCARA scale the feed rate from mm/s to degrees/s
  12309. // i.e., Complete the angular vector in the given time.
  12310. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], raw[Z_AXIS], raw[E_CART], HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT))
  12311. break;
  12312. oldA = delta[A_AXIS]; oldB = delta[B_AXIS];
  12313. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  12314. // For DELTA scale the feed rate from Effector mm/s to Carriage mm/s
  12315. // i.e., Complete the linear vector in the given time.
  12316. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS], SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT))
  12317. break;
  12318. oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; oldC = delta[C_AXIS];
  12319. #elif HAS_UBL_AND_CURVES
  12320. float pos[XYZ] = { raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS] };
  12321. planner.apply_leveling(pos);
  12322. if (!planner.buffer_segment(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], raw[E_CART], fr_mm_s, active_extruder, MM_PER_ARC_SEGMENT))
  12323. break;
  12324. #else
  12325. if (!planner.buffer_line_kinematic(raw, fr_mm_s, active_extruder))
  12326. break;
  12327. #endif
  12328. }
  12329. // Ensure last segment arrives at target location.
  12330. #if HAS_FEEDRATE_SCALING
  12331. inverse_kinematics(cart);
  12332. ADJUST_DELTA(cart);
  12333. #endif
  12334. #if ENABLED(SCARA_FEEDRATE_SCALING)
  12335. const float diff2 = HYPOT2(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB);
  12336. if (diff2)
  12337. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], cart[Z_AXIS], cart[E_CART], SQRT(diff2) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT);
  12338. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  12339. const float diff2 = sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC);
  12340. if (diff2)
  12341. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], cart[E_CART], SQRT(diff2) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT);
  12342. #elif HAS_UBL_AND_CURVES
  12343. float pos[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
  12344. planner.apply_leveling(pos);
  12345. planner.buffer_segment(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], cart[E_CART], fr_mm_s, active_extruder, MM_PER_ARC_SEGMENT);
  12346. #else
  12347. planner.buffer_line_kinematic(cart, fr_mm_s, active_extruder);
  12348. #endif
  12349. COPY(current_position, cart);
  12350. } // plan_arc
  12351. #endif // ARC_SUPPORT
  12352. #if ENABLED(BEZIER_CURVE_SUPPORT)
  12353. void plan_cubic_move(const float (&cart)[XYZE], const float (&offset)[4]) {
  12354. cubic_b_spline(current_position, cart, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  12355. COPY(current_position, cart);
  12356. }
  12357. #endif // BEZIER_CURVE_SUPPORT
  12358. #if ENABLED(USE_CONTROLLER_FAN)
  12359. void controllerFan() {
  12360. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  12361. nextMotorCheck = 0; // Last time the state was checked
  12362. const millis_t ms = millis();
  12363. if (ELAPSED(ms, nextMotorCheck)) {
  12364. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  12365. // If any of the drivers or the bed are enabled...
  12366. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON
  12367. #if HAS_HEATED_BED
  12368. || thermalManager.soft_pwm_amount_bed > 0
  12369. #endif
  12370. #if HAS_X2_ENABLE
  12371. || X2_ENABLE_READ == X_ENABLE_ON
  12372. #endif
  12373. #if HAS_Y2_ENABLE
  12374. || Y2_ENABLE_READ == Y_ENABLE_ON
  12375. #endif
  12376. #if HAS_Z2_ENABLE
  12377. || Z2_ENABLE_READ == Z_ENABLE_ON
  12378. #endif
  12379. || E0_ENABLE_READ == E_ENABLE_ON
  12380. #if E_STEPPERS > 1
  12381. || E1_ENABLE_READ == E_ENABLE_ON
  12382. #if E_STEPPERS > 2
  12383. || E2_ENABLE_READ == E_ENABLE_ON
  12384. #if E_STEPPERS > 3
  12385. || E3_ENABLE_READ == E_ENABLE_ON
  12386. #if E_STEPPERS > 4
  12387. || E4_ENABLE_READ == E_ENABLE_ON
  12388. #endif
  12389. #endif
  12390. #endif
  12391. #endif
  12392. ) {
  12393. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  12394. }
  12395. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  12396. const uint8_t speed = (lastMotorOn && PENDING(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? CONTROLLERFAN_SPEED : 0;
  12397. controllerFanSpeed = speed;
  12398. // allows digital or PWM fan output to be used (see M42 handling)
  12399. WRITE(CONTROLLER_FAN_PIN, speed);
  12400. analogWrite(CONTROLLER_FAN_PIN, speed);
  12401. }
  12402. }
  12403. #endif // USE_CONTROLLER_FAN
  12404. #if ENABLED(MORGAN_SCARA)
  12405. /**
  12406. * Morgan SCARA Forward Kinematics. Results in cartes[].
  12407. * Maths and first version by QHARLEY.
  12408. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  12409. */
  12410. void forward_kinematics_SCARA(const float &a, const float &b) {
  12411. float a_sin = sin(RADIANS(a)) * L1,
  12412. a_cos = cos(RADIANS(a)) * L1,
  12413. b_sin = sin(RADIANS(b)) * L2,
  12414. b_cos = cos(RADIANS(b)) * L2;
  12415. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  12416. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  12417. /*
  12418. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  12419. SERIAL_ECHOPAIR(" b=", b);
  12420. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  12421. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  12422. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  12423. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  12424. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  12425. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  12426. //*/
  12427. }
  12428. /**
  12429. * Morgan SCARA Inverse Kinematics. Results in delta[].
  12430. *
  12431. * See http://forums.reprap.org/read.php?185,283327
  12432. *
  12433. * Maths and first version by QHARLEY.
  12434. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  12435. */
  12436. void inverse_kinematics(const float raw[XYZ]) {
  12437. static float C2, S2, SK1, SK2, THETA, PSI;
  12438. float sx = raw[X_AXIS] - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  12439. sy = raw[Y_AXIS] - SCARA_OFFSET_Y; // With scaling factor.
  12440. if (L1 == L2)
  12441. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  12442. else
  12443. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  12444. S2 = SQRT(1 - sq(C2));
  12445. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  12446. SK1 = L1 + L2 * C2;
  12447. // Rotated Arm2 gives the distance from Arm1 to Arm2
  12448. SK2 = L2 * S2;
  12449. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  12450. THETA = ATAN2(SK1, SK2) - ATAN2(sx, sy);
  12451. // Angle of Arm2
  12452. PSI = ATAN2(S2, C2);
  12453. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  12454. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  12455. delta[C_AXIS] = raw[Z_AXIS];
  12456. /*
  12457. DEBUG_POS("SCARA IK", raw);
  12458. DEBUG_POS("SCARA IK", delta);
  12459. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  12460. SERIAL_ECHOPAIR(",", sy);
  12461. SERIAL_ECHOPAIR(" C2=", C2);
  12462. SERIAL_ECHOPAIR(" S2=", S2);
  12463. SERIAL_ECHOPAIR(" Theta=", THETA);
  12464. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  12465. //*/
  12466. }
  12467. #endif // MORGAN_SCARA
  12468. #if ENABLED(TEMP_STAT_LEDS)
  12469. static bool red_led = false;
  12470. static millis_t next_status_led_update_ms = 0;
  12471. void handle_status_leds(void) {
  12472. if (ELAPSED(millis(), next_status_led_update_ms)) {
  12473. next_status_led_update_ms += 500; // Update every 0.5s
  12474. float max_temp = 0.0;
  12475. #if HAS_HEATED_BED
  12476. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  12477. #endif
  12478. HOTEND_LOOP()
  12479. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  12480. const bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  12481. if (new_led != red_led) {
  12482. red_led = new_led;
  12483. #if PIN_EXISTS(STAT_LED_RED)
  12484. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  12485. #if PIN_EXISTS(STAT_LED_BLUE)
  12486. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  12487. #endif
  12488. #else
  12489. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  12490. #endif
  12491. }
  12492. }
  12493. }
  12494. #endif
  12495. void enable_all_steppers() {
  12496. #if ENABLED(AUTO_POWER_CONTROL)
  12497. powerManager.power_on();
  12498. #endif
  12499. #if ENABLED(HANGPRINTER)
  12500. enable_A();
  12501. enable_B();
  12502. enable_C();
  12503. enable_D();
  12504. #else
  12505. enable_X();
  12506. enable_Y();
  12507. enable_Z();
  12508. enable_E4();
  12509. #endif
  12510. enable_E0();
  12511. enable_E1();
  12512. enable_E2();
  12513. enable_E3();
  12514. }
  12515. void disable_e_stepper(const uint8_t e) {
  12516. switch (e) {
  12517. case 0: disable_E0(); break;
  12518. case 1: disable_E1(); break;
  12519. case 2: disable_E2(); break;
  12520. case 3: disable_E3(); break;
  12521. case 4: disable_E4(); break;
  12522. }
  12523. }
  12524. void disable_e_steppers() {
  12525. disable_E0();
  12526. disable_E1();
  12527. disable_E2();
  12528. disable_E3();
  12529. disable_E4();
  12530. }
  12531. void disable_all_steppers() {
  12532. disable_X();
  12533. disable_Y();
  12534. disable_Z();
  12535. disable_e_steppers();
  12536. }
  12537. /**
  12538. * Manage several activities:
  12539. * - Check for Filament Runout
  12540. * - Keep the command buffer full
  12541. * - Check for maximum inactive time between commands
  12542. * - Check for maximum inactive time between stepper commands
  12543. * - Check if pin CHDK needs to go LOW
  12544. * - Check for KILL button held down
  12545. * - Check for HOME button held down
  12546. * - Check if cooling fan needs to be switched on
  12547. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  12548. */
  12549. void manage_inactivity(const bool ignore_stepper_queue/*=false*/) {
  12550. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  12551. runout.run();
  12552. #endif
  12553. if (commands_in_queue < BUFSIZE) get_available_commands();
  12554. const millis_t ms = millis();
  12555. if (max_inactive_time && ELAPSED(ms, previous_move_ms + max_inactive_time)) {
  12556. SERIAL_ERROR_START();
  12557. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  12558. kill(PSTR(MSG_KILLED));
  12559. }
  12560. // Prevent steppers timing-out in the middle of M600
  12561. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  12562. #define MOVE_AWAY_TEST !did_pause_print
  12563. #else
  12564. #define MOVE_AWAY_TEST true
  12565. #endif
  12566. if (stepper_inactive_time) {
  12567. if (planner.has_blocks_queued())
  12568. previous_move_ms = ms; // reset_stepper_timeout to keep steppers powered
  12569. else if (MOVE_AWAY_TEST && !ignore_stepper_queue && ELAPSED(ms, previous_move_ms + stepper_inactive_time)) {
  12570. #if ENABLED(DISABLE_INACTIVE_X)
  12571. disable_X();
  12572. #endif
  12573. #if ENABLED(DISABLE_INACTIVE_Y)
  12574. disable_Y();
  12575. #endif
  12576. #if ENABLED(DISABLE_INACTIVE_Z)
  12577. disable_Z();
  12578. #endif
  12579. #if ENABLED(DISABLE_INACTIVE_E)
  12580. disable_e_steppers();
  12581. #endif
  12582. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTIPANEL) // Only needed with an LCD
  12583. if (ubl.lcd_map_control) ubl.lcd_map_control = defer_return_to_status = false;
  12584. #endif
  12585. }
  12586. }
  12587. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  12588. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  12589. chdkActive = false;
  12590. WRITE(CHDK, LOW);
  12591. }
  12592. #endif
  12593. #if HAS_KILL
  12594. // Check if the kill button was pressed and wait just in case it was an accidental
  12595. // key kill key press
  12596. // -------------------------------------------------------------------------------
  12597. static int killCount = 0; // make the inactivity button a bit less responsive
  12598. const int KILL_DELAY = 750;
  12599. if (!READ(KILL_PIN))
  12600. killCount++;
  12601. else if (killCount > 0)
  12602. killCount--;
  12603. // Exceeded threshold and we can confirm that it was not accidental
  12604. // KILL the machine
  12605. // ----------------------------------------------------------------
  12606. if (killCount >= KILL_DELAY) {
  12607. SERIAL_ERROR_START();
  12608. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  12609. kill(PSTR(MSG_KILLED));
  12610. }
  12611. #endif
  12612. #if HAS_HOME
  12613. // Check to see if we have to home, use poor man's debouncer
  12614. // ---------------------------------------------------------
  12615. static int homeDebounceCount = 0; // poor man's debouncing count
  12616. const int HOME_DEBOUNCE_DELAY = 2500;
  12617. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  12618. if (!homeDebounceCount) {
  12619. enqueue_and_echo_commands_P(PSTR("G28"));
  12620. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  12621. }
  12622. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  12623. homeDebounceCount++;
  12624. else
  12625. homeDebounceCount = 0;
  12626. }
  12627. #endif
  12628. #if ENABLED(USE_CONTROLLER_FAN)
  12629. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  12630. #endif
  12631. #if ENABLED(AUTO_POWER_CONTROL)
  12632. powerManager.check();
  12633. #endif
  12634. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  12635. if (thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP
  12636. && ELAPSED(ms, previous_move_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  12637. && !planner.has_blocks_queued()
  12638. ) {
  12639. #if ENABLED(SWITCHING_EXTRUDER)
  12640. bool oldstatus;
  12641. switch (active_extruder) {
  12642. default: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  12643. #if E_STEPPERS > 1
  12644. case 2: case 3: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  12645. #if E_STEPPERS > 2
  12646. case 4: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  12647. #endif // E_STEPPERS > 2
  12648. #endif // E_STEPPERS > 1
  12649. }
  12650. #else // !SWITCHING_EXTRUDER
  12651. bool oldstatus;
  12652. switch (active_extruder) {
  12653. default: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  12654. #if E_STEPPERS > 1
  12655. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  12656. #if E_STEPPERS > 2
  12657. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  12658. #if E_STEPPERS > 3
  12659. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  12660. #if E_STEPPERS > 4
  12661. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  12662. #endif // E_STEPPERS > 4
  12663. #endif // E_STEPPERS > 3
  12664. #endif // E_STEPPERS > 2
  12665. #endif // E_STEPPERS > 1
  12666. }
  12667. #endif // !SWITCHING_EXTRUDER
  12668. const float olde = current_position[E_CART];
  12669. current_position[E_CART] += EXTRUDER_RUNOUT_EXTRUDE;
  12670. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  12671. current_position[E_CART] = olde;
  12672. planner.set_e_position_mm(olde);
  12673. planner.synchronize();
  12674. #if ENABLED(SWITCHING_EXTRUDER)
  12675. switch (active_extruder) {
  12676. default: oldstatus = E0_ENABLE_WRITE(oldstatus); break;
  12677. #if E_STEPPERS > 1
  12678. case 2: case 3: oldstatus = E1_ENABLE_WRITE(oldstatus); break;
  12679. #if E_STEPPERS > 2
  12680. case 4: oldstatus = E2_ENABLE_WRITE(oldstatus); break;
  12681. #endif // E_STEPPERS > 2
  12682. #endif // E_STEPPERS > 1
  12683. }
  12684. #else // !SWITCHING_EXTRUDER
  12685. switch (active_extruder) {
  12686. case 0: E0_ENABLE_WRITE(oldstatus); break;
  12687. #if E_STEPPERS > 1
  12688. case 1: E1_ENABLE_WRITE(oldstatus); break;
  12689. #if E_STEPPERS > 2
  12690. case 2: E2_ENABLE_WRITE(oldstatus); break;
  12691. #if E_STEPPERS > 3
  12692. case 3: E3_ENABLE_WRITE(oldstatus); break;
  12693. #if E_STEPPERS > 4
  12694. case 4: E4_ENABLE_WRITE(oldstatus); break;
  12695. #endif // E_STEPPERS > 4
  12696. #endif // E_STEPPERS > 3
  12697. #endif // E_STEPPERS > 2
  12698. #endif // E_STEPPERS > 1
  12699. }
  12700. #endif // !SWITCHING_EXTRUDER
  12701. previous_move_ms = ms; // reset_stepper_timeout to keep steppers powered
  12702. }
  12703. #endif // EXTRUDER_RUNOUT_PREVENT
  12704. #if ENABLED(DUAL_X_CARRIAGE)
  12705. // handle delayed move timeout
  12706. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  12707. // travel moves have been received so enact them
  12708. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  12709. set_destination_from_current();
  12710. prepare_move_to_destination();
  12711. }
  12712. #endif
  12713. #if ENABLED(TEMP_STAT_LEDS)
  12714. handle_status_leds();
  12715. #endif
  12716. #if ENABLED(MONITOR_DRIVER_STATUS)
  12717. monitor_tmc_driver();
  12718. #endif
  12719. planner.check_axes_activity();
  12720. }
  12721. /**
  12722. * Standard idle routine keeps the machine alive
  12723. */
  12724. void idle(
  12725. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  12726. bool no_stepper_sleep/*=false*/
  12727. #endif
  12728. ) {
  12729. #if ENABLED(MAX7219_DEBUG)
  12730. max7219.idle_tasks();
  12731. #endif
  12732. lcd_update();
  12733. host_keepalive();
  12734. manage_inactivity(
  12735. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  12736. no_stepper_sleep
  12737. #endif
  12738. );
  12739. thermalManager.manage_heater();
  12740. #if ENABLED(PRINTCOUNTER)
  12741. print_job_timer.tick();
  12742. #endif
  12743. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  12744. buzzer.tick();
  12745. #endif
  12746. #if ENABLED(I2C_POSITION_ENCODERS)
  12747. static millis_t i2cpem_next_update_ms;
  12748. if (planner.has_blocks_queued() && ELAPSED(millis(), i2cpem_next_update_ms)) {
  12749. I2CPEM.update();
  12750. i2cpem_next_update_ms = millis() + I2CPE_MIN_UPD_TIME_MS;
  12751. }
  12752. #endif
  12753. #if HAS_AUTO_REPORTING
  12754. if (!suspend_auto_report) {
  12755. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  12756. thermalManager.auto_report_temperatures();
  12757. #endif
  12758. #if ENABLED(AUTO_REPORT_SD_STATUS)
  12759. card.auto_report_sd_status();
  12760. #endif
  12761. }
  12762. #endif
  12763. }
  12764. /**
  12765. * Kill all activity and lock the machine.
  12766. * After this the machine will need to be reset.
  12767. */
  12768. void kill(const char* lcd_msg) {
  12769. SERIAL_ERROR_START();
  12770. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  12771. thermalManager.disable_all_heaters();
  12772. disable_all_steppers();
  12773. #if ENABLED(ULTRA_LCD)
  12774. kill_screen(lcd_msg);
  12775. #else
  12776. UNUSED(lcd_msg);
  12777. #endif
  12778. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  12779. cli(); // Stop interrupts
  12780. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  12781. thermalManager.disable_all_heaters(); //turn off heaters again
  12782. #ifdef ACTION_ON_KILL
  12783. SERIAL_ECHOLNPGM("//action:" ACTION_ON_KILL);
  12784. #endif
  12785. #if HAS_POWER_SWITCH
  12786. PSU_OFF();
  12787. #endif
  12788. suicide();
  12789. while (1) {
  12790. #if ENABLED(USE_WATCHDOG)
  12791. watchdog_reset();
  12792. #endif
  12793. } // Wait for reset
  12794. }
  12795. /**
  12796. * Turn off heaters and stop the print in progress
  12797. * After a stop the machine may be resumed with M999
  12798. */
  12799. void stop() {
  12800. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  12801. #if ENABLED(PROBING_FANS_OFF)
  12802. if (fans_paused) fans_pause(false); // put things back the way they were
  12803. #endif
  12804. if (IsRunning()) {
  12805. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  12806. SERIAL_ERROR_START();
  12807. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  12808. LCD_MESSAGEPGM(MSG_STOPPED);
  12809. safe_delay(350); // allow enough time for messages to get out before stopping
  12810. Running = false;
  12811. }
  12812. }
  12813. /**
  12814. * Marlin entry-point: Set up before the program loop
  12815. * - Set up the kill pin, filament runout, power hold
  12816. * - Start the serial port
  12817. * - Print startup messages and diagnostics
  12818. * - Get EEPROM or default settings
  12819. * - Initialize managers for:
  12820. * • temperature
  12821. * • planner
  12822. * • watchdog
  12823. * • stepper
  12824. * • photo pin
  12825. * • servos
  12826. * • LCD controller
  12827. * • Digipot I2C
  12828. * • Z probe sled
  12829. * • status LEDs
  12830. */
  12831. void setup() {
  12832. #if ENABLED(MAX7219_DEBUG)
  12833. max7219.init();
  12834. #endif
  12835. #if ENABLED(DISABLE_JTAG)
  12836. // Disable JTAG on AT90USB chips to free up pins for IO
  12837. MCUCR = 0x80;
  12838. MCUCR = 0x80;
  12839. #endif
  12840. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  12841. runout.setup();
  12842. #endif
  12843. setup_killpin();
  12844. setup_powerhold();
  12845. #if HAS_STEPPER_RESET
  12846. disableStepperDrivers();
  12847. #endif
  12848. MYSERIAL0.begin(BAUDRATE);
  12849. SERIAL_PROTOCOLLNPGM("start");
  12850. SERIAL_ECHO_START();
  12851. // Prepare communication for TMC drivers
  12852. #if HAS_DRIVER(TMC2130)
  12853. tmc_init_cs_pins();
  12854. #endif
  12855. #if HAS_DRIVER(TMC2208)
  12856. tmc2208_serial_begin();
  12857. #endif
  12858. // Check startup - does nothing if bootloader sets MCUSR to 0
  12859. byte mcu = MCUSR;
  12860. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  12861. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  12862. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  12863. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  12864. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  12865. MCUSR = 0;
  12866. SERIAL_ECHOPGM(MSG_MARLIN);
  12867. SERIAL_CHAR(' ');
  12868. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  12869. SERIAL_EOL();
  12870. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  12871. SERIAL_ECHO_START();
  12872. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  12873. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  12874. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  12875. SERIAL_ECHO_START();
  12876. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  12877. #endif
  12878. SERIAL_ECHO_START();
  12879. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  12880. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, int(sizeof(block_t))*(BLOCK_BUFFER_SIZE));
  12881. // Send "ok" after commands by default
  12882. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  12883. // Load data from EEPROM if available (or use defaults)
  12884. // This also updates variables in the planner, elsewhere
  12885. (void)settings.load();
  12886. #if HAS_M206_COMMAND
  12887. // Initialize current position based on home_offset
  12888. COPY(current_position, home_offset);
  12889. #else
  12890. ZERO(current_position);
  12891. #endif
  12892. // Vital to init stepper/planner equivalent for current_position
  12893. SYNC_PLAN_POSITION_KINEMATIC();
  12894. thermalManager.init(); // Initialize temperature loop
  12895. print_job_timer.init(); // Initial setup of print job timer
  12896. endstops.init(); // Init endstops and pullups
  12897. stepper.init(); // Init stepper. This enables interrupts!
  12898. servo_init(); // Initialize all servos, stow servo probe
  12899. #if HAS_PHOTOGRAPH
  12900. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  12901. #endif
  12902. #if HAS_CASE_LIGHT
  12903. case_light_on = CASE_LIGHT_DEFAULT_ON;
  12904. case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS;
  12905. update_case_light();
  12906. #endif
  12907. #if ENABLED(SPINDLE_LASER_ENABLE)
  12908. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  12909. #if SPINDLE_DIR_CHANGE
  12910. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  12911. #endif
  12912. #if ENABLED(SPINDLE_LASER_PWM)
  12913. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  12914. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  12915. #endif
  12916. #endif
  12917. #if HAS_BED_PROBE
  12918. endstops.enable_z_probe(false);
  12919. #endif
  12920. #if ENABLED(USE_CONTROLLER_FAN)
  12921. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  12922. #endif
  12923. #if HAS_STEPPER_RESET
  12924. enableStepperDrivers();
  12925. #endif
  12926. #if ENABLED(DIGIPOT_I2C)
  12927. digipot_i2c_init();
  12928. #endif
  12929. #if ENABLED(DAC_STEPPER_CURRENT)
  12930. dac_init();
  12931. #endif
  12932. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  12933. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  12934. #endif
  12935. #if HAS_HOME
  12936. SET_INPUT_PULLUP(HOME_PIN);
  12937. #endif
  12938. #if PIN_EXISTS(STAT_LED_RED)
  12939. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  12940. #endif
  12941. #if PIN_EXISTS(STAT_LED_BLUE)
  12942. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  12943. #endif
  12944. #if HAS_COLOR_LEDS
  12945. leds.setup();
  12946. #endif
  12947. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  12948. SET_OUTPUT(RGB_LED_R_PIN);
  12949. SET_OUTPUT(RGB_LED_G_PIN);
  12950. SET_OUTPUT(RGB_LED_B_PIN);
  12951. #if ENABLED(RGBW_LED)
  12952. SET_OUTPUT(RGB_LED_W_PIN);
  12953. #endif
  12954. #endif
  12955. #if ENABLED(MK2_MULTIPLEXER)
  12956. SET_OUTPUT(E_MUX0_PIN);
  12957. SET_OUTPUT(E_MUX1_PIN);
  12958. SET_OUTPUT(E_MUX2_PIN);
  12959. #endif
  12960. #if HAS_FANMUX
  12961. fanmux_init();
  12962. #endif
  12963. lcd_init();
  12964. lcd_reset_status();
  12965. #if ENABLED(SHOW_BOOTSCREEN)
  12966. lcd_bootscreen();
  12967. #endif
  12968. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  12969. // Virtual Tools 0, 1, 2, 3 = Filament 1, 2, 3, 4, etc.
  12970. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS && t < MIXING_STEPPERS; t++)
  12971. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  12972. mixing_virtual_tool_mix[t][i] = (t == i) ? 1.0 : 0.0;
  12973. // Remaining virtual tools are 100% filament 1
  12974. #if MIXING_STEPPERS < MIXING_VIRTUAL_TOOLS
  12975. for (uint8_t t = MIXING_STEPPERS; t < MIXING_VIRTUAL_TOOLS; t++)
  12976. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  12977. mixing_virtual_tool_mix[t][i] = (i == 0) ? 1.0 : 0.0;
  12978. #endif
  12979. // Initialize mixing to tool 0 color
  12980. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  12981. mixing_factor[i] = mixing_virtual_tool_mix[0][i];
  12982. #endif
  12983. #if ENABLED(BLTOUCH)
  12984. // Make sure any BLTouch error condition is cleared
  12985. bltouch_command(BLTOUCH_RESET);
  12986. set_bltouch_deployed(false);
  12987. #endif
  12988. #if ENABLED(I2C_POSITION_ENCODERS)
  12989. I2CPEM.init();
  12990. #endif
  12991. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  12992. i2c.onReceive(i2c_on_receive);
  12993. i2c.onRequest(i2c_on_request);
  12994. #endif
  12995. #if DO_SWITCH_EXTRUDER
  12996. move_extruder_servo(0); // Initialize extruder servo
  12997. #endif
  12998. #if ENABLED(SWITCHING_NOZZLE)
  12999. move_nozzle_servo(0); // Initialize nozzle servo
  13000. #endif
  13001. #if ENABLED(PARKING_EXTRUDER)
  13002. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  13003. pe_activate_magnet(0);
  13004. pe_activate_magnet(1);
  13005. #else
  13006. pe_deactivate_magnet(0);
  13007. pe_deactivate_magnet(1);
  13008. #endif
  13009. #endif
  13010. #if ENABLED(POWER_LOSS_RECOVERY)
  13011. check_print_job_recovery();
  13012. #endif
  13013. #if ENABLED(USE_WATCHDOG)
  13014. watchdog_init();
  13015. #endif
  13016. #if ENABLED(HANGPRINTER)
  13017. enable_A();
  13018. enable_B();
  13019. enable_C();
  13020. enable_D();
  13021. #endif
  13022. #if ENABLED(SDSUPPORT) && DISABLED(ULTRA_LCD)
  13023. card.beginautostart();
  13024. #endif
  13025. }
  13026. /**
  13027. * The main Marlin program loop
  13028. *
  13029. * - Abort SD printing if flagged
  13030. * - Save or log commands to SD
  13031. * - Process available commands (if not saving)
  13032. * - Call heater manager
  13033. * - Call inactivity manager
  13034. * - Call endstop manager
  13035. * - Call LCD update
  13036. */
  13037. void loop() {
  13038. #if ENABLED(SDSUPPORT)
  13039. card.checkautostart();
  13040. #if ENABLED(ULTIPANEL)
  13041. if (abort_sd_printing) {
  13042. abort_sd_printing = false;
  13043. card.stopSDPrint(
  13044. #if SD_RESORT
  13045. true
  13046. #endif
  13047. );
  13048. clear_command_queue();
  13049. quickstop_stepper();
  13050. print_job_timer.stop();
  13051. thermalManager.disable_all_heaters();
  13052. #if FAN_COUNT > 0
  13053. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  13054. #endif
  13055. wait_for_heatup = false;
  13056. #if ENABLED(POWER_LOSS_RECOVERY)
  13057. card.removeJobRecoveryFile();
  13058. #endif
  13059. }
  13060. #endif
  13061. #endif // SDSUPPORT
  13062. if (commands_in_queue < BUFSIZE) get_available_commands();
  13063. if (commands_in_queue) {
  13064. #if ENABLED(SDSUPPORT)
  13065. if (card.saving) {
  13066. char* command = command_queue[cmd_queue_index_r];
  13067. if (strstr_P(command, PSTR("M29"))) {
  13068. // M29 closes the file
  13069. card.closefile();
  13070. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  13071. #if USE_MARLINSERIAL
  13072. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  13073. SERIAL_ECHOLNPAIR("Dropped bytes: ", customizedSerial.dropped());
  13074. #endif
  13075. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  13076. SERIAL_ECHOLNPAIR("Max RX Queue Size: ", customizedSerial.rxMaxEnqueued());
  13077. #endif
  13078. #endif
  13079. ok_to_send();
  13080. }
  13081. else {
  13082. // Write the string from the read buffer to SD
  13083. card.write_command(command);
  13084. if (card.logging)
  13085. process_next_command(); // The card is saving because it's logging
  13086. else
  13087. ok_to_send();
  13088. }
  13089. }
  13090. else {
  13091. process_next_command();
  13092. #if ENABLED(POWER_LOSS_RECOVERY)
  13093. if (card.cardOK && card.sdprinting) save_job_recovery_info();
  13094. #endif
  13095. }
  13096. #else
  13097. process_next_command();
  13098. #endif // SDSUPPORT
  13099. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  13100. if (commands_in_queue) {
  13101. --commands_in_queue;
  13102. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  13103. }
  13104. }
  13105. endstops.event_handler();
  13106. idle();
  13107. }