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

Marlin_main.cpp 235KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432
  1. /**
  2. * Marlin Firmware
  3. *
  4. * Based on Sprinter and grbl.
  5. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * About Marlin
  21. *
  22. * This firmware is a mashup between Sprinter and grbl.
  23. * - https://github.com/kliment/Sprinter
  24. * - https://github.com/simen/grbl/tree
  25. *
  26. * It has preliminary support for Matthew Roberts advance algorithm
  27. * - http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  28. */
  29. #include "Marlin.h"
  30. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  31. #include "vector_3.h"
  32. #if ENABLED(AUTO_BED_LEVELING_GRID)
  33. #include "qr_solve.h"
  34. #endif
  35. #endif // AUTO_BED_LEVELING_FEATURE
  36. #if ENABLED(MESH_BED_LEVELING)
  37. #include "mesh_bed_leveling.h"
  38. #endif
  39. #include "ultralcd.h"
  40. #include "planner.h"
  41. #include "stepper.h"
  42. #include "temperature.h"
  43. #include "cardreader.h"
  44. #include "configuration_store.h"
  45. #include "language.h"
  46. #include "pins_arduino.h"
  47. #include "math.h"
  48. #include "buzzer.h"
  49. #if ENABLED(USE_WATCHDOG)
  50. #include "watchdog.h"
  51. #endif
  52. #if ENABLED(BLINKM)
  53. #include "blinkm.h"
  54. #include "Wire.h"
  55. #endif
  56. #if HAS_SERVOS
  57. #include "servo.h"
  58. #endif
  59. #if HAS_DIGIPOTSS
  60. #include <SPI.h>
  61. #endif
  62. /**
  63. * Look here for descriptions of G-codes:
  64. * - http://linuxcnc.org/handbook/gcode/g-code.html
  65. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  66. *
  67. * Help us document these G-codes online:
  68. * - https://github.com/MarlinFirmware/Marlin/wiki/G-Code-in-Marlin
  69. * - http://reprap.org/wiki/G-code
  70. *
  71. * -----------------
  72. * Implemented Codes
  73. * -----------------
  74. *
  75. * "G" Codes
  76. *
  77. * G0 -> G1
  78. * G1 - Coordinated Movement X Y Z E
  79. * G2 - CW ARC
  80. * G3 - CCW ARC
  81. * G4 - Dwell S<seconds> or P<milliseconds>
  82. * G10 - retract filament according to settings of M207
  83. * G11 - retract recover filament according to settings of M208
  84. * G28 - Home one or more axes
  85. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  86. * G30 - Single Z probe, probes bed at current XY location.
  87. * G31 - Dock sled (Z_PROBE_SLED only)
  88. * G32 - Undock sled (Z_PROBE_SLED only)
  89. * G90 - Use Absolute Coordinates
  90. * G91 - Use Relative Coordinates
  91. * G92 - Set current position to coordinates given
  92. *
  93. * "M" Codes
  94. *
  95. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  96. * M1 - Same as M0
  97. * M17 - Enable/Power all stepper motors
  98. * M18 - Disable all stepper motors; same as M84
  99. * M20 - List SD card
  100. * M21 - Init SD card
  101. * M22 - Release SD card
  102. * M23 - Select SD file (M23 filename.g)
  103. * M24 - Start/resume SD print
  104. * M25 - Pause SD print
  105. * M26 - Set SD position in bytes (M26 S12345)
  106. * M27 - Report SD print status
  107. * M28 - Start SD write (M28 filename.g)
  108. * M29 - Stop SD write
  109. * M30 - Delete file from SD (M30 filename.g)
  110. * M31 - Output time since last M109 or SD card start to serial
  111. * M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  112. * syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  113. * Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  114. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  115. * M33 - Get the longname version of a path
  116. * M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used.
  117. * M48 - Measure Z_Probe repeatability. M48 [P # of points] [X position] [Y position] [V_erboseness #] [E_ngage Probe] [L # of legs of travel]
  118. * M80 - Turn on Power Supply
  119. * M81 - Turn off Power Supply
  120. * M82 - Set E codes absolute (default)
  121. * M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  122. * M84 - Disable steppers until next move,
  123. * or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  124. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  125. * M92 - Set axis_steps_per_unit - same syntax as G92
  126. * M104 - Set extruder target temp
  127. * M105 - Read current temp
  128. * M106 - Fan on
  129. * M107 - Fan off
  130. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  131. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  132. * IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  133. * M110 - Set the current line number
  134. * M111 - Set debug flags with S<mask>. See flag bits defined in Marlin.h.
  135. * M112 - Emergency stop
  136. * M114 - Output current position to serial port
  137. * M115 - Capabilities string
  138. * M117 - Display a message on the controller screen
  139. * M119 - Output Endstop status to serial port
  140. * M120 - Enable endstop detection
  141. * M121 - Disable endstop detection
  142. * M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  143. * M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  144. * M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  145. * M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  146. * M140 - Set bed target temp
  147. * M145 - Set the heatup state H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  148. * M150 - Set BlinkM Color Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work.
  149. * M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  150. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  151. * M200 - set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).:D<millimeters>-
  152. * M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  153. * M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  154. * M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  155. * M204 - Set default acceleration: P for Printing moves, R for Retract only (no X, Y, Z) moves and T for Travel (non printing) moves (ex. M204 P800 T3000 R9000) in mm/sec^2
  156. * M205 - advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk, E=maximum E jerk
  157. * M206 - Set additional homing offset
  158. * M207 - Set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  159. * M208 - Set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  160. * M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  161. * M218 - Set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  162. * M220 - Set speed factor override percentage: S<factor in percent>
  163. * M221 - Set extrude factor override percentage: S<factor in percent>
  164. * M226 - Wait until the specified pin reaches the state required: P<pin number> S<pin state>
  165. * M240 - Trigger a camera to take a photograph
  166. * M250 - Set LCD contrast C<contrast value> (value 0..63)
  167. * M280 - Set servo position absolute. P: servo index, S: angle or microseconds
  168. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  169. * M301 - Set PID parameters P I and D
  170. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  171. * M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  172. * M304 - Set bed PID parameters P I and D
  173. * M380 - Activate solenoid on active extruder
  174. * M381 - Disable all solenoids
  175. * M400 - Finish all moves
  176. * M401 - Lower Z probe if present
  177. * M402 - Raise Z probe if present
  178. * M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  179. * M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  180. * M406 - Turn off Filament Sensor extrusion control
  181. * M407 - Display measured filament diameter
  182. * M410 - Quickstop. Abort all the planned moves
  183. * M420 - Enable/Disable Mesh Leveling (with current values) S1=enable S0=disable
  184. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<mm> Y<mm> Z<mm>
  185. * M428 - Set the home_offset logically based on the current_position
  186. * M500 - Store parameters in EEPROM
  187. * M501 - Read parameters from EEPROM (if you need reset them after you changed them temporarily).
  188. * M502 - Revert to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  189. * M503 - Print the current settings (from memory not from EEPROM). Use S0 to leave off headings.
  190. * M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  191. * M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  192. * M665 - Set delta configurations: L<diagonal rod> R<delta radius> S<segments/s>
  193. * M666 - Set delta endstop adjustment
  194. * M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  195. * M907 - Set digital trimpot motor current using axis codes.
  196. * M908 - Control digital trimpot directly.
  197. * M350 - Set microstepping mode.
  198. * M351 - Toggle MS1 MS2 pins directly.
  199. *
  200. * ************ SCARA Specific - This can change to suit future G-code regulations
  201. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  202. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  203. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  204. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  205. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  206. * M365 - SCARA calibration: Scaling factor, X, Y, Z axis
  207. * ************* SCARA End ***************
  208. *
  209. * ************ Custom codes - This can change to suit future G-code regulations
  210. * M100 - Watch Free Memory (For Debugging Only)
  211. * M851 - Set Z probe's Z offset (mm above extruder -- The value will always be negative)
  212. * M928 - Start SD logging (M928 filename.g) - ended by M29
  213. * M999 - Restart after being stopped by error
  214. *
  215. * "T" Codes
  216. *
  217. * T0-T3 - Select a tool by index (usually an extruder) [ F<mm/min> ]
  218. *
  219. */
  220. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  221. void gcode_M100();
  222. #endif
  223. #if ENABLED(SDSUPPORT)
  224. CardReader card;
  225. #endif
  226. bool Running = true;
  227. uint8_t marlin_debug_flags = DEBUG_INFO | DEBUG_ERRORS;
  228. static float feedrate = 1500.0, saved_feedrate;
  229. float current_position[NUM_AXIS] = { 0.0 };
  230. static float destination[NUM_AXIS] = { 0.0 };
  231. bool axis_known_position[3] = { false };
  232. bool axis_homed[3] = { false };
  233. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  234. static char* current_command, *current_command_args;
  235. static int cmd_queue_index_r = 0;
  236. static int cmd_queue_index_w = 0;
  237. static int commands_in_queue = 0;
  238. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  239. const float homing_feedrate[] = HOMING_FEEDRATE;
  240. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  241. int feedrate_multiplier = 100; //100->1 200->2
  242. int saved_feedrate_multiplier;
  243. int extruder_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  244. bool volumetric_enabled = false;
  245. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA);
  246. float volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  247. float home_offset[3] = { 0 };
  248. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  249. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  250. #if FAN_COUNT > 0
  251. int fanSpeeds[FAN_COUNT] = { 0 };
  252. #endif
  253. uint8_t active_extruder = 0;
  254. bool cancel_heatup = false;
  255. const char errormagic[] PROGMEM = "Error:";
  256. const char echomagic[] PROGMEM = "echo:";
  257. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  258. static bool relative_mode = false; //Determines Absolute or Relative Coordinates
  259. static int serial_count = 0;
  260. static char* seen_pointer; ///< A pointer to find chars in the command string (X, Y, Z, E, etc.)
  261. const char* queued_commands_P = NULL; /* pointer to the current line in the active sequence of commands, or NULL when none */
  262. const int sensitive_pins[] = SENSITIVE_PINS; ///< Sensitive pin list for M42
  263. // Inactivity shutdown
  264. millis_t previous_cmd_ms = 0;
  265. static millis_t max_inactive_time = 0;
  266. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000L;
  267. millis_t print_job_start_ms = 0; ///< Print job start time
  268. millis_t print_job_stop_ms = 0; ///< Print job stop time
  269. static uint8_t target_extruder;
  270. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  271. int xy_travel_speed = XY_TRAVEL_SPEED;
  272. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  273. #endif
  274. #if ENABLED(Z_DUAL_ENDSTOPS) && DISABLED(DELTA)
  275. float z_endstop_adj = 0;
  276. #endif
  277. // Extruder offsets
  278. #if EXTRUDERS > 1
  279. #ifndef EXTRUDER_OFFSET_X
  280. #define EXTRUDER_OFFSET_X { 0 }
  281. #endif
  282. #ifndef EXTRUDER_OFFSET_Y
  283. #define EXTRUDER_OFFSET_Y { 0 }
  284. #endif
  285. float extruder_offset[][EXTRUDERS] = {
  286. EXTRUDER_OFFSET_X,
  287. EXTRUDER_OFFSET_Y
  288. #if ENABLED(DUAL_X_CARRIAGE)
  289. , { 0 } // supports offsets in XYZ plane
  290. #endif
  291. };
  292. #endif
  293. #if HAS_SERVO_ENDSTOPS
  294. const int servo_endstop_id[] = SERVO_ENDSTOP_IDS;
  295. const int servo_endstop_angle[][2] = SERVO_ENDSTOP_ANGLES;
  296. #endif
  297. #if ENABLED(BARICUDA)
  298. int ValvePressure = 0;
  299. int EtoPPressure = 0;
  300. #endif
  301. #if ENABLED(FWRETRACT)
  302. bool autoretract_enabled = false;
  303. bool retracted[EXTRUDERS] = { false };
  304. bool retracted_swap[EXTRUDERS] = { false };
  305. float retract_length = RETRACT_LENGTH;
  306. float retract_length_swap = RETRACT_LENGTH_SWAP;
  307. float retract_feedrate = RETRACT_FEEDRATE;
  308. float retract_zlift = RETRACT_ZLIFT;
  309. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  310. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  311. float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  312. #endif // FWRETRACT
  313. #if ENABLED(ULTIPANEL) && HAS_POWER_SWITCH
  314. bool powersupply =
  315. #if ENABLED(PS_DEFAULT_OFF)
  316. false
  317. #else
  318. true
  319. #endif
  320. ;
  321. #endif
  322. #if ENABLED(DELTA)
  323. #define TOWER_1 X_AXIS
  324. #define TOWER_2 Y_AXIS
  325. #define TOWER_3 Z_AXIS
  326. float delta[3] = { 0 };
  327. #define SIN_60 0.8660254037844386
  328. #define COS_60 0.5
  329. float endstop_adj[3] = { 0 };
  330. // these are the default values, can be overriden with M665
  331. float delta_radius = DELTA_RADIUS;
  332. float delta_tower1_x = -SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  333. float delta_tower1_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1);
  334. float delta_tower2_x = SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  335. float delta_tower2_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2);
  336. float delta_tower3_x = 0; // back middle tower
  337. float delta_tower3_y = (delta_radius + DELTA_RADIUS_TRIM_TOWER_3);
  338. float delta_diagonal_rod = DELTA_DIAGONAL_ROD;
  339. float delta_diagonal_rod_trim_tower_1 = DELTA_DIAGONAL_ROD_TRIM_TOWER_1;
  340. float delta_diagonal_rod_trim_tower_2 = DELTA_DIAGONAL_ROD_TRIM_TOWER_2;
  341. float delta_diagonal_rod_trim_tower_3 = DELTA_DIAGONAL_ROD_TRIM_TOWER_3;
  342. float delta_diagonal_rod_2_tower_1 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_1);
  343. float delta_diagonal_rod_2_tower_2 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_2);
  344. float delta_diagonal_rod_2_tower_3 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_3);
  345. //float delta_diagonal_rod_2 = sq(delta_diagonal_rod);
  346. float delta_segments_per_second = DELTA_SEGMENTS_PER_SECOND;
  347. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  348. int delta_grid_spacing[2] = { 0, 0 };
  349. float bed_level[AUTO_BED_LEVELING_GRID_POINTS][AUTO_BED_LEVELING_GRID_POINTS];
  350. #endif
  351. #else
  352. static bool home_all_axis = true;
  353. #endif
  354. #if ENABLED(SCARA)
  355. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND;
  356. static float delta[3] = { 0 };
  357. float axis_scaling[3] = { 1, 1, 1 }; // Build size scaling, default to 1
  358. #endif
  359. #if ENABLED(FILAMENT_SENSOR)
  360. //Variables for Filament Sensor input
  361. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
  362. bool filament_sensor = false; //M405 turns on filament_sensor control, M406 turns it off
  363. float filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
  364. signed char measurement_delay[MAX_MEASUREMENT_DELAY + 1]; //ring buffer to delay measurement store extruder factor after subtracting 100
  365. int delay_index1 = 0; //index into ring buffer
  366. int delay_index2 = -1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
  367. float delay_dist = 0; //delay distance counter
  368. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  369. #endif
  370. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  371. static bool filrunoutEnqueued = false;
  372. #endif
  373. static bool send_ok[BUFSIZE];
  374. #if HAS_SERVOS
  375. Servo servo[NUM_SERVOS];
  376. #endif
  377. #ifdef CHDK
  378. unsigned long chdkHigh = 0;
  379. boolean chdkActive = false;
  380. #endif
  381. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  382. int lpq_len = 20;
  383. #endif
  384. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  385. // States for managing Marlin and host communication
  386. // Marlin sends messages if blocked or busy
  387. enum MarlinBusyState {
  388. NOT_BUSY, // Not in a handler
  389. IN_HANDLER, // Processing a GCode
  390. IN_PROCESS, // Known to be blocking command input (as in G29)
  391. PAUSED_FOR_USER, // Blocking pending any input
  392. PAUSED_FOR_INPUT // Blocking pending text input (concept)
  393. };
  394. static MarlinBusyState busy_state = NOT_BUSY;
  395. static millis_t next_busy_signal_ms = -1;
  396. #define KEEPALIVE_STATE(n) do{ busy_state = n; }while(0)
  397. #else
  398. #define host_keepalive() ;
  399. #define KEEPALIVE_STATE(n) ;
  400. #endif // HOST_KEEPALIVE_FEATURE
  401. //===========================================================================
  402. //================================ Functions ================================
  403. //===========================================================================
  404. void process_next_command();
  405. void plan_arc(float target[NUM_AXIS], float* offset, uint8_t clockwise);
  406. bool setTargetedHotend(int code);
  407. void serial_echopair_P(const char* s_P, int v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  408. void serial_echopair_P(const char* s_P, long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  409. void serial_echopair_P(const char* s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  410. void serial_echopair_P(const char* s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  411. void serial_echopair_P(const char* s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  412. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  413. float extrude_min_temp = EXTRUDE_MINTEMP;
  414. #endif
  415. #if ENABLED(SDSUPPORT)
  416. #include "SdFatUtil.h"
  417. int freeMemory() { return SdFatUtil::FreeRam(); }
  418. #else
  419. extern "C" {
  420. extern unsigned int __bss_end;
  421. extern unsigned int __heap_start;
  422. extern void* __brkval;
  423. int freeMemory() {
  424. int free_memory;
  425. if ((int)__brkval == 0)
  426. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  427. else
  428. free_memory = ((int)&free_memory) - ((int)__brkval);
  429. return free_memory;
  430. }
  431. }
  432. #endif //!SDSUPPORT
  433. /**
  434. * Inject the next "immediate" command, when possible.
  435. * Return true if any immediate commands remain to inject.
  436. */
  437. static bool drain_queued_commands_P() {
  438. if (queued_commands_P != NULL) {
  439. // Get the next gcode to run
  440. size_t i = 0;
  441. char c;
  442. while ((c = queued_commands_P[i++]) && c != '\n') { };
  443. if (i > 1) {
  444. char cmd[i];
  445. strncpy_P(cmd, queued_commands_P, i - 1);
  446. cmd[i - 1] = '\0';
  447. if (enqueue_and_echo_command(cmd)) { // buffer was not full (else we will retry later)
  448. if (c)
  449. queued_commands_P += i; // move to next command
  450. else
  451. queued_commands_P = NULL; // no more commands in the sequence
  452. }
  453. }
  454. }
  455. return (queued_commands_P != NULL); // any more left to add?
  456. }
  457. /**
  458. * Record one or many commands to run from program memory.
  459. * Aborts the current queue, if any.
  460. * Note: drain_queued_commands_P() must be called repeatedly to drain the commands afterwards
  461. */
  462. void enqueue_and_echo_commands_P(const char* pgcode) {
  463. queued_commands_P = pgcode;
  464. drain_queued_commands_P(); // first command executed asap (when possible)
  465. }
  466. /**
  467. * Once a new command is in the ring buffer, call this to commit it
  468. */
  469. inline void _commit_command(bool say_ok) {
  470. send_ok[cmd_queue_index_w] = say_ok;
  471. cmd_queue_index_w = (cmd_queue_index_w + 1) % BUFSIZE;
  472. commands_in_queue++;
  473. }
  474. /**
  475. * Copy a command directly into the main command buffer, from RAM.
  476. * Returns true if successfully adds the command
  477. */
  478. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  479. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  480. strcpy(command_queue[cmd_queue_index_w], cmd);
  481. _commit_command(say_ok);
  482. return true;
  483. }
  484. /**
  485. * Enqueue with Serial Echo
  486. */
  487. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  488. if (_enqueuecommand(cmd, say_ok)) {
  489. SERIAL_ECHO_START;
  490. SERIAL_ECHOPGM(MSG_Enqueueing);
  491. SERIAL_ECHO(cmd);
  492. SERIAL_ECHOLNPGM("\"");
  493. return true;
  494. }
  495. return false;
  496. }
  497. void setup_killpin() {
  498. #if HAS_KILL
  499. SET_INPUT(KILL_PIN);
  500. WRITE(KILL_PIN, HIGH);
  501. #endif
  502. }
  503. void setup_filrunoutpin() {
  504. #if HAS_FILRUNOUT
  505. pinMode(FILRUNOUT_PIN, INPUT);
  506. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  507. WRITE(FILRUNOUT_PIN, HIGH);
  508. #endif
  509. #endif
  510. }
  511. // Set home pin
  512. void setup_homepin(void) {
  513. #if HAS_HOME
  514. SET_INPUT(HOME_PIN);
  515. WRITE(HOME_PIN, HIGH);
  516. #endif
  517. }
  518. void setup_photpin() {
  519. #if HAS_PHOTOGRAPH
  520. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  521. #endif
  522. }
  523. void setup_powerhold() {
  524. #if HAS_SUICIDE
  525. OUT_WRITE(SUICIDE_PIN, HIGH);
  526. #endif
  527. #if HAS_POWER_SWITCH
  528. #if ENABLED(PS_DEFAULT_OFF)
  529. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  530. #else
  531. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  532. #endif
  533. #endif
  534. }
  535. void suicide() {
  536. #if HAS_SUICIDE
  537. OUT_WRITE(SUICIDE_PIN, LOW);
  538. #endif
  539. }
  540. void servo_init() {
  541. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  542. servo[0].attach(SERVO0_PIN);
  543. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  544. #endif
  545. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  546. servo[1].attach(SERVO1_PIN);
  547. servo[1].detach();
  548. #endif
  549. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  550. servo[2].attach(SERVO2_PIN);
  551. servo[2].detach();
  552. #endif
  553. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  554. servo[3].attach(SERVO3_PIN);
  555. servo[3].detach();
  556. #endif
  557. // Set position of Servo Endstops that are defined
  558. #if HAS_SERVO_ENDSTOPS
  559. for (int i = 0; i < 3; i++)
  560. if (servo_endstop_id[i] >= 0)
  561. servo[servo_endstop_id[i]].move(servo_endstop_angle[i][1]);
  562. #endif
  563. }
  564. /**
  565. * Stepper Reset (RigidBoard, et.al.)
  566. */
  567. #if HAS_STEPPER_RESET
  568. void disableStepperDrivers() {
  569. pinMode(STEPPER_RESET_PIN, OUTPUT);
  570. digitalWrite(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  571. }
  572. void enableStepperDrivers() { pinMode(STEPPER_RESET_PIN, INPUT); } // set to input, which allows it to be pulled high by pullups
  573. #endif
  574. /**
  575. * Marlin entry-point: Set up before the program loop
  576. * - Set up the kill pin, filament runout, power hold
  577. * - Start the serial port
  578. * - Print startup messages and diagnostics
  579. * - Get EEPROM or default settings
  580. * - Initialize managers for:
  581. * • temperature
  582. * • planner
  583. * • watchdog
  584. * • stepper
  585. * • photo pin
  586. * • servos
  587. * • LCD controller
  588. * • Digipot I2C
  589. * • Z probe sled
  590. * • status LEDs
  591. */
  592. void setup() {
  593. #ifdef DISABLE_JTAG
  594. // Disable JTAG on AT90USB chips to free up pins for IO
  595. MCUCR = 0x80;
  596. MCUCR = 0x80;
  597. #endif
  598. setup_killpin();
  599. setup_filrunoutpin();
  600. setup_powerhold();
  601. #if HAS_STEPPER_RESET
  602. disableStepperDrivers();
  603. #endif
  604. MYSERIAL.begin(BAUDRATE);
  605. SERIAL_PROTOCOLLNPGM("start");
  606. SERIAL_ECHO_START;
  607. // Check startup - does nothing if bootloader sets MCUSR to 0
  608. byte mcu = MCUSR;
  609. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  610. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  611. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  612. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  613. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  614. MCUSR = 0;
  615. SERIAL_ECHOPGM(MSG_MARLIN);
  616. SERIAL_ECHOLNPGM(" " SHORT_BUILD_VERSION);
  617. #ifdef STRING_DISTRIBUTION_DATE
  618. #ifdef STRING_CONFIG_H_AUTHOR
  619. SERIAL_ECHO_START;
  620. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  621. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  622. SERIAL_ECHOPGM(MSG_AUTHOR);
  623. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  624. SERIAL_ECHOPGM("Compiled: ");
  625. SERIAL_ECHOLNPGM(__DATE__);
  626. #endif // STRING_CONFIG_H_AUTHOR
  627. #endif // STRING_DISTRIBUTION_DATE
  628. SERIAL_ECHO_START;
  629. SERIAL_ECHOPGM(MSG_FREE_MEMORY);
  630. SERIAL_ECHO(freeMemory());
  631. SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES);
  632. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  633. // Send "ok" after commands by default
  634. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  635. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  636. Config_RetrieveSettings();
  637. lcd_init();
  638. tp_init(); // Initialize temperature loop
  639. plan_init(); // Initialize planner;
  640. #if ENABLED(USE_WATCHDOG)
  641. watchdog_init();
  642. #endif
  643. st_init(); // Initialize stepper, this enables interrupts!
  644. setup_photpin();
  645. servo_init();
  646. #if HAS_CONTROLLERFAN
  647. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  648. #endif
  649. #if HAS_STEPPER_RESET
  650. enableStepperDrivers();
  651. #endif
  652. #if ENABLED(DIGIPOT_I2C)
  653. digipot_i2c_init();
  654. #endif
  655. #if ENABLED(Z_PROBE_SLED)
  656. pinMode(SLED_PIN, OUTPUT);
  657. digitalWrite(SLED_PIN, LOW); // turn it off
  658. #endif // Z_PROBE_SLED
  659. setup_homepin();
  660. #ifdef STAT_LED_RED
  661. pinMode(STAT_LED_RED, OUTPUT);
  662. digitalWrite(STAT_LED_RED, LOW); // turn it off
  663. #endif
  664. #ifdef STAT_LED_BLUE
  665. pinMode(STAT_LED_BLUE, OUTPUT);
  666. digitalWrite(STAT_LED_BLUE, LOW); // turn it off
  667. #endif
  668. }
  669. /**
  670. * The main Marlin program loop
  671. *
  672. * - Save or log commands to SD
  673. * - Process available commands (if not saving)
  674. * - Call heater manager
  675. * - Call inactivity manager
  676. * - Call endstop manager
  677. * - Call LCD update
  678. */
  679. void loop() {
  680. if (commands_in_queue < BUFSIZE) get_command();
  681. #if ENABLED(SDSUPPORT)
  682. card.checkautostart(false);
  683. #endif
  684. if (commands_in_queue) {
  685. #if ENABLED(SDSUPPORT)
  686. if (card.saving) {
  687. char* command = command_queue[cmd_queue_index_r];
  688. if (strstr_P(command, PSTR("M29"))) {
  689. // M29 closes the file
  690. card.closefile();
  691. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  692. ok_to_send();
  693. }
  694. else {
  695. // Write the string from the read buffer to SD
  696. card.write_command(command);
  697. if (card.logging)
  698. process_next_command(); // The card is saving because it's logging
  699. else
  700. ok_to_send();
  701. }
  702. }
  703. else
  704. process_next_command();
  705. #else
  706. process_next_command();
  707. #endif // SDSUPPORT
  708. commands_in_queue--;
  709. cmd_queue_index_r = (cmd_queue_index_r + 1) % BUFSIZE;
  710. }
  711. checkHitEndstops();
  712. idle();
  713. }
  714. void gcode_line_error(const char* err, bool doFlush = true) {
  715. SERIAL_ERROR_START;
  716. serialprintPGM(err);
  717. SERIAL_ERRORLN(gcode_LastN);
  718. //Serial.println(gcode_N);
  719. if (doFlush) FlushSerialRequestResend();
  720. serial_count = 0;
  721. }
  722. /**
  723. * Add to the circular command queue the next command from:
  724. * - The command-injection queue (queued_commands_P)
  725. * - The active serial input (usually USB)
  726. * - The SD card file being actively printed
  727. */
  728. void get_command() {
  729. static char serial_line_buffer[MAX_CMD_SIZE];
  730. static boolean serial_comment_mode = false;
  731. if (drain_queued_commands_P()) return; // priority is given to non-serial commands
  732. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  733. static millis_t last_command_time = 0;
  734. millis_t ms = millis();
  735. if (!MYSERIAL.available() && commands_in_queue == 0 && ms - last_command_time > NO_TIMEOUTS) {
  736. SERIAL_ECHOLNPGM(MSG_WAIT);
  737. last_command_time = ms;
  738. }
  739. #endif
  740. //
  741. // Loop while serial characters are incoming and the queue is not full
  742. //
  743. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  744. char serial_char = MYSERIAL.read();
  745. //
  746. // If the character ends the line
  747. //
  748. if (serial_char == '\n' || serial_char == '\r') {
  749. serial_comment_mode = false; // end of line == end of comment
  750. if (!serial_count) return; // empty lines just exit
  751. serial_line_buffer[serial_count] = 0; // terminate string
  752. serial_count = 0; //reset buffer
  753. char* command = serial_line_buffer;
  754. while (*command == ' ') command++; // skip any leading spaces
  755. char* npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  756. char* apos = strchr(command, '*');
  757. if (npos) {
  758. boolean M110 = strstr_P(command, PSTR("M110")) != NULL;
  759. if (M110) {
  760. char* n2pos = strchr(command + 4, 'N');
  761. if (n2pos) npos = n2pos;
  762. }
  763. gcode_N = strtol(npos + 1, NULL, 10);
  764. if (gcode_N != gcode_LastN + 1 && !M110) {
  765. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  766. return;
  767. }
  768. if (apos) {
  769. byte checksum = 0, count = 0;
  770. while (command[count] != '*') checksum ^= command[count++];
  771. if (strtol(apos + 1, NULL, 10) != checksum) {
  772. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  773. return;
  774. }
  775. // if no errors, continue parsing
  776. }
  777. else {
  778. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  779. return;
  780. }
  781. gcode_LastN = gcode_N;
  782. // if no errors, continue parsing
  783. }
  784. else if (apos) { // No '*' without 'N'
  785. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  786. return;
  787. }
  788. // Movement commands alert when stopped
  789. if (IsStopped()) {
  790. char* gpos = strchr(command, 'G');
  791. if (gpos) {
  792. int codenum = strtol(gpos + 1, NULL, 10);
  793. switch (codenum) {
  794. case 0:
  795. case 1:
  796. case 2:
  797. case 3:
  798. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  799. LCD_MESSAGEPGM(MSG_STOPPED);
  800. break;
  801. }
  802. }
  803. }
  804. // If command was e-stop process now
  805. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  806. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  807. last_command_time = ms;
  808. #endif
  809. // Add the command to the queue
  810. _enqueuecommand(serial_line_buffer, true);
  811. }
  812. else if (serial_count >= MAX_CMD_SIZE - 1) {
  813. // Keep fetching, but ignore normal characters beyond the max length
  814. // The command will be injected when EOL is reached
  815. }
  816. else if (serial_char == '\\') { // Handle escapes
  817. if (MYSERIAL.available() > 0) {
  818. // if we have one more character, copy it over
  819. serial_char = MYSERIAL.read();
  820. serial_line_buffer[serial_count++] = serial_char;
  821. }
  822. // otherwise do nothing
  823. }
  824. else { // it's not a newline, carriage return or escape char
  825. if (serial_char == ';') serial_comment_mode = true;
  826. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  827. }
  828. } // queue has space, serial has data
  829. #if ENABLED(SDSUPPORT)
  830. static bool stop_buffering = false,
  831. sd_comment_mode = false;
  832. if (!card.sdprinting) return;
  833. // '#' stops reading from SD to the buffer prematurely, so procedural macro calls are possible
  834. // if it occurs, stop_buffering is triggered and the buffer is run dry.
  835. // this character _can_ occur in serial com, due to checksums. however, no checksums are used in SD printing
  836. if (commands_in_queue == 0) stop_buffering = false;
  837. uint16_t sd_count = 0;
  838. bool card_eof = card.eof();
  839. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  840. int16_t n = card.get();
  841. char sd_char = (char)n;
  842. card_eof = card.eof();
  843. if (card_eof || n == -1
  844. || sd_char == '\n' || sd_char == '\r'
  845. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  846. ) {
  847. if (card_eof) {
  848. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  849. print_job_stop_ms = millis();
  850. char time[30];
  851. millis_t t = (print_job_stop_ms - print_job_start_ms) / 1000;
  852. int hours = t / 60 / 60, minutes = (t / 60) % 60;
  853. sprintf_P(time, PSTR("%i " MSG_END_HOUR " %i " MSG_END_MINUTE), hours, minutes);
  854. SERIAL_ECHO_START;
  855. SERIAL_ECHOLN(time);
  856. lcd_setstatus(time, true);
  857. card.printingHasFinished();
  858. card.checkautostart(true);
  859. }
  860. if (sd_char == '#') stop_buffering = true;
  861. sd_comment_mode = false; //for new command
  862. if (!sd_count) continue; //skip empty lines
  863. command_queue[cmd_queue_index_w][sd_count] = '\0'; //terminate string
  864. sd_count = 0; //clear buffer
  865. _commit_command(false);
  866. }
  867. else if (sd_count >= MAX_CMD_SIZE - 1) {
  868. // Keep fetching, but ignore normal characters beyond the max length
  869. // The command will be injected when EOL is reached
  870. }
  871. else {
  872. if (sd_char == ';') sd_comment_mode = true;
  873. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  874. }
  875. }
  876. #endif // SDSUPPORT
  877. }
  878. bool code_has_value() {
  879. int i = 1;
  880. char c = seen_pointer[i];
  881. while (c == ' ') c = seen_pointer[++i];
  882. if (c == '-' || c == '+') c = seen_pointer[++i];
  883. if (c == '.') c = seen_pointer[++i];
  884. return (c >= '0' && c <= '9');
  885. }
  886. float code_value() {
  887. float ret;
  888. char* e = strchr(seen_pointer, 'E');
  889. if (e) {
  890. *e = 0;
  891. ret = strtod(seen_pointer + 1, NULL);
  892. *e = 'E';
  893. }
  894. else
  895. ret = strtod(seen_pointer + 1, NULL);
  896. return ret;
  897. }
  898. long code_value_long() { return strtol(seen_pointer + 1, NULL, 10); }
  899. int16_t code_value_short() { return (int16_t)strtol(seen_pointer + 1, NULL, 10); }
  900. bool code_seen(char code) {
  901. seen_pointer = strchr(current_command_args, code);
  902. return (seen_pointer != NULL); // Return TRUE if the code-letter was found
  903. }
  904. #define DEFINE_PGM_READ_ANY(type, reader) \
  905. static inline type pgm_read_any(const type *p) \
  906. { return pgm_read_##reader##_near(p); }
  907. DEFINE_PGM_READ_ANY(float, float);
  908. DEFINE_PGM_READ_ANY(signed char, byte);
  909. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  910. static const PROGMEM type array##_P[3] = \
  911. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  912. static inline type array(int axis) \
  913. { return pgm_read_any(&array##_P[axis]); }
  914. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  915. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  916. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  917. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  918. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  919. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  920. #if ENABLED(DUAL_X_CARRIAGE)
  921. #define DXC_FULL_CONTROL_MODE 0
  922. #define DXC_AUTO_PARK_MODE 1
  923. #define DXC_DUPLICATION_MODE 2
  924. static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  925. static float x_home_pos(int extruder) {
  926. if (extruder == 0)
  927. return base_home_pos(X_AXIS) + home_offset[X_AXIS];
  928. else
  929. // In dual carriage mode the extruder offset provides an override of the
  930. // second X-carriage offset when homed - otherwise X2_HOME_POS is used.
  931. // This allow soft recalibration of the second extruder offset position without firmware reflash
  932. // (through the M218 command).
  933. return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : X2_HOME_POS;
  934. }
  935. static int x_home_dir(int extruder) {
  936. return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR;
  937. }
  938. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  939. static bool active_extruder_parked = false; // used in mode 1 & 2
  940. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  941. static millis_t delayed_move_time = 0; // used in mode 1
  942. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  943. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  944. bool extruder_duplication_enabled = false; // used in mode 2
  945. #endif //DUAL_X_CARRIAGE
  946. #if ENABLED(DEBUG_LEVELING_FEATURE)
  947. void print_xyz(const char* prefix, const float x, const float y, const float z) {
  948. SERIAL_ECHO(prefix);
  949. SERIAL_ECHOPAIR(": (", x);
  950. SERIAL_ECHOPAIR(", ", y);
  951. SERIAL_ECHOPAIR(", ", z);
  952. SERIAL_ECHOLNPGM(")");
  953. }
  954. void print_xyz(const char* prefix, const float xyz[]) {
  955. print_xyz(prefix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  956. }
  957. #endif
  958. static void set_axis_is_at_home(AxisEnum axis) {
  959. #if ENABLED(DUAL_X_CARRIAGE)
  960. if (axis == X_AXIS) {
  961. if (active_extruder != 0) {
  962. current_position[X_AXIS] = x_home_pos(active_extruder);
  963. min_pos[X_AXIS] = X2_MIN_POS;
  964. max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], X2_MAX_POS);
  965. return;
  966. }
  967. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  968. float xoff = home_offset[X_AXIS];
  969. current_position[X_AXIS] = base_home_pos(X_AXIS) + xoff;
  970. min_pos[X_AXIS] = base_min_pos(X_AXIS) + xoff;
  971. max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + xoff, max(extruder_offset[X_AXIS][1], X2_MAX_POS) - duplicate_extruder_x_offset);
  972. return;
  973. }
  974. }
  975. #endif
  976. #if ENABLED(SCARA)
  977. if (axis == X_AXIS || axis == Y_AXIS) {
  978. float homeposition[3];
  979. for (int i = 0; i < 3; i++) homeposition[i] = base_home_pos(i);
  980. // SERIAL_ECHOPGM("homeposition[x]= "); SERIAL_ECHO(homeposition[0]);
  981. // SERIAL_ECHOPGM("homeposition[y]= "); SERIAL_ECHOLN(homeposition[1]);
  982. // Works out real Homeposition angles using inverse kinematics,
  983. // and calculates homing offset using forward kinematics
  984. calculate_delta(homeposition);
  985. // SERIAL_ECHOPGM("base Theta= "); SERIAL_ECHO(delta[X_AXIS]);
  986. // SERIAL_ECHOPGM(" base Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]);
  987. for (int i = 0; i < 2; i++) delta[i] -= home_offset[i];
  988. // SERIAL_ECHOPGM("addhome X="); SERIAL_ECHO(home_offset[X_AXIS]);
  989. // SERIAL_ECHOPGM(" addhome Y="); SERIAL_ECHO(home_offset[Y_AXIS]);
  990. // SERIAL_ECHOPGM(" addhome Theta="); SERIAL_ECHO(delta[X_AXIS]);
  991. // SERIAL_ECHOPGM(" addhome Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]);
  992. calculate_SCARA_forward_Transform(delta);
  993. // SERIAL_ECHOPGM("Delta X="); SERIAL_ECHO(delta[X_AXIS]);
  994. // SERIAL_ECHOPGM(" Delta Y="); SERIAL_ECHOLN(delta[Y_AXIS]);
  995. current_position[axis] = delta[axis];
  996. // SCARA home positions are based on configuration since the actual limits are determined by the
  997. // inverse kinematic transform.
  998. min_pos[axis] = base_min_pos(axis); // + (delta[axis] - base_home_pos(axis));
  999. max_pos[axis] = base_max_pos(axis); // + (delta[axis] - base_home_pos(axis));
  1000. }
  1001. else
  1002. #endif
  1003. {
  1004. current_position[axis] = base_home_pos(axis) + home_offset[axis];
  1005. min_pos[axis] = base_min_pos(axis) + home_offset[axis];
  1006. max_pos[axis] = base_max_pos(axis) + home_offset[axis];
  1007. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && Z_HOME_DIR < 0
  1008. if (axis == Z_AXIS) current_position[Z_AXIS] -= zprobe_zoffset;
  1009. #endif
  1010. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1011. if (marlin_debug_flags & DEBUG_LEVELING) {
  1012. SERIAL_ECHOPAIR("set_axis_is_at_home ", (unsigned long)axis);
  1013. SERIAL_ECHOPAIR(" > (home_offset[axis]==", home_offset[axis]);
  1014. print_xyz(") > current_position", current_position);
  1015. }
  1016. #endif
  1017. }
  1018. }
  1019. /**
  1020. * Some planner shorthand inline functions
  1021. */
  1022. inline void set_homing_bump_feedrate(AxisEnum axis) {
  1023. const int homing_bump_divisor[] = HOMING_BUMP_DIVISOR;
  1024. int hbd = homing_bump_divisor[axis];
  1025. if (hbd < 1) {
  1026. hbd = 10;
  1027. SERIAL_ECHO_START;
  1028. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1029. }
  1030. feedrate = homing_feedrate[axis] / hbd;
  1031. }
  1032. inline void line_to_current_position() {
  1033. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate / 60, active_extruder);
  1034. }
  1035. inline void line_to_z(float zPosition) {
  1036. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate / 60, active_extruder);
  1037. }
  1038. inline void line_to_destination(float mm_m) {
  1039. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], mm_m / 60, active_extruder);
  1040. }
  1041. inline void line_to_destination() {
  1042. line_to_destination(feedrate);
  1043. }
  1044. inline void sync_plan_position() {
  1045. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1046. }
  1047. #if ENABLED(DELTA) || ENABLED(SCARA)
  1048. inline void sync_plan_position_delta() {
  1049. calculate_delta(current_position);
  1050. plan_set_position(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], current_position[E_AXIS]);
  1051. }
  1052. #endif
  1053. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1054. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1055. static void setup_for_endstop_move() {
  1056. saved_feedrate = feedrate;
  1057. saved_feedrate_multiplier = feedrate_multiplier;
  1058. feedrate_multiplier = 100;
  1059. refresh_cmd_timeout();
  1060. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1061. if (marlin_debug_flags & DEBUG_LEVELING) {
  1062. SERIAL_ECHOLNPGM("setup_for_endstop_move > enable_endstops(true)");
  1063. }
  1064. #endif
  1065. enable_endstops(true);
  1066. }
  1067. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  1068. #if ENABLED(DELTA)
  1069. /**
  1070. * Calculate delta, start a line, and set current_position to destination
  1071. */
  1072. void prepare_move_raw() {
  1073. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1074. if (marlin_debug_flags & DEBUG_LEVELING) {
  1075. print_xyz("prepare_move_raw > destination", destination);
  1076. }
  1077. #endif
  1078. refresh_cmd_timeout();
  1079. calculate_delta(destination);
  1080. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], (feedrate / 60) * (feedrate_multiplier / 100.0), active_extruder);
  1081. set_current_to_destination();
  1082. }
  1083. #endif
  1084. #if ENABLED(AUTO_BED_LEVELING_GRID)
  1085. #if DISABLED(DELTA)
  1086. static void set_bed_level_equation_lsq(double* plane_equation_coefficients) {
  1087. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1088. planeNormal.debug("planeNormal");
  1089. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1090. //bedLevel.debug("bedLevel");
  1091. //plan_bed_level_matrix.debug("bed level before");
  1092. //vector_3 uncorrected_position = plan_get_position_mm();
  1093. //uncorrected_position.debug("position before");
  1094. vector_3 corrected_position = plan_get_position();
  1095. //corrected_position.debug("position after");
  1096. current_position[X_AXIS] = corrected_position.x;
  1097. current_position[Y_AXIS] = corrected_position.y;
  1098. current_position[Z_AXIS] = corrected_position.z;
  1099. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1100. if (marlin_debug_flags & DEBUG_LEVELING) {
  1101. print_xyz("set_bed_level_equation_lsq > current_position", current_position);
  1102. }
  1103. #endif
  1104. sync_plan_position();
  1105. }
  1106. #endif // !DELTA
  1107. #else // !AUTO_BED_LEVELING_GRID
  1108. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1109. plan_bed_level_matrix.set_to_identity();
  1110. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1111. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1112. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1113. vector_3 planeNormal = vector_3::cross(pt1 - pt2, pt3 - pt2).get_normal();
  1114. if (planeNormal.z < 0) {
  1115. planeNormal.x = -planeNormal.x;
  1116. planeNormal.y = -planeNormal.y;
  1117. planeNormal.z = -planeNormal.z;
  1118. }
  1119. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1120. vector_3 corrected_position = plan_get_position();
  1121. current_position[X_AXIS] = corrected_position.x;
  1122. current_position[Y_AXIS] = corrected_position.y;
  1123. current_position[Z_AXIS] = corrected_position.z;
  1124. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1125. if (marlin_debug_flags & DEBUG_LEVELING) {
  1126. print_xyz("set_bed_level_equation_3pts > current_position", current_position);
  1127. }
  1128. #endif
  1129. sync_plan_position();
  1130. }
  1131. #endif // !AUTO_BED_LEVELING_GRID
  1132. static void run_z_probe() {
  1133. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1134. #if ENABLED(DELTA)
  1135. float start_z = current_position[Z_AXIS];
  1136. long start_steps = st_get_position(Z_AXIS);
  1137. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1138. if (marlin_debug_flags & DEBUG_LEVELING) {
  1139. SERIAL_ECHOLNPGM("run_z_probe (DELTA) 1");
  1140. }
  1141. #endif
  1142. // move down slowly until you find the bed
  1143. feedrate = homing_feedrate[Z_AXIS] / 4;
  1144. destination[Z_AXIS] = -10;
  1145. prepare_move_raw(); // this will also set_current_to_destination
  1146. st_synchronize();
  1147. endstops_hit_on_purpose(); // clear endstop hit flags
  1148. // we have to let the planner know where we are right now as it is not where we said to go.
  1149. long stop_steps = st_get_position(Z_AXIS);
  1150. float mm = start_z - float(start_steps - stop_steps) / axis_steps_per_unit[Z_AXIS];
  1151. current_position[Z_AXIS] = mm;
  1152. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1153. if (marlin_debug_flags & DEBUG_LEVELING) {
  1154. print_xyz("run_z_probe (DELTA) 2 > current_position", current_position);
  1155. }
  1156. #endif
  1157. sync_plan_position_delta();
  1158. #else // !DELTA
  1159. plan_bed_level_matrix.set_to_identity();
  1160. feedrate = homing_feedrate[Z_AXIS];
  1161. // Move down until the Z probe (or endstop?) is triggered
  1162. float zPosition = -(Z_MAX_LENGTH + 10);
  1163. line_to_z(zPosition);
  1164. st_synchronize();
  1165. // Tell the planner where we ended up - Get this from the stepper handler
  1166. zPosition = st_get_axis_position_mm(Z_AXIS);
  1167. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1168. // move up the retract distance
  1169. zPosition += home_bump_mm(Z_AXIS);
  1170. line_to_z(zPosition);
  1171. st_synchronize();
  1172. endstops_hit_on_purpose(); // clear endstop hit flags
  1173. // move back down slowly to find bed
  1174. set_homing_bump_feedrate(Z_AXIS);
  1175. zPosition -= home_bump_mm(Z_AXIS) * 2;
  1176. line_to_z(zPosition);
  1177. st_synchronize();
  1178. endstops_hit_on_purpose(); // clear endstop hit flags
  1179. // Get the current stepper position after bumping an endstop
  1180. current_position[Z_AXIS] = st_get_axis_position_mm(Z_AXIS);
  1181. sync_plan_position();
  1182. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1183. if (marlin_debug_flags & DEBUG_LEVELING) {
  1184. print_xyz("run_z_probe > current_position", current_position);
  1185. }
  1186. #endif
  1187. #endif // !DELTA
  1188. }
  1189. /**
  1190. * Plan a move to (X, Y, Z) and set the current_position
  1191. * The final current_position may not be the one that was requested
  1192. */
  1193. static void do_blocking_move_to(float x, float y, float z) {
  1194. float oldFeedRate = feedrate;
  1195. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1196. if (marlin_debug_flags & DEBUG_LEVELING) {
  1197. print_xyz("do_blocking_move_to", x, y, z);
  1198. }
  1199. #endif
  1200. #if ENABLED(DELTA)
  1201. feedrate = XY_TRAVEL_SPEED;
  1202. destination[X_AXIS] = x;
  1203. destination[Y_AXIS] = y;
  1204. destination[Z_AXIS] = z;
  1205. prepare_move_raw(); // this will also set_current_to_destination
  1206. st_synchronize();
  1207. #else
  1208. feedrate = homing_feedrate[Z_AXIS];
  1209. current_position[Z_AXIS] = z;
  1210. line_to_current_position();
  1211. st_synchronize();
  1212. feedrate = xy_travel_speed;
  1213. current_position[X_AXIS] = x;
  1214. current_position[Y_AXIS] = y;
  1215. line_to_current_position();
  1216. st_synchronize();
  1217. #endif
  1218. feedrate = oldFeedRate;
  1219. }
  1220. inline void do_blocking_move_to_xy(float x, float y) { do_blocking_move_to(x, y, current_position[Z_AXIS]); }
  1221. inline void do_blocking_move_to_x(float x) { do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS]); }
  1222. inline void do_blocking_move_to_z(float z) { do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z); }
  1223. inline void raise_z_after_probing() { do_blocking_move_to_z(current_position[Z_AXIS] + Z_RAISE_AFTER_PROBING); }
  1224. static void clean_up_after_endstop_move() {
  1225. #if ENABLED(ENDSTOPS_ONLY_FOR_HOMING)
  1226. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1227. if (marlin_debug_flags & DEBUG_LEVELING) {
  1228. SERIAL_ECHOLNPGM("clean_up_after_endstop_move > ENDSTOPS_ONLY_FOR_HOMING > enable_endstops(false)");
  1229. }
  1230. #endif
  1231. enable_endstops(false);
  1232. #endif
  1233. feedrate = saved_feedrate;
  1234. feedrate_multiplier = saved_feedrate_multiplier;
  1235. refresh_cmd_timeout();
  1236. }
  1237. static void deploy_z_probe() {
  1238. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1239. if (marlin_debug_flags & DEBUG_LEVELING) {
  1240. print_xyz("deploy_z_probe > current_position", current_position);
  1241. }
  1242. #endif
  1243. #if HAS_SERVO_ENDSTOPS
  1244. // Engage Z Servo endstop if enabled
  1245. if (servo_endstop_id[Z_AXIS] >= 0) servo[servo_endstop_id[Z_AXIS]].move(servo_endstop_angle[Z_AXIS][0]);
  1246. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1247. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE;
  1248. // If endstop is already false, the Z probe is deployed
  1249. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1250. bool z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1251. if (z_probe_endstop)
  1252. #else
  1253. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1254. if (z_min_endstop)
  1255. #endif
  1256. {
  1257. // Move to the start position to initiate deployment
  1258. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_X;
  1259. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_Y;
  1260. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_Z;
  1261. prepare_move_raw(); // this will also set_current_to_destination
  1262. // Move to engage deployment
  1263. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE)
  1264. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE;
  1265. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_X != Z_PROBE_ALLEN_KEY_DEPLOY_1_X)
  1266. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_X;
  1267. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_Y != Z_PROBE_ALLEN_KEY_DEPLOY_1_Y)
  1268. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_Y;
  1269. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_Z != Z_PROBE_ALLEN_KEY_DEPLOY_1_Z)
  1270. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_Z;
  1271. prepare_move_raw();
  1272. #ifdef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1273. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE)
  1274. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE;
  1275. // Move to trigger deployment
  1276. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE)
  1277. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE;
  1278. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_X != Z_PROBE_ALLEN_KEY_DEPLOY_2_X)
  1279. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_X;
  1280. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_Y != Z_PROBE_ALLEN_KEY_DEPLOY_2_Y)
  1281. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_Y;
  1282. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_Z != Z_PROBE_ALLEN_KEY_DEPLOY_2_Z)
  1283. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_Z;
  1284. prepare_move_raw();
  1285. #endif
  1286. }
  1287. // Partially Home X,Y for safety
  1288. destination[X_AXIS] = destination[X_AXIS] * 0.75;
  1289. destination[Y_AXIS] = destination[Y_AXIS] * 0.75;
  1290. prepare_move_raw(); // this will also set_current_to_destination
  1291. st_synchronize();
  1292. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1293. z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1294. if (z_probe_endstop)
  1295. #else
  1296. z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1297. if (z_min_endstop)
  1298. #endif
  1299. {
  1300. if (IsRunning()) {
  1301. SERIAL_ERROR_START;
  1302. SERIAL_ERRORLNPGM("Z-Probe failed to engage!");
  1303. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1304. }
  1305. Stop();
  1306. }
  1307. #endif // Z_PROBE_ALLEN_KEY
  1308. }
  1309. static void stow_z_probe(bool doRaise = true) {
  1310. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1311. if (marlin_debug_flags & DEBUG_LEVELING) {
  1312. print_xyz("stow_z_probe > current_position", current_position);
  1313. }
  1314. #endif
  1315. #if HAS_SERVO_ENDSTOPS
  1316. // Retract Z Servo endstop if enabled
  1317. if (servo_endstop_id[Z_AXIS] >= 0) {
  1318. #if Z_RAISE_AFTER_PROBING > 0
  1319. if (doRaise) {
  1320. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1321. if (marlin_debug_flags & DEBUG_LEVELING) {
  1322. SERIAL_ECHOPAIR("Raise Z (after) by ", (float)Z_RAISE_AFTER_PROBING);
  1323. SERIAL_EOL;
  1324. SERIAL_ECHO("> SERVO_ENDSTOPS > raise_z_after_probing()");
  1325. SERIAL_EOL;
  1326. }
  1327. #endif
  1328. raise_z_after_probing(); // this also updates current_position
  1329. st_synchronize();
  1330. }
  1331. #endif
  1332. // Change the Z servo angle
  1333. servo[servo_endstop_id[Z_AXIS]].move(servo_endstop_angle[Z_AXIS][1]);
  1334. }
  1335. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1336. // Move up for safety
  1337. feedrate = Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE;
  1338. #if Z_RAISE_AFTER_PROBING > 0
  1339. destination[Z_AXIS] = current_position[Z_AXIS] + Z_RAISE_AFTER_PROBING;
  1340. prepare_move_raw(); // this will also set_current_to_destination
  1341. #endif
  1342. // Move to the start position to initiate retraction
  1343. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_X;
  1344. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_Y;
  1345. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_Z;
  1346. prepare_move_raw();
  1347. // Move the nozzle down to push the Z probe into retracted position
  1348. if (Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE != Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE)
  1349. feedrate = Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE;
  1350. if (Z_PROBE_ALLEN_KEY_STOW_2_X != Z_PROBE_ALLEN_KEY_STOW_1_X)
  1351. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_X;
  1352. if (Z_PROBE_ALLEN_KEY_STOW_2_Y != Z_PROBE_ALLEN_KEY_STOW_1_Y)
  1353. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_Y;
  1354. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_Z;
  1355. prepare_move_raw();
  1356. // Move up for safety
  1357. if (Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE != Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE)
  1358. feedrate = Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE;
  1359. if (Z_PROBE_ALLEN_KEY_STOW_3_X != Z_PROBE_ALLEN_KEY_STOW_2_X)
  1360. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_X;
  1361. if (Z_PROBE_ALLEN_KEY_STOW_3_Y != Z_PROBE_ALLEN_KEY_STOW_2_Y)
  1362. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_Y;
  1363. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_Z;
  1364. prepare_move_raw();
  1365. // Home XY for safety
  1366. feedrate = homing_feedrate[X_AXIS] / 2;
  1367. destination[X_AXIS] = 0;
  1368. destination[Y_AXIS] = 0;
  1369. prepare_move_raw(); // this will also set_current_to_destination
  1370. st_synchronize();
  1371. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1372. bool z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1373. if (!z_probe_endstop)
  1374. #else
  1375. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1376. if (!z_min_endstop)
  1377. #endif
  1378. {
  1379. if (IsRunning()) {
  1380. SERIAL_ERROR_START;
  1381. SERIAL_ERRORLNPGM("Z-Probe failed to retract!");
  1382. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1383. }
  1384. Stop();
  1385. }
  1386. #endif // Z_PROBE_ALLEN_KEY
  1387. }
  1388. enum ProbeAction {
  1389. ProbeStay = 0,
  1390. ProbeDeploy = _BV(0),
  1391. ProbeStow = _BV(1),
  1392. ProbeDeployAndStow = (ProbeDeploy | ProbeStow)
  1393. };
  1394. // Probe bed height at position (x,y), returns the measured z value
  1395. static float probe_pt(float x, float y, float z_before, ProbeAction probe_action = ProbeDeployAndStow, int verbose_level = 1) {
  1396. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1397. if (marlin_debug_flags & DEBUG_LEVELING) {
  1398. SERIAL_ECHOLNPGM("probe_pt >>>");
  1399. SERIAL_ECHOPAIR("> ProbeAction:", (unsigned long)probe_action);
  1400. SERIAL_EOL;
  1401. print_xyz("> current_position", current_position);
  1402. }
  1403. #endif
  1404. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1405. if (marlin_debug_flags & DEBUG_LEVELING) {
  1406. SERIAL_ECHOPAIR("Z Raise to z_before ", z_before);
  1407. SERIAL_EOL;
  1408. SERIAL_ECHOPAIR("> do_blocking_move_to_z ", z_before);
  1409. SERIAL_EOL;
  1410. }
  1411. #endif
  1412. // Move Z up to the z_before height, then move the Z probe to the given XY
  1413. do_blocking_move_to_z(z_before); // this also updates current_position
  1414. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1415. if (marlin_debug_flags & DEBUG_LEVELING) {
  1416. SERIAL_ECHOPAIR("> do_blocking_move_to_xy ", x - (X_PROBE_OFFSET_FROM_EXTRUDER));
  1417. SERIAL_ECHOPAIR(", ", y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1418. SERIAL_EOL;
  1419. }
  1420. #endif
  1421. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER)); // this also updates current_position
  1422. #if DISABLED(Z_PROBE_SLED) && DISABLED(Z_PROBE_ALLEN_KEY)
  1423. if (probe_action & ProbeDeploy) {
  1424. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1425. if (marlin_debug_flags & DEBUG_LEVELING) {
  1426. SERIAL_ECHOLNPGM("> ProbeDeploy");
  1427. }
  1428. #endif
  1429. deploy_z_probe();
  1430. }
  1431. #endif
  1432. run_z_probe();
  1433. float measured_z = current_position[Z_AXIS];
  1434. #if DISABLED(Z_PROBE_SLED) && DISABLED(Z_PROBE_ALLEN_KEY)
  1435. if (probe_action & ProbeStow) {
  1436. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1437. if (marlin_debug_flags & DEBUG_LEVELING) {
  1438. SERIAL_ECHOLNPGM("> ProbeStow (stow_z_probe will do Z Raise)");
  1439. }
  1440. #endif
  1441. stow_z_probe();
  1442. }
  1443. #endif
  1444. if (verbose_level > 2) {
  1445. SERIAL_PROTOCOLPGM("Bed X: ");
  1446. SERIAL_PROTOCOL_F(x, 3);
  1447. SERIAL_PROTOCOLPGM(" Y: ");
  1448. SERIAL_PROTOCOL_F(y, 3);
  1449. SERIAL_PROTOCOLPGM(" Z: ");
  1450. SERIAL_PROTOCOL_F(measured_z, 3);
  1451. SERIAL_EOL;
  1452. }
  1453. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1454. if (marlin_debug_flags & DEBUG_LEVELING) {
  1455. SERIAL_ECHOLNPGM("<<< probe_pt");
  1456. }
  1457. #endif
  1458. return measured_z;
  1459. }
  1460. #if ENABLED(DELTA)
  1461. /**
  1462. * All DELTA leveling in the Marlin uses NONLINEAR_BED_LEVELING
  1463. */
  1464. static void extrapolate_one_point(int x, int y, int xdir, int ydir) {
  1465. if (bed_level[x][y] != 0.0) {
  1466. return; // Don't overwrite good values.
  1467. }
  1468. float a = 2 * bed_level[x + xdir][y] - bed_level[x + xdir * 2][y]; // Left to right.
  1469. float b = 2 * bed_level[x][y + ydir] - bed_level[x][y + ydir * 2]; // Front to back.
  1470. float c = 2 * bed_level[x + xdir][y + ydir] - bed_level[x + xdir * 2][y + ydir * 2]; // Diagonal.
  1471. float median = c; // Median is robust (ignores outliers).
  1472. if (a < b) {
  1473. if (b < c) median = b;
  1474. if (c < a) median = a;
  1475. }
  1476. else { // b <= a
  1477. if (c < b) median = b;
  1478. if (a < c) median = a;
  1479. }
  1480. bed_level[x][y] = median;
  1481. }
  1482. // Fill in the unprobed points (corners of circular print surface)
  1483. // using linear extrapolation, away from the center.
  1484. static void extrapolate_unprobed_bed_level() {
  1485. int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2;
  1486. for (int y = 0; y <= half; y++) {
  1487. for (int x = 0; x <= half; x++) {
  1488. if (x + y < 3) continue;
  1489. extrapolate_one_point(half - x, half - y, x > 1 ? +1 : 0, y > 1 ? +1 : 0);
  1490. extrapolate_one_point(half + x, half - y, x > 1 ? -1 : 0, y > 1 ? +1 : 0);
  1491. extrapolate_one_point(half - x, half + y, x > 1 ? +1 : 0, y > 1 ? -1 : 0);
  1492. extrapolate_one_point(half + x, half + y, x > 1 ? -1 : 0, y > 1 ? -1 : 0);
  1493. }
  1494. }
  1495. }
  1496. // Print calibration results for plotting or manual frame adjustment.
  1497. static void print_bed_level() {
  1498. for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) {
  1499. for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) {
  1500. SERIAL_PROTOCOL_F(bed_level[x][y], 2);
  1501. SERIAL_PROTOCOLCHAR(' ');
  1502. }
  1503. SERIAL_EOL;
  1504. }
  1505. }
  1506. // Reset calibration results to zero.
  1507. void reset_bed_level() {
  1508. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1509. if (marlin_debug_flags & DEBUG_LEVELING) {
  1510. SERIAL_ECHOLNPGM("reset_bed_level");
  1511. }
  1512. #endif
  1513. for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) {
  1514. for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) {
  1515. bed_level[x][y] = 0.0;
  1516. }
  1517. }
  1518. }
  1519. #endif // DELTA
  1520. #if HAS_SERVO_ENDSTOPS && DISABLED(Z_PROBE_SLED)
  1521. void raise_z_for_servo() {
  1522. float zpos = current_position[Z_AXIS], z_dest = Z_RAISE_BEFORE_PROBING;
  1523. // The zprobe_zoffset is negative any switch below the nozzle, so
  1524. // multiply by Z_HOME_DIR (-1) to move enough away from bed for the probe
  1525. z_dest += axis_known_position[Z_AXIS] ? zprobe_zoffset * Z_HOME_DIR : zpos;
  1526. if (zpos < z_dest) do_blocking_move_to_z(z_dest); // also updates current_position
  1527. }
  1528. #endif
  1529. #endif // AUTO_BED_LEVELING_FEATURE
  1530. static void unknown_position_error() {
  1531. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  1532. SERIAL_ECHO_START;
  1533. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  1534. }
  1535. #if ENABLED(Z_PROBE_SLED)
  1536. #ifndef SLED_DOCKING_OFFSET
  1537. #define SLED_DOCKING_OFFSET 0
  1538. #endif
  1539. /**
  1540. * Method to dock/undock a sled designed by Charles Bell.
  1541. *
  1542. * dock[in] If true, move to MAX_X and engage the electromagnet
  1543. * offset[in] The additional distance to move to adjust docking location
  1544. */
  1545. static void dock_sled(bool dock, int offset = 0) {
  1546. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1547. if (marlin_debug_flags & DEBUG_LEVELING) {
  1548. SERIAL_ECHOPAIR("dock_sled", dock);
  1549. SERIAL_EOL;
  1550. }
  1551. #endif
  1552. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  1553. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  1554. SERIAL_ECHO_START;
  1555. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  1556. return;
  1557. }
  1558. float oldXpos = current_position[X_AXIS]; // save x position
  1559. if (dock) {
  1560. #if Z_RAISE_AFTER_PROBING > 0
  1561. raise_z_after_probing(); // raise Z
  1562. #endif
  1563. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET + offset - 1); // Dock sled a bit closer to ensure proper capturing
  1564. digitalWrite(SLED_PIN, LOW); // turn off magnet
  1565. }
  1566. else {
  1567. float z_loc = current_position[Z_AXIS];
  1568. if (z_loc < Z_RAISE_BEFORE_PROBING + 5) z_loc = Z_RAISE_BEFORE_PROBING;
  1569. do_blocking_move_to(X_MAX_POS + SLED_DOCKING_OFFSET + offset, current_position[Y_AXIS], z_loc); // this also updates current_position
  1570. digitalWrite(SLED_PIN, HIGH); // turn on magnet
  1571. }
  1572. do_blocking_move_to_x(oldXpos); // return to position before docking
  1573. }
  1574. #endif // Z_PROBE_SLED
  1575. /**
  1576. * Home an individual axis
  1577. */
  1578. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  1579. static void homeaxis(AxisEnum axis) {
  1580. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1581. if (marlin_debug_flags & DEBUG_LEVELING) {
  1582. SERIAL_ECHOPAIR(">>> homeaxis(", (unsigned long)axis);
  1583. SERIAL_CHAR(')');
  1584. SERIAL_EOL;
  1585. }
  1586. #endif
  1587. #define HOMEAXIS_DO(LETTER) \
  1588. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1589. if (axis == X_AXIS ? HOMEAXIS_DO(X) : axis == Y_AXIS ? HOMEAXIS_DO(Y) : axis == Z_AXIS ? HOMEAXIS_DO(Z) : 0) {
  1590. int axis_home_dir =
  1591. #if ENABLED(DUAL_X_CARRIAGE)
  1592. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  1593. #endif
  1594. home_dir(axis);
  1595. // Set the axis position as setup for the move
  1596. current_position[axis] = 0;
  1597. sync_plan_position();
  1598. #if ENABLED(Z_PROBE_SLED)
  1599. // Get Probe
  1600. if (axis == Z_AXIS) {
  1601. if (axis_home_dir < 0) dock_sled(false);
  1602. }
  1603. #endif
  1604. #if SERVO_LEVELING && DISABLED(Z_PROBE_SLED)
  1605. // Deploy a Z probe if there is one, and homing towards the bed
  1606. if (axis == Z_AXIS) {
  1607. if (axis_home_dir < 0) deploy_z_probe();
  1608. }
  1609. #endif
  1610. #if HAS_SERVO_ENDSTOPS
  1611. // Engage Servo endstop if enabled
  1612. if (axis != Z_AXIS && servo_endstop_id[axis] >= 0)
  1613. servo[servo_endstop_id[axis]].move(servo_endstop_angle[axis][0]);
  1614. #endif
  1615. // Set a flag for Z motor locking
  1616. #if ENABLED(Z_DUAL_ENDSTOPS)
  1617. if (axis == Z_AXIS) In_Homing_Process(true);
  1618. #endif
  1619. // Move towards the endstop until an endstop is triggered
  1620. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1621. feedrate = homing_feedrate[axis];
  1622. line_to_destination();
  1623. st_synchronize();
  1624. // Set the axis position as setup for the move
  1625. current_position[axis] = 0;
  1626. sync_plan_position();
  1627. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1628. if (marlin_debug_flags & DEBUG_LEVELING) {
  1629. SERIAL_ECHOLNPGM("> enable_endstops(false)");
  1630. }
  1631. #endif
  1632. enable_endstops(false); // Disable endstops while moving away
  1633. // Move away from the endstop by the axis HOME_BUMP_MM
  1634. destination[axis] = -home_bump_mm(axis) * axis_home_dir;
  1635. line_to_destination();
  1636. st_synchronize();
  1637. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1638. if (marlin_debug_flags & DEBUG_LEVELING) {
  1639. SERIAL_ECHOLNPGM("> enable_endstops(true)");
  1640. }
  1641. #endif
  1642. enable_endstops(true); // Enable endstops for next homing move
  1643. // Slow down the feedrate for the next move
  1644. set_homing_bump_feedrate(axis);
  1645. // Move slowly towards the endstop until triggered
  1646. destination[axis] = 2 * home_bump_mm(axis) * axis_home_dir;
  1647. line_to_destination();
  1648. st_synchronize();
  1649. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1650. if (marlin_debug_flags & DEBUG_LEVELING) {
  1651. print_xyz("> TRIGGER ENDSTOP > current_position", current_position);
  1652. }
  1653. #endif
  1654. #if ENABLED(Z_DUAL_ENDSTOPS)
  1655. if (axis == Z_AXIS) {
  1656. float adj = fabs(z_endstop_adj);
  1657. bool lockZ1;
  1658. if (axis_home_dir > 0) {
  1659. adj = -adj;
  1660. lockZ1 = (z_endstop_adj > 0);
  1661. }
  1662. else
  1663. lockZ1 = (z_endstop_adj < 0);
  1664. if (lockZ1) Lock_z_motor(true); else Lock_z2_motor(true);
  1665. sync_plan_position();
  1666. // Move to the adjusted endstop height
  1667. feedrate = homing_feedrate[axis];
  1668. destination[Z_AXIS] = adj;
  1669. line_to_destination();
  1670. st_synchronize();
  1671. if (lockZ1) Lock_z_motor(false); else Lock_z2_motor(false);
  1672. In_Homing_Process(false);
  1673. } // Z_AXIS
  1674. #endif
  1675. #if ENABLED(DELTA)
  1676. // retrace by the amount specified in endstop_adj
  1677. if (endstop_adj[axis] * axis_home_dir < 0) {
  1678. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1679. if (marlin_debug_flags & DEBUG_LEVELING) {
  1680. SERIAL_ECHOLNPGM("> enable_endstops(false)");
  1681. }
  1682. #endif
  1683. enable_endstops(false); // Disable endstops while moving away
  1684. sync_plan_position();
  1685. destination[axis] = endstop_adj[axis];
  1686. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1687. if (marlin_debug_flags & DEBUG_LEVELING) {
  1688. SERIAL_ECHOPAIR("> endstop_adj = ", endstop_adj[axis]);
  1689. print_xyz(" > destination", destination);
  1690. }
  1691. #endif
  1692. line_to_destination();
  1693. st_synchronize();
  1694. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1695. if (marlin_debug_flags & DEBUG_LEVELING) {
  1696. SERIAL_ECHOLNPGM("> enable_endstops(true)");
  1697. }
  1698. #endif
  1699. enable_endstops(true); // Enable endstops for next homing move
  1700. }
  1701. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1702. else {
  1703. if (marlin_debug_flags & DEBUG_LEVELING) {
  1704. SERIAL_ECHOPAIR("> endstop_adj * axis_home_dir = ", endstop_adj[axis] * axis_home_dir);
  1705. SERIAL_EOL;
  1706. }
  1707. }
  1708. #endif
  1709. #endif
  1710. // Set the axis position to its home position (plus home offsets)
  1711. set_axis_is_at_home(axis);
  1712. sync_plan_position();
  1713. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1714. if (marlin_debug_flags & DEBUG_LEVELING) {
  1715. print_xyz("> AFTER set_axis_is_at_home > current_position", current_position);
  1716. }
  1717. #endif
  1718. destination[axis] = current_position[axis];
  1719. feedrate = 0.0;
  1720. endstops_hit_on_purpose(); // clear endstop hit flags
  1721. axis_known_position[axis] = true;
  1722. axis_homed[axis] = true;
  1723. #if ENABLED(Z_PROBE_SLED)
  1724. // bring Z probe back
  1725. if (axis == Z_AXIS) {
  1726. if (axis_home_dir < 0) dock_sled(true);
  1727. }
  1728. #endif
  1729. #if SERVO_LEVELING && DISABLED(Z_PROBE_SLED)
  1730. // Deploy a Z probe if there is one, and homing towards the bed
  1731. if (axis == Z_AXIS) {
  1732. if (axis_home_dir < 0) {
  1733. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1734. if (marlin_debug_flags & DEBUG_LEVELING) {
  1735. SERIAL_ECHOLNPGM("> SERVO_LEVELING > stow_z_probe");
  1736. }
  1737. #endif
  1738. stow_z_probe();
  1739. }
  1740. }
  1741. else
  1742. #endif
  1743. {
  1744. #if HAS_SERVO_ENDSTOPS
  1745. // Retract Servo endstop if enabled
  1746. if (servo_endstop_id[axis] >= 0) {
  1747. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1748. if (marlin_debug_flags & DEBUG_LEVELING) {
  1749. SERIAL_ECHOLNPGM("> SERVO_ENDSTOPS > Stow with servo.move()");
  1750. }
  1751. #endif
  1752. servo[servo_endstop_id[axis]].move(servo_endstop_angle[axis][1]);
  1753. }
  1754. #endif
  1755. }
  1756. }
  1757. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1758. if (marlin_debug_flags & DEBUG_LEVELING) {
  1759. SERIAL_ECHOPAIR("<<< homeaxis(", (unsigned long)axis);
  1760. SERIAL_CHAR(')');
  1761. SERIAL_EOL;
  1762. }
  1763. #endif
  1764. }
  1765. #if ENABLED(FWRETRACT)
  1766. void retract(bool retracting, bool swapping = false) {
  1767. if (retracting == retracted[active_extruder]) return;
  1768. float oldFeedrate = feedrate;
  1769. set_destination_to_current();
  1770. if (retracting) {
  1771. feedrate = retract_feedrate * 60;
  1772. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  1773. plan_set_e_position(current_position[E_AXIS]);
  1774. prepare_move();
  1775. if (retract_zlift > 0.01) {
  1776. current_position[Z_AXIS] -= retract_zlift;
  1777. #if ENABLED(DELTA)
  1778. sync_plan_position_delta();
  1779. #else
  1780. sync_plan_position();
  1781. #endif
  1782. prepare_move();
  1783. }
  1784. }
  1785. else {
  1786. if (retract_zlift > 0.01) {
  1787. current_position[Z_AXIS] += retract_zlift;
  1788. #if ENABLED(DELTA)
  1789. sync_plan_position_delta();
  1790. #else
  1791. sync_plan_position();
  1792. #endif
  1793. //prepare_move();
  1794. }
  1795. feedrate = retract_recover_feedrate * 60;
  1796. float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  1797. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  1798. plan_set_e_position(current_position[E_AXIS]);
  1799. prepare_move();
  1800. }
  1801. feedrate = oldFeedrate;
  1802. retracted[active_extruder] = retracting;
  1803. } // retract()
  1804. #endif // FWRETRACT
  1805. /**
  1806. *
  1807. * G-Code Handler functions
  1808. *
  1809. */
  1810. /**
  1811. * Set XYZE destination and feedrate from the current GCode command
  1812. *
  1813. * - Set destination from included axis codes
  1814. * - Set to current for missing axis codes
  1815. * - Set the feedrate, if included
  1816. */
  1817. void gcode_get_destination() {
  1818. for (int i = 0; i < NUM_AXIS; i++) {
  1819. if (code_seen(axis_codes[i]))
  1820. destination[i] = code_value() + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  1821. else
  1822. destination[i] = current_position[i];
  1823. }
  1824. if (code_seen('F')) {
  1825. float next_feedrate = code_value();
  1826. if (next_feedrate > 0.0) feedrate = next_feedrate;
  1827. }
  1828. }
  1829. void unknown_command_error() {
  1830. SERIAL_ECHO_START;
  1831. SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND);
  1832. SERIAL_ECHO(current_command);
  1833. SERIAL_ECHOPGM("\"\n");
  1834. }
  1835. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  1836. void host_keepalive() {
  1837. millis_t ms = millis();
  1838. if (busy_state != NOT_BUSY) {
  1839. if (ms < next_busy_signal_ms) return;
  1840. switch (busy_state) {
  1841. case NOT_BUSY:
  1842. break;
  1843. case IN_HANDLER:
  1844. case IN_PROCESS:
  1845. SERIAL_ECHO_START;
  1846. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  1847. break;
  1848. case PAUSED_FOR_USER:
  1849. SERIAL_ECHO_START;
  1850. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  1851. break;
  1852. case PAUSED_FOR_INPUT:
  1853. SERIAL_ECHO_START;
  1854. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  1855. break;
  1856. }
  1857. }
  1858. next_busy_signal_ms = ms + 2000UL;
  1859. }
  1860. #endif //HOST_KEEPALIVE_FEATURE
  1861. /**
  1862. * G0, G1: Coordinated movement of X Y Z E axes
  1863. */
  1864. inline void gcode_G0_G1() {
  1865. if (IsRunning()) {
  1866. gcode_get_destination(); // For X Y Z E F
  1867. #if ENABLED(FWRETRACT)
  1868. if (autoretract_enabled && !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  1869. float echange = destination[E_AXIS] - current_position[E_AXIS];
  1870. // Is this move an attempt to retract or recover?
  1871. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  1872. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  1873. plan_set_e_position(current_position[E_AXIS]); // AND from the planner
  1874. retract(!retracted[active_extruder]);
  1875. return;
  1876. }
  1877. }
  1878. #endif //FWRETRACT
  1879. prepare_move();
  1880. }
  1881. }
  1882. /**
  1883. * G2: Clockwise Arc
  1884. * G3: Counterclockwise Arc
  1885. */
  1886. inline void gcode_G2_G3(bool clockwise) {
  1887. if (IsRunning()) {
  1888. #if ENABLED(SF_ARC_FIX)
  1889. bool relative_mode_backup = relative_mode;
  1890. relative_mode = true;
  1891. #endif
  1892. gcode_get_destination();
  1893. #if ENABLED(SF_ARC_FIX)
  1894. relative_mode = relative_mode_backup;
  1895. #endif
  1896. // Center of arc as offset from current_position
  1897. float arc_offset[2] = {
  1898. code_seen('I') ? code_value() : 0,
  1899. code_seen('J') ? code_value() : 0
  1900. };
  1901. // Send an arc to the planner
  1902. plan_arc(destination, arc_offset, clockwise);
  1903. refresh_cmd_timeout();
  1904. }
  1905. }
  1906. /**
  1907. * G4: Dwell S<seconds> or P<milliseconds>
  1908. */
  1909. inline void gcode_G4() {
  1910. millis_t codenum = 0;
  1911. if (code_seen('P')) codenum = code_value_long(); // milliseconds to wait
  1912. if (code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  1913. st_synchronize();
  1914. refresh_cmd_timeout();
  1915. codenum += previous_cmd_ms; // keep track of when we started waiting
  1916. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  1917. while (millis() < codenum) idle();
  1918. }
  1919. #if ENABLED(FWRETRACT)
  1920. /**
  1921. * G10 - Retract filament according to settings of M207
  1922. * G11 - Recover filament according to settings of M208
  1923. */
  1924. inline void gcode_G10_G11(bool doRetract=false) {
  1925. #if EXTRUDERS > 1
  1926. if (doRetract) {
  1927. retracted_swap[active_extruder] = (code_seen('S') && code_value_short() == 1); // checks for swap retract argument
  1928. }
  1929. #endif
  1930. retract(doRetract
  1931. #if EXTRUDERS > 1
  1932. , retracted_swap[active_extruder]
  1933. #endif
  1934. );
  1935. }
  1936. #endif //FWRETRACT
  1937. /**
  1938. * G28: Home all axes according to settings
  1939. *
  1940. * Parameters
  1941. *
  1942. * None Home to all axes with no parameters.
  1943. * With QUICK_HOME enabled XY will home together, then Z.
  1944. *
  1945. * Cartesian parameters
  1946. *
  1947. * X Home to the X endstop
  1948. * Y Home to the Y endstop
  1949. * Z Home to the Z endstop
  1950. *
  1951. */
  1952. inline void gcode_G28() {
  1953. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1954. if (marlin_debug_flags & DEBUG_LEVELING) {
  1955. SERIAL_ECHOLNPGM("gcode_G28 >>>");
  1956. }
  1957. #endif
  1958. // Wait for planner moves to finish!
  1959. st_synchronize();
  1960. // For auto bed leveling, clear the level matrix
  1961. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  1962. plan_bed_level_matrix.set_to_identity();
  1963. #if ENABLED(DELTA)
  1964. reset_bed_level();
  1965. #endif
  1966. #endif
  1967. // For manual bed leveling deactivate the matrix temporarily
  1968. #if ENABLED(MESH_BED_LEVELING)
  1969. uint8_t mbl_was_active = mbl.active;
  1970. mbl.active = 0;
  1971. #endif
  1972. setup_for_endstop_move();
  1973. set_destination_to_current(); // Directly after a reset this is all 0. Later we get a hint if we have to raise z or not.
  1974. feedrate = 0.0;
  1975. #if ENABLED(DELTA)
  1976. // A delta can only safely home all axis at the same time
  1977. // all axis have to home at the same time
  1978. // Pretend the current position is 0,0,0
  1979. for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = 0;
  1980. sync_plan_position();
  1981. // Move all carriages up together until the first endstop is hit.
  1982. for (int i = X_AXIS; i <= Z_AXIS; i++) destination[i] = 3 * (Z_MAX_LENGTH);
  1983. feedrate = 1.732 * homing_feedrate[X_AXIS];
  1984. line_to_destination();
  1985. st_synchronize();
  1986. endstops_hit_on_purpose(); // clear endstop hit flags
  1987. // Destination reached
  1988. for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = destination[i];
  1989. // take care of back off and rehome now we are all at the top
  1990. HOMEAXIS(X);
  1991. HOMEAXIS(Y);
  1992. HOMEAXIS(Z);
  1993. sync_plan_position_delta();
  1994. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1995. if (marlin_debug_flags & DEBUG_LEVELING) {
  1996. print_xyz("(DELTA) > current_position", current_position);
  1997. }
  1998. #endif
  1999. #else // NOT DELTA
  2000. bool homeX = code_seen(axis_codes[X_AXIS]),
  2001. homeY = code_seen(axis_codes[Y_AXIS]),
  2002. homeZ = code_seen(axis_codes[Z_AXIS]);
  2003. home_all_axis = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  2004. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2005. if (home_all_axis || homeZ) {
  2006. HOMEAXIS(Z);
  2007. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2008. if (marlin_debug_flags & DEBUG_LEVELING) {
  2009. print_xyz("> HOMEAXIS(Z) > current_position", current_position);
  2010. }
  2011. #endif
  2012. }
  2013. #elif defined(MIN_Z_HEIGHT_FOR_HOMING) && MIN_Z_HEIGHT_FOR_HOMING > 0
  2014. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  2015. if (current_position[Z_AXIS] <= MIN_Z_HEIGHT_FOR_HOMING) {
  2016. destination[Z_AXIS] = MIN_Z_HEIGHT_FOR_HOMING;
  2017. feedrate = max_feedrate[Z_AXIS] * 60; // feedrate (mm/m) = max_feedrate (mm/s)
  2018. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2019. if (marlin_debug_flags & DEBUG_LEVELING) {
  2020. SERIAL_ECHOPAIR("Raise Z (before homing) to ", (float)(MIN_Z_HEIGHT_FOR_HOMING));
  2021. SERIAL_EOL;
  2022. print_xyz("> (home_all_axis || homeZ) > current_position", current_position);
  2023. print_xyz("> (home_all_axis || homeZ) > destination", destination);
  2024. }
  2025. #endif
  2026. line_to_destination();
  2027. st_synchronize();
  2028. // Update the current Z position even if it currently not real from Z-home
  2029. // otherwise each call to line_to_destination() will want to move Z-axis
  2030. // by MIN_Z_HEIGHT_FOR_HOMING.
  2031. current_position[Z_AXIS] = destination[Z_AXIS];
  2032. }
  2033. #endif
  2034. #if ENABLED(QUICK_HOME)
  2035. if (home_all_axis || (homeX && homeY)) { // First diagonal move
  2036. current_position[X_AXIS] = current_position[Y_AXIS] = 0;
  2037. #if ENABLED(DUAL_X_CARRIAGE)
  2038. int x_axis_home_dir = x_home_dir(active_extruder);
  2039. extruder_duplication_enabled = false;
  2040. #else
  2041. int x_axis_home_dir = home_dir(X_AXIS);
  2042. #endif
  2043. sync_plan_position();
  2044. float mlx = max_length(X_AXIS), mly = max_length(Y_AXIS),
  2045. mlratio = mlx > mly ? mly / mlx : mlx / mly;
  2046. destination[X_AXIS] = 1.5 * mlx * x_axis_home_dir;
  2047. destination[Y_AXIS] = 1.5 * mly * home_dir(Y_AXIS);
  2048. feedrate = min(homing_feedrate[X_AXIS], homing_feedrate[Y_AXIS]) * sqrt(mlratio * mlratio + 1);
  2049. line_to_destination();
  2050. st_synchronize();
  2051. set_axis_is_at_home(X_AXIS);
  2052. set_axis_is_at_home(Y_AXIS);
  2053. sync_plan_position();
  2054. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2055. if (marlin_debug_flags & DEBUG_LEVELING) {
  2056. print_xyz("> QUICK_HOME > current_position 1", current_position);
  2057. }
  2058. #endif
  2059. destination[X_AXIS] = current_position[X_AXIS];
  2060. destination[Y_AXIS] = current_position[Y_AXIS];
  2061. line_to_destination();
  2062. feedrate = 0.0;
  2063. st_synchronize();
  2064. endstops_hit_on_purpose(); // clear endstop hit flags
  2065. current_position[X_AXIS] = destination[X_AXIS];
  2066. current_position[Y_AXIS] = destination[Y_AXIS];
  2067. #if DISABLED(SCARA)
  2068. current_position[Z_AXIS] = destination[Z_AXIS];
  2069. #endif
  2070. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2071. if (marlin_debug_flags & DEBUG_LEVELING) {
  2072. print_xyz("> QUICK_HOME > current_position 2", current_position);
  2073. }
  2074. #endif
  2075. }
  2076. #endif // QUICK_HOME
  2077. #if ENABLED(HOME_Y_BEFORE_X)
  2078. // Home Y
  2079. if (home_all_axis || homeY) HOMEAXIS(Y);
  2080. #endif
  2081. // Home X
  2082. if (home_all_axis || homeX) {
  2083. #if ENABLED(DUAL_X_CARRIAGE)
  2084. int tmp_extruder = active_extruder;
  2085. extruder_duplication_enabled = false;
  2086. active_extruder = !active_extruder;
  2087. HOMEAXIS(X);
  2088. inactive_extruder_x_pos = current_position[X_AXIS];
  2089. active_extruder = tmp_extruder;
  2090. HOMEAXIS(X);
  2091. // reset state used by the different modes
  2092. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  2093. delayed_move_time = 0;
  2094. active_extruder_parked = true;
  2095. #else
  2096. HOMEAXIS(X);
  2097. #endif
  2098. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2099. if (marlin_debug_flags & DEBUG_LEVELING) {
  2100. print_xyz("> homeX", current_position);
  2101. }
  2102. #endif
  2103. }
  2104. #if DISABLED(HOME_Y_BEFORE_X)
  2105. // Home Y
  2106. if (home_all_axis || homeY) {
  2107. HOMEAXIS(Y);
  2108. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2109. if (marlin_debug_flags & DEBUG_LEVELING) {
  2110. print_xyz("> homeY", current_position);
  2111. }
  2112. #endif
  2113. }
  2114. #endif
  2115. // Home Z last if homing towards the bed
  2116. #if Z_HOME_DIR < 0
  2117. if (home_all_axis || homeZ) {
  2118. #if ENABLED(Z_SAFE_HOMING)
  2119. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2120. if (marlin_debug_flags & DEBUG_LEVELING) {
  2121. SERIAL_ECHOLNPGM("> Z_SAFE_HOMING >>>");
  2122. }
  2123. #endif
  2124. if (home_all_axis) {
  2125. // At this point we already have Z at MIN_Z_HEIGHT_FOR_HOMING height
  2126. // No need to move Z any more as this height should already be safe
  2127. // enough to reach Z_SAFE_HOMING XY positions.
  2128. // Just make sure the planner is in sync.
  2129. sync_plan_position();
  2130. //
  2131. // Set the Z probe (or just the nozzle) destination to the safe homing point
  2132. //
  2133. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - (X_PROBE_OFFSET_FROM_EXTRUDER));
  2134. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  2135. destination[Z_AXIS] = current_position[Z_AXIS]; //z is already at the right height
  2136. feedrate = XY_TRAVEL_SPEED;
  2137. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2138. if (marlin_debug_flags & DEBUG_LEVELING) {
  2139. print_xyz("> Z_SAFE_HOMING > home_all_axis > current_position", current_position);
  2140. print_xyz("> Z_SAFE_HOMING > home_all_axis > destination", destination);
  2141. }
  2142. #endif
  2143. // Move in the XY plane
  2144. line_to_destination();
  2145. st_synchronize();
  2146. // Update the current positions for XY, Z is still at least at
  2147. // MIN_Z_HEIGHT_FOR_HOMING height, no changes there.
  2148. current_position[X_AXIS] = destination[X_AXIS];
  2149. current_position[Y_AXIS] = destination[Y_AXIS];
  2150. // Home the Z axis
  2151. HOMEAXIS(Z);
  2152. }
  2153. else if (homeZ) { // Don't need to Home Z twice
  2154. // Let's see if X and Y are homed
  2155. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  2156. // Make sure the Z probe is within the physical limits
  2157. // NOTE: This doesn't necessarily ensure the Z probe is also within the bed!
  2158. float cpx = current_position[X_AXIS], cpy = current_position[Y_AXIS];
  2159. if ( cpx >= X_MIN_POS - (X_PROBE_OFFSET_FROM_EXTRUDER)
  2160. && cpx <= X_MAX_POS - (X_PROBE_OFFSET_FROM_EXTRUDER)
  2161. && cpy >= Y_MIN_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)
  2162. && cpy <= Y_MAX_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)) {
  2163. // Home the Z axis
  2164. HOMEAXIS(Z);
  2165. }
  2166. else {
  2167. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  2168. SERIAL_ECHO_START;
  2169. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  2170. }
  2171. }
  2172. else {
  2173. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  2174. SERIAL_ECHO_START;
  2175. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  2176. }
  2177. } // !home_all_axes && homeZ
  2178. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2179. if (marlin_debug_flags & DEBUG_LEVELING) {
  2180. SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  2181. }
  2182. #endif
  2183. #else // !Z_SAFE_HOMING
  2184. HOMEAXIS(Z);
  2185. #endif // !Z_SAFE_HOMING
  2186. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2187. if (marlin_debug_flags & DEBUG_LEVELING) {
  2188. print_xyz("> (home_all_axis || homeZ) > final", current_position);
  2189. }
  2190. #endif
  2191. } // home_all_axis || homeZ
  2192. #endif // Z_HOME_DIR < 0
  2193. sync_plan_position();
  2194. #endif // else DELTA
  2195. #if ENABLED(SCARA)
  2196. sync_plan_position_delta();
  2197. #endif
  2198. #if ENABLED(ENDSTOPS_ONLY_FOR_HOMING)
  2199. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2200. if (marlin_debug_flags & DEBUG_LEVELING) {
  2201. SERIAL_ECHOLNPGM("ENDSTOPS_ONLY_FOR_HOMING enable_endstops(false)");
  2202. }
  2203. #endif
  2204. enable_endstops(false);
  2205. #endif
  2206. // For manual leveling move back to 0,0
  2207. #if ENABLED(MESH_BED_LEVELING)
  2208. if (mbl_was_active) {
  2209. current_position[X_AXIS] = mbl.get_x(0);
  2210. current_position[Y_AXIS] = mbl.get_y(0);
  2211. set_destination_to_current();
  2212. feedrate = homing_feedrate[X_AXIS];
  2213. line_to_destination();
  2214. st_synchronize();
  2215. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2216. sync_plan_position();
  2217. mbl.active = 1;
  2218. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2219. if (marlin_debug_flags & DEBUG_LEVELING) {
  2220. print_xyz("mbl_was_active > current_position", current_position);
  2221. }
  2222. #endif
  2223. }
  2224. #endif
  2225. feedrate = saved_feedrate;
  2226. feedrate_multiplier = saved_feedrate_multiplier;
  2227. refresh_cmd_timeout();
  2228. endstops_hit_on_purpose(); // clear endstop hit flags
  2229. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2230. if (marlin_debug_flags & DEBUG_LEVELING) {
  2231. SERIAL_ECHOLNPGM("<<< gcode_G28");
  2232. }
  2233. #endif
  2234. }
  2235. #if ENABLED(MESH_BED_LEVELING)
  2236. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  2237. /**
  2238. * G29: Mesh-based Z probe, probes a grid and produces a
  2239. * mesh to compensate for variable bed height
  2240. *
  2241. * Parameters With MESH_BED_LEVELING:
  2242. *
  2243. * S0 Produce a mesh report
  2244. * S1 Start probing mesh points
  2245. * S2 Probe the next mesh point
  2246. * S3 Xn Yn Zn.nn Manually modify a single point
  2247. *
  2248. * The S0 report the points as below
  2249. *
  2250. * +----> X-axis
  2251. * |
  2252. * |
  2253. * v Y-axis
  2254. *
  2255. */
  2256. inline void gcode_G29() {
  2257. static int probe_point = -1;
  2258. MeshLevelingState state = code_seen('S') ? (MeshLevelingState)code_value_short() : MeshReport;
  2259. if (state < 0 || state > 3) {
  2260. SERIAL_PROTOCOLLNPGM("S out of range (0-3).");
  2261. return;
  2262. }
  2263. int ix, iy;
  2264. float z;
  2265. switch (state) {
  2266. case MeshReport:
  2267. if (mbl.active) {
  2268. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2269. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2270. SERIAL_PROTOCOLCHAR(',');
  2271. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2272. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2273. SERIAL_PROTOCOL(MESH_HOME_SEARCH_Z);
  2274. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2275. for (int y = 0; y < MESH_NUM_Y_POINTS; y++) {
  2276. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2277. SERIAL_PROTOCOLPGM(" ");
  2278. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2279. }
  2280. SERIAL_EOL;
  2281. }
  2282. }
  2283. else
  2284. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  2285. break;
  2286. case MeshStart:
  2287. mbl.reset();
  2288. probe_point = 0;
  2289. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  2290. break;
  2291. case MeshNext:
  2292. if (probe_point < 0) {
  2293. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  2294. return;
  2295. }
  2296. if (probe_point == 0) {
  2297. // Set Z to a positive value before recording the first Z.
  2298. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2299. sync_plan_position();
  2300. }
  2301. else {
  2302. // For others, save the Z of the previous point, then raise Z again.
  2303. ix = (probe_point - 1) % (MESH_NUM_X_POINTS);
  2304. iy = (probe_point - 1) / (MESH_NUM_X_POINTS);
  2305. if (iy & 1) ix = (MESH_NUM_X_POINTS - 1) - ix; // zig-zag
  2306. mbl.set_z(ix, iy, current_position[Z_AXIS]);
  2307. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2308. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS] / 60, active_extruder);
  2309. st_synchronize();
  2310. }
  2311. // Is there another point to sample? Move there.
  2312. if (probe_point < (MESH_NUM_X_POINTS) * (MESH_NUM_Y_POINTS)) {
  2313. ix = probe_point % (MESH_NUM_X_POINTS);
  2314. iy = probe_point / (MESH_NUM_X_POINTS);
  2315. if (iy & 1) ix = (MESH_NUM_X_POINTS - 1) - ix; // zig-zag
  2316. current_position[X_AXIS] = mbl.get_x(ix);
  2317. current_position[Y_AXIS] = mbl.get_y(iy);
  2318. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS] / 60, active_extruder);
  2319. st_synchronize();
  2320. probe_point++;
  2321. }
  2322. else {
  2323. // After recording the last point, activate the mbl and home
  2324. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  2325. probe_point = -1;
  2326. mbl.active = 1;
  2327. enqueue_and_echo_commands_P(PSTR("G28"));
  2328. }
  2329. break;
  2330. case MeshSet:
  2331. if (code_seen('X')) {
  2332. ix = code_value_long() - 1;
  2333. if (ix < 0 || ix >= MESH_NUM_X_POINTS) {
  2334. SERIAL_PROTOCOLPGM("X out of range (1-" STRINGIFY(MESH_NUM_X_POINTS) ").\n");
  2335. return;
  2336. }
  2337. }
  2338. else {
  2339. SERIAL_PROTOCOLPGM("X not entered.\n");
  2340. return;
  2341. }
  2342. if (code_seen('Y')) {
  2343. iy = code_value_long() - 1;
  2344. if (iy < 0 || iy >= MESH_NUM_Y_POINTS) {
  2345. SERIAL_PROTOCOLPGM("Y out of range (1-" STRINGIFY(MESH_NUM_Y_POINTS) ").\n");
  2346. return;
  2347. }
  2348. }
  2349. else {
  2350. SERIAL_PROTOCOLPGM("Y not entered.\n");
  2351. return;
  2352. }
  2353. if (code_seen('Z')) {
  2354. z = code_value();
  2355. }
  2356. else {
  2357. SERIAL_PROTOCOLPGM("Z not entered.\n");
  2358. return;
  2359. }
  2360. mbl.z_values[iy][ix] = z;
  2361. } // switch(state)
  2362. }
  2363. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  2364. void out_of_range_error(const char* p_edge) {
  2365. SERIAL_PROTOCOLPGM("?Probe ");
  2366. serialprintPGM(p_edge);
  2367. SERIAL_PROTOCOLLNPGM(" position out of range.");
  2368. }
  2369. /**
  2370. * G29: Detailed Z probe, probes the bed at 3 or more points.
  2371. * Will fail if the printer has not been homed with G28.
  2372. *
  2373. * Enhanced G29 Auto Bed Leveling Probe Routine
  2374. *
  2375. * Parameters With AUTO_BED_LEVELING_GRID:
  2376. *
  2377. * P Set the size of the grid that will be probed (P x P points).
  2378. * Not supported by non-linear delta printer bed leveling.
  2379. * Example: "G29 P4"
  2380. *
  2381. * S Set the XY travel speed between probe points (in mm/min)
  2382. *
  2383. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  2384. * or clean the rotation Matrix. Useful to check the topology
  2385. * after a first run of G29.
  2386. *
  2387. * V Set the verbose level (0-4). Example: "G29 V3"
  2388. *
  2389. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  2390. * This is useful for manual bed leveling and finding flaws in the bed (to
  2391. * assist with part placement).
  2392. * Not supported by non-linear delta printer bed leveling.
  2393. *
  2394. * F Set the Front limit of the probing grid
  2395. * B Set the Back limit of the probing grid
  2396. * L Set the Left limit of the probing grid
  2397. * R Set the Right limit of the probing grid
  2398. *
  2399. * Global Parameters:
  2400. *
  2401. * E/e By default G29 will engage the Z probe, test the bed, then disengage.
  2402. * Include "E" to engage/disengage the Z probe for each sample.
  2403. * There's no extra effect if you have a fixed Z probe.
  2404. * Usage: "G29 E" or "G29 e"
  2405. *
  2406. */
  2407. inline void gcode_G29() {
  2408. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2409. if (marlin_debug_flags & DEBUG_LEVELING) {
  2410. SERIAL_ECHOLNPGM("gcode_G29 >>>");
  2411. }
  2412. #endif
  2413. // Don't allow auto-leveling without homing first
  2414. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  2415. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  2416. SERIAL_ECHO_START;
  2417. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  2418. return;
  2419. }
  2420. int verbose_level = code_seen('V') ? code_value_short() : 1;
  2421. if (verbose_level < 0 || verbose_level > 4) {
  2422. SERIAL_ECHOLNPGM("?(V)erbose Level is implausible (0-4).");
  2423. return;
  2424. }
  2425. bool dryrun = code_seen('D'),
  2426. deploy_probe_for_each_reading = code_seen('E');
  2427. #if ENABLED(AUTO_BED_LEVELING_GRID)
  2428. #if DISABLED(DELTA)
  2429. bool do_topography_map = verbose_level > 2 || code_seen('T');
  2430. #endif
  2431. if (verbose_level > 0) {
  2432. SERIAL_PROTOCOLPGM("G29 Auto Bed Leveling\n");
  2433. if (dryrun) SERIAL_ECHOLNPGM("Running in DRY-RUN mode");
  2434. }
  2435. int auto_bed_leveling_grid_points = AUTO_BED_LEVELING_GRID_POINTS;
  2436. #if DISABLED(DELTA)
  2437. if (code_seen('P')) auto_bed_leveling_grid_points = code_value_short();
  2438. if (auto_bed_leveling_grid_points < 2) {
  2439. SERIAL_PROTOCOLPGM("?Number of probed (P)oints is implausible (2 minimum).\n");
  2440. return;
  2441. }
  2442. #endif
  2443. xy_travel_speed = code_seen('S') ? code_value_short() : XY_TRAVEL_SPEED;
  2444. int left_probe_bed_position = code_seen('L') ? code_value_short() : LEFT_PROBE_BED_POSITION,
  2445. right_probe_bed_position = code_seen('R') ? code_value_short() : RIGHT_PROBE_BED_POSITION,
  2446. front_probe_bed_position = code_seen('F') ? code_value_short() : FRONT_PROBE_BED_POSITION,
  2447. back_probe_bed_position = code_seen('B') ? code_value_short() : BACK_PROBE_BED_POSITION;
  2448. bool left_out_l = left_probe_bed_position < MIN_PROBE_X,
  2449. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  2450. right_out_r = right_probe_bed_position > MAX_PROBE_X,
  2451. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  2452. front_out_f = front_probe_bed_position < MIN_PROBE_Y,
  2453. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  2454. back_out_b = back_probe_bed_position > MAX_PROBE_Y,
  2455. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  2456. if (left_out || right_out || front_out || back_out) {
  2457. if (left_out) {
  2458. out_of_range_error(PSTR("(L)eft"));
  2459. left_probe_bed_position = left_out_l ? MIN_PROBE_X : right_probe_bed_position - (MIN_PROBE_EDGE);
  2460. }
  2461. if (right_out) {
  2462. out_of_range_error(PSTR("(R)ight"));
  2463. right_probe_bed_position = right_out_r ? MAX_PROBE_X : left_probe_bed_position + MIN_PROBE_EDGE;
  2464. }
  2465. if (front_out) {
  2466. out_of_range_error(PSTR("(F)ront"));
  2467. front_probe_bed_position = front_out_f ? MIN_PROBE_Y : back_probe_bed_position - (MIN_PROBE_EDGE);
  2468. }
  2469. if (back_out) {
  2470. out_of_range_error(PSTR("(B)ack"));
  2471. back_probe_bed_position = back_out_b ? MAX_PROBE_Y : front_probe_bed_position + MIN_PROBE_EDGE;
  2472. }
  2473. return;
  2474. }
  2475. #endif // AUTO_BED_LEVELING_GRID
  2476. #if ENABLED(Z_PROBE_SLED)
  2477. dock_sled(false); // engage (un-dock) the Z probe
  2478. #elif ENABLED(Z_PROBE_ALLEN_KEY) //|| SERVO_LEVELING
  2479. deploy_z_probe();
  2480. #endif
  2481. st_synchronize();
  2482. if (!dryrun) {
  2483. // make sure the bed_level_rotation_matrix is identity or the planner will get it wrong
  2484. plan_bed_level_matrix.set_to_identity();
  2485. #if ENABLED(DELTA)
  2486. reset_bed_level();
  2487. #else //!DELTA
  2488. //vector_3 corrected_position = plan_get_position_mm();
  2489. //corrected_position.debug("position before G29");
  2490. vector_3 uncorrected_position = plan_get_position();
  2491. //uncorrected_position.debug("position during G29");
  2492. current_position[X_AXIS] = uncorrected_position.x;
  2493. current_position[Y_AXIS] = uncorrected_position.y;
  2494. current_position[Z_AXIS] = uncorrected_position.z;
  2495. sync_plan_position();
  2496. #endif // !DELTA
  2497. }
  2498. setup_for_endstop_move();
  2499. feedrate = homing_feedrate[Z_AXIS];
  2500. #if ENABLED(AUTO_BED_LEVELING_GRID)
  2501. // probe at the points of a lattice grid
  2502. const int xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (auto_bed_leveling_grid_points - 1),
  2503. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (auto_bed_leveling_grid_points - 1);
  2504. #if ENABLED(DELTA)
  2505. delta_grid_spacing[0] = xGridSpacing;
  2506. delta_grid_spacing[1] = yGridSpacing;
  2507. float z_offset = zprobe_zoffset;
  2508. if (code_seen(axis_codes[Z_AXIS])) z_offset += code_value();
  2509. #else // !DELTA
  2510. // solve the plane equation ax + by + d = z
  2511. // A is the matrix with rows [x y 1] for all the probed points
  2512. // B is the vector of the Z positions
  2513. // the normal vector to the plane is formed by the coefficients of the plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  2514. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  2515. int abl2 = auto_bed_leveling_grid_points * auto_bed_leveling_grid_points;
  2516. double eqnAMatrix[abl2 * 3], // "A" matrix of the linear system of equations
  2517. eqnBVector[abl2], // "B" vector of Z points
  2518. mean = 0.0;
  2519. int8_t indexIntoAB[auto_bed_leveling_grid_points][auto_bed_leveling_grid_points];
  2520. #endif // !DELTA
  2521. int probePointCounter = 0;
  2522. bool zig = (auto_bed_leveling_grid_points & 1) ? true : false; //always end at [RIGHT_PROBE_BED_POSITION, BACK_PROBE_BED_POSITION]
  2523. for (int yCount = 0; yCount < auto_bed_leveling_grid_points; yCount++) {
  2524. double yProbe = front_probe_bed_position + yGridSpacing * yCount;
  2525. int xStart, xStop, xInc;
  2526. if (zig) {
  2527. xStart = 0;
  2528. xStop = auto_bed_leveling_grid_points;
  2529. xInc = 1;
  2530. }
  2531. else {
  2532. xStart = auto_bed_leveling_grid_points - 1;
  2533. xStop = -1;
  2534. xInc = -1;
  2535. }
  2536. zig = !zig;
  2537. for (int xCount = xStart; xCount != xStop; xCount += xInc) {
  2538. double xProbe = left_probe_bed_position + xGridSpacing * xCount;
  2539. // raise extruder
  2540. float measured_z,
  2541. z_before = probePointCounter ? Z_RAISE_BETWEEN_PROBINGS + current_position[Z_AXIS] : Z_RAISE_BEFORE_PROBING;
  2542. if (probePointCounter) {
  2543. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2544. if (marlin_debug_flags & DEBUG_LEVELING) {
  2545. SERIAL_ECHOPAIR("z_before = (between) ", (float)(Z_RAISE_BETWEEN_PROBINGS + current_position[Z_AXIS]));
  2546. SERIAL_EOL;
  2547. }
  2548. #endif
  2549. }
  2550. else {
  2551. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2552. if (marlin_debug_flags & DEBUG_LEVELING) {
  2553. SERIAL_ECHOPAIR("z_before = (before) ", (float)Z_RAISE_BEFORE_PROBING);
  2554. SERIAL_EOL;
  2555. }
  2556. #endif
  2557. }
  2558. #if ENABLED(DELTA)
  2559. // Avoid probing the corners (outside the round or hexagon print surface) on a delta printer.
  2560. float distance_from_center = sqrt(xProbe * xProbe + yProbe * yProbe);
  2561. if (distance_from_center > DELTA_PROBABLE_RADIUS) continue;
  2562. #endif //DELTA
  2563. ProbeAction act;
  2564. if (deploy_probe_for_each_reading) // G29 E - Stow between probes
  2565. act = ProbeDeployAndStow;
  2566. else if (yCount == 0 && xCount == xStart)
  2567. act = ProbeDeploy;
  2568. else if (yCount == auto_bed_leveling_grid_points - 1 && xCount == xStop - xInc)
  2569. act = ProbeStow;
  2570. else
  2571. act = ProbeStay;
  2572. measured_z = probe_pt(xProbe, yProbe, z_before, act, verbose_level);
  2573. #if DISABLED(DELTA)
  2574. mean += measured_z;
  2575. eqnBVector[probePointCounter] = measured_z;
  2576. eqnAMatrix[probePointCounter + 0 * abl2] = xProbe;
  2577. eqnAMatrix[probePointCounter + 1 * abl2] = yProbe;
  2578. eqnAMatrix[probePointCounter + 2 * abl2] = 1;
  2579. indexIntoAB[xCount][yCount] = probePointCounter;
  2580. #else
  2581. bed_level[xCount][yCount] = measured_z + z_offset;
  2582. #endif
  2583. probePointCounter++;
  2584. idle();
  2585. } //xProbe
  2586. } //yProbe
  2587. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2588. if (marlin_debug_flags & DEBUG_LEVELING) {
  2589. print_xyz("> probing complete > current_position", current_position);
  2590. }
  2591. #endif
  2592. clean_up_after_endstop_move();
  2593. #if ENABLED(DELTA)
  2594. if (!dryrun) extrapolate_unprobed_bed_level();
  2595. print_bed_level();
  2596. #else // !DELTA
  2597. // solve lsq problem
  2598. double plane_equation_coefficients[3];
  2599. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  2600. mean /= abl2;
  2601. if (verbose_level) {
  2602. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  2603. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  2604. SERIAL_PROTOCOLPGM(" b: ");
  2605. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  2606. SERIAL_PROTOCOLPGM(" d: ");
  2607. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  2608. SERIAL_EOL;
  2609. if (verbose_level > 2) {
  2610. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  2611. SERIAL_PROTOCOL_F(mean, 8);
  2612. SERIAL_EOL;
  2613. }
  2614. }
  2615. if (!dryrun) set_bed_level_equation_lsq(plane_equation_coefficients);
  2616. // Show the Topography map if enabled
  2617. if (do_topography_map) {
  2618. SERIAL_PROTOCOLPGM(" \nBed Height Topography: \n");
  2619. SERIAL_PROTOCOLPGM(" +--- BACK --+\n");
  2620. SERIAL_PROTOCOLPGM(" | |\n");
  2621. SERIAL_PROTOCOLPGM(" L | (+) | R\n");
  2622. SERIAL_PROTOCOLPGM(" E | | I\n");
  2623. SERIAL_PROTOCOLPGM(" F | (-) N (+) | G\n");
  2624. SERIAL_PROTOCOLPGM(" T | | H\n");
  2625. SERIAL_PROTOCOLPGM(" | (-) | T\n");
  2626. SERIAL_PROTOCOLPGM(" | |\n");
  2627. SERIAL_PROTOCOLPGM(" O-- FRONT --+\n");
  2628. SERIAL_PROTOCOLPGM(" (0,0)\n");
  2629. float min_diff = 999;
  2630. for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) {
  2631. for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) {
  2632. int ind = indexIntoAB[xx][yy];
  2633. float diff = eqnBVector[ind] - mean;
  2634. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  2635. y_tmp = eqnAMatrix[ind + 1 * abl2],
  2636. z_tmp = 0;
  2637. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp);
  2638. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  2639. if (diff >= 0.0)
  2640. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  2641. else
  2642. SERIAL_PROTOCOLCHAR(' ');
  2643. SERIAL_PROTOCOL_F(diff, 5);
  2644. } // xx
  2645. SERIAL_EOL;
  2646. } // yy
  2647. SERIAL_EOL;
  2648. if (verbose_level > 3) {
  2649. SERIAL_PROTOCOLPGM(" \nCorrected Bed Height vs. Bed Topology: \n");
  2650. for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) {
  2651. for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) {
  2652. int ind = indexIntoAB[xx][yy];
  2653. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  2654. y_tmp = eqnAMatrix[ind + 1 * abl2],
  2655. z_tmp = 0;
  2656. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp);
  2657. float diff = eqnBVector[ind] - z_tmp - min_diff;
  2658. if (diff >= 0.0)
  2659. SERIAL_PROTOCOLPGM(" +");
  2660. // Include + for column alignment
  2661. else
  2662. SERIAL_PROTOCOLCHAR(' ');
  2663. SERIAL_PROTOCOL_F(diff, 5);
  2664. } // xx
  2665. SERIAL_EOL;
  2666. } // yy
  2667. SERIAL_EOL;
  2668. }
  2669. } //do_topography_map
  2670. #endif //!DELTA
  2671. #else // !AUTO_BED_LEVELING_GRID
  2672. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2673. if (marlin_debug_flags & DEBUG_LEVELING) {
  2674. SERIAL_ECHOLNPGM("> 3-point Leveling");
  2675. }
  2676. #endif
  2677. // Actions for each probe
  2678. ProbeAction p1, p2, p3;
  2679. if (deploy_probe_for_each_reading)
  2680. p1 = p2 = p3 = ProbeDeployAndStow;
  2681. else
  2682. p1 = ProbeDeploy, p2 = ProbeStay, p3 = ProbeStow;
  2683. // Probe at 3 arbitrary points
  2684. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING, p1, verbose_level),
  2685. z_at_pt_2 = probe_pt(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS, p2, verbose_level),
  2686. z_at_pt_3 = probe_pt(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS, p3, verbose_level);
  2687. clean_up_after_endstop_move();
  2688. if (!dryrun) set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  2689. #endif // !AUTO_BED_LEVELING_GRID
  2690. #if ENABLED(DELTA)
  2691. // Allen Key Probe for Delta
  2692. #if ENABLED(Z_PROBE_ALLEN_KEY)
  2693. stow_z_probe();
  2694. #elif Z_RAISE_AFTER_PROBING > 0
  2695. raise_z_after_probing();
  2696. #endif
  2697. #else // !DELTA
  2698. if (verbose_level > 0)
  2699. plan_bed_level_matrix.debug(" \n\nBed Level Correction Matrix:");
  2700. if (!dryrun) {
  2701. // Correct the Z height difference from Z probe position and nozzle tip position.
  2702. // The Z height on homing is measured by Z probe, but the Z probe is quite far from the nozzle.
  2703. // When the bed is uneven, this height must be corrected.
  2704. float x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  2705. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER,
  2706. z_tmp = current_position[Z_AXIS],
  2707. real_z = st_get_axis_position_mm(Z_AXIS); //get the real Z (since plan_get_position is now correcting the plane)
  2708. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2709. if (marlin_debug_flags & DEBUG_LEVELING) {
  2710. SERIAL_ECHOPAIR("> BEFORE apply_rotation_xyz > z_tmp = ", z_tmp);
  2711. SERIAL_EOL;
  2712. SERIAL_ECHOPAIR("> BEFORE apply_rotation_xyz > real_z = ", real_z);
  2713. SERIAL_EOL;
  2714. }
  2715. #endif
  2716. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); // Apply the correction sending the Z probe offset
  2717. // Get the current Z position and send it to the planner.
  2718. //
  2719. // >> (z_tmp - real_z) : The rotated current Z minus the uncorrected Z (most recent plan_set_position/sync_plan_position)
  2720. //
  2721. // >> zprobe_zoffset : Z distance from nozzle to Z probe (set by default, M851, EEPROM, or Menu)
  2722. //
  2723. // >> Z_RAISE_AFTER_PROBING : The distance the Z probe will have lifted after the last probe
  2724. //
  2725. // >> Should home_offset[Z_AXIS] be included?
  2726. //
  2727. // Discussion: home_offset[Z_AXIS] was applied in G28 to set the starting Z.
  2728. // If Z is not tweaked in G29 -and- the Z probe in G29 is not actually "homing" Z...
  2729. // then perhaps it should not be included here. The purpose of home_offset[] is to
  2730. // adjust for inaccurate endstops, not for reasonably accurate probes. If it were
  2731. // added here, it could be seen as a compensating factor for the Z probe.
  2732. //
  2733. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2734. if (marlin_debug_flags & DEBUG_LEVELING) {
  2735. SERIAL_ECHOPAIR("> AFTER apply_rotation_xyz > z_tmp = ", z_tmp);
  2736. SERIAL_EOL;
  2737. }
  2738. #endif
  2739. current_position[Z_AXIS] = -zprobe_zoffset + (z_tmp - real_z)
  2740. #if HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED)
  2741. + Z_RAISE_AFTER_PROBING
  2742. #endif
  2743. ;
  2744. // current_position[Z_AXIS] += home_offset[Z_AXIS]; // The Z probe determines Z=0, not "Z home"
  2745. sync_plan_position();
  2746. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2747. if (marlin_debug_flags & DEBUG_LEVELING) {
  2748. print_xyz("> corrected Z in G29", current_position);
  2749. }
  2750. #endif
  2751. }
  2752. // Sled assembly for Cartesian bots
  2753. #if ENABLED(Z_PROBE_SLED)
  2754. dock_sled(true); // dock the sled
  2755. #elif Z_RAISE_AFTER_PROBING > 0
  2756. // Raise Z axis for non-delta and non servo based probes
  2757. #if !defined(HAS_SERVO_ENDSTOPS) && DISABLED(Z_PROBE_ALLEN_KEY) && DISABLED(Z_PROBE_SLED)
  2758. raise_z_after_probing();
  2759. #endif
  2760. #endif
  2761. #endif // !DELTA
  2762. #ifdef Z_PROBE_END_SCRIPT
  2763. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2764. if (marlin_debug_flags & DEBUG_LEVELING) {
  2765. SERIAL_ECHO("Z Probe End Script: ");
  2766. SERIAL_ECHOLNPGM(Z_PROBE_END_SCRIPT);
  2767. }
  2768. #endif
  2769. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  2770. st_synchronize();
  2771. #endif
  2772. KEEPALIVE_STATE(IN_HANDLER);
  2773. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2774. if (marlin_debug_flags & DEBUG_LEVELING) {
  2775. SERIAL_ECHOLNPGM("<<< gcode_G29");
  2776. }
  2777. #endif
  2778. }
  2779. #if DISABLED(Z_PROBE_SLED)
  2780. /**
  2781. * G30: Do a single Z probe at the current XY
  2782. */
  2783. inline void gcode_G30() {
  2784. #if HAS_SERVO_ENDSTOPS
  2785. raise_z_for_servo();
  2786. #endif
  2787. deploy_z_probe(); // Engage Z Servo endstop if available
  2788. st_synchronize();
  2789. // TODO: clear the leveling matrix or the planner will be set incorrectly
  2790. setup_for_endstop_move();
  2791. feedrate = homing_feedrate[Z_AXIS];
  2792. run_z_probe();
  2793. SERIAL_PROTOCOLPGM("Bed X: ");
  2794. SERIAL_PROTOCOL(current_position[X_AXIS] + 0.0001);
  2795. SERIAL_PROTOCOLPGM(" Y: ");
  2796. SERIAL_PROTOCOL(current_position[Y_AXIS] + 0.0001);
  2797. SERIAL_PROTOCOLPGM(" Z: ");
  2798. SERIAL_PROTOCOL(current_position[Z_AXIS] + 0.0001);
  2799. SERIAL_EOL;
  2800. clean_up_after_endstop_move();
  2801. #if HAS_SERVO_ENDSTOPS
  2802. raise_z_for_servo();
  2803. #endif
  2804. stow_z_probe(false); // Retract Z Servo endstop if available
  2805. }
  2806. #endif //!Z_PROBE_SLED
  2807. #endif //AUTO_BED_LEVELING_FEATURE
  2808. /**
  2809. * G92: Set current position to given X Y Z E
  2810. */
  2811. inline void gcode_G92() {
  2812. if (!code_seen(axis_codes[E_AXIS]))
  2813. st_synchronize();
  2814. bool didXYZ = false;
  2815. for (int i = 0; i < NUM_AXIS; i++) {
  2816. if (code_seen(axis_codes[i])) {
  2817. float v = current_position[i] = code_value();
  2818. if (i == E_AXIS)
  2819. plan_set_e_position(v);
  2820. else
  2821. didXYZ = true;
  2822. }
  2823. }
  2824. if (didXYZ) {
  2825. #if ENABLED(DELTA) || ENABLED(SCARA)
  2826. sync_plan_position_delta();
  2827. #else
  2828. sync_plan_position();
  2829. #endif
  2830. }
  2831. }
  2832. #if ENABLED(ULTIPANEL)
  2833. /**
  2834. * M0: // M0 - Unconditional stop - Wait for user button press on LCD
  2835. * M1: // M1 - Conditional stop - Wait for user button press on LCD
  2836. */
  2837. inline void gcode_M0_M1() {
  2838. char* args = current_command_args;
  2839. millis_t codenum = 0;
  2840. bool hasP = false, hasS = false;
  2841. if (code_seen('P')) {
  2842. codenum = code_value_short(); // milliseconds to wait
  2843. hasP = codenum > 0;
  2844. }
  2845. if (code_seen('S')) {
  2846. codenum = code_value() * 1000; // seconds to wait
  2847. hasS = codenum > 0;
  2848. }
  2849. if (!hasP && !hasS && *args != '\0')
  2850. lcd_setstatus(args, true);
  2851. else {
  2852. LCD_MESSAGEPGM(MSG_USERWAIT);
  2853. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  2854. dontExpireStatus();
  2855. #endif
  2856. }
  2857. lcd_ignore_click();
  2858. st_synchronize();
  2859. refresh_cmd_timeout();
  2860. if (codenum > 0) {
  2861. codenum += previous_cmd_ms; // wait until this time for a click
  2862. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2863. while (millis() < codenum && !lcd_clicked()) idle();
  2864. KEEPALIVE_STATE(IN_HANDLER);
  2865. lcd_ignore_click(false);
  2866. }
  2867. else {
  2868. if (!lcd_detected()) return;
  2869. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2870. while (!lcd_clicked()) idle();
  2871. KEEPALIVE_STATE(IN_HANDLER);
  2872. }
  2873. if (IS_SD_PRINTING)
  2874. LCD_MESSAGEPGM(MSG_RESUMING);
  2875. else
  2876. LCD_MESSAGEPGM(WELCOME_MSG);
  2877. }
  2878. #endif // ULTIPANEL
  2879. /**
  2880. * M17: Enable power on all stepper motors
  2881. */
  2882. inline void gcode_M17() {
  2883. LCD_MESSAGEPGM(MSG_NO_MOVE);
  2884. enable_all_steppers();
  2885. }
  2886. #if ENABLED(SDSUPPORT)
  2887. /**
  2888. * M20: List SD card to serial output
  2889. */
  2890. inline void gcode_M20() {
  2891. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  2892. card.ls();
  2893. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  2894. }
  2895. /**
  2896. * M21: Init SD Card
  2897. */
  2898. inline void gcode_M21() {
  2899. card.initsd();
  2900. }
  2901. /**
  2902. * M22: Release SD Card
  2903. */
  2904. inline void gcode_M22() {
  2905. card.release();
  2906. }
  2907. /**
  2908. * M23: Open a file
  2909. */
  2910. inline void gcode_M23() {
  2911. card.openFile(current_command_args, true);
  2912. }
  2913. /**
  2914. * M24: Start SD Print
  2915. */
  2916. inline void gcode_M24() {
  2917. card.startFileprint();
  2918. print_job_start_ms = millis();
  2919. }
  2920. /**
  2921. * M25: Pause SD Print
  2922. */
  2923. inline void gcode_M25() {
  2924. card.pauseSDPrint();
  2925. }
  2926. /**
  2927. * M26: Set SD Card file index
  2928. */
  2929. inline void gcode_M26() {
  2930. if (card.cardOK && code_seen('S'))
  2931. card.setIndex(code_value_short());
  2932. }
  2933. /**
  2934. * M27: Get SD Card status
  2935. */
  2936. inline void gcode_M27() {
  2937. card.getStatus();
  2938. }
  2939. /**
  2940. * M28: Start SD Write
  2941. */
  2942. inline void gcode_M28() {
  2943. card.openFile(current_command_args, false);
  2944. }
  2945. /**
  2946. * M29: Stop SD Write
  2947. * Processed in write to file routine above
  2948. */
  2949. inline void gcode_M29() {
  2950. // card.saving = false;
  2951. }
  2952. /**
  2953. * M30 <filename>: Delete SD Card file
  2954. */
  2955. inline void gcode_M30() {
  2956. if (card.cardOK) {
  2957. card.closefile();
  2958. card.removeFile(current_command_args);
  2959. }
  2960. }
  2961. #endif //SDSUPPORT
  2962. /**
  2963. * M31: Get the time since the start of SD Print (or last M109)
  2964. */
  2965. inline void gcode_M31() {
  2966. print_job_stop_ms = millis();
  2967. millis_t t = (print_job_stop_ms - print_job_start_ms) / 1000;
  2968. int min = t / 60, sec = t % 60;
  2969. char time[30];
  2970. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  2971. SERIAL_ECHO_START;
  2972. SERIAL_ECHOLN(time);
  2973. lcd_setstatus(time);
  2974. autotempShutdown();
  2975. }
  2976. #if ENABLED(SDSUPPORT)
  2977. /**
  2978. * M32: Select file and start SD Print
  2979. */
  2980. inline void gcode_M32() {
  2981. if (card.sdprinting)
  2982. st_synchronize();
  2983. char* namestartpos = strchr(current_command_args, '!'); // Find ! to indicate filename string start.
  2984. if (!namestartpos)
  2985. namestartpos = current_command_args; // Default name position, 4 letters after the M
  2986. else
  2987. namestartpos++; //to skip the '!'
  2988. bool call_procedure = code_seen('P') && (seen_pointer < namestartpos);
  2989. if (card.cardOK) {
  2990. card.openFile(namestartpos, true, !call_procedure);
  2991. if (code_seen('S') && seen_pointer < namestartpos) // "S" (must occur _before_ the filename!)
  2992. card.setIndex(code_value_short());
  2993. card.startFileprint();
  2994. if (!call_procedure)
  2995. print_job_start_ms = millis(); //procedure calls count as normal print time.
  2996. }
  2997. }
  2998. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  2999. /**
  3000. * M33: Get the long full path of a file or folder
  3001. *
  3002. * Parameters:
  3003. * <dospath> Case-insensitive DOS-style path to a file or folder
  3004. *
  3005. * Example:
  3006. * M33 miscel~1/armchair/armcha~1.gco
  3007. *
  3008. * Output:
  3009. * /Miscellaneous/Armchair/Armchair.gcode
  3010. */
  3011. inline void gcode_M33() {
  3012. card.printLongPath(current_command_args);
  3013. }
  3014. #endif
  3015. /**
  3016. * M928: Start SD Write
  3017. */
  3018. inline void gcode_M928() {
  3019. card.openLogFile(current_command_args);
  3020. }
  3021. #endif // SDSUPPORT
  3022. /**
  3023. * M42: Change pin status via GCode
  3024. *
  3025. * P<pin> Pin number (LED if omitted)
  3026. * S<byte> Pin status from 0 - 255
  3027. */
  3028. inline void gcode_M42() {
  3029. if (code_seen('S')) {
  3030. int pin_status = code_value_short();
  3031. if (pin_status < 0 || pin_status > 255) return;
  3032. int pin_number = code_seen('P') ? code_value_short() : LED_PIN;
  3033. if (pin_number < 0) return;
  3034. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  3035. if (pin_number == sensitive_pins[i]) return;
  3036. pinMode(pin_number, OUTPUT);
  3037. digitalWrite(pin_number, pin_status);
  3038. analogWrite(pin_number, pin_status);
  3039. #if FAN_COUNT > 0
  3040. switch (pin_number) {
  3041. #if HAS_FAN0
  3042. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  3043. #endif
  3044. #if HAS_FAN1
  3045. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  3046. #endif
  3047. #if HAS_FAN2
  3048. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  3049. #endif
  3050. }
  3051. #endif
  3052. } // code_seen('S')
  3053. }
  3054. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  3055. // This is redundant since the SanityCheck.h already checks for a valid Z_MIN_PROBE_PIN, but here for clarity.
  3056. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  3057. #if !HAS_Z_PROBE
  3058. #error You must define Z_MIN_PROBE_PIN to enable Z probe repeatability calculation.
  3059. #endif
  3060. #elif !HAS_Z_MIN
  3061. #error You must define Z_MIN_PIN to enable Z probe repeatability calculation.
  3062. #endif
  3063. /**
  3064. * M48: Z probe repeatability measurement function.
  3065. *
  3066. * Usage:
  3067. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  3068. * P = Number of sampled points (4-50, default 10)
  3069. * X = Sample X position
  3070. * Y = Sample Y position
  3071. * V = Verbose level (0-4, default=1)
  3072. * E = Engage Z probe for each reading
  3073. * L = Number of legs of movement before probe
  3074. * S = Schizoid (Or Star if you prefer)
  3075. *
  3076. * This function assumes the bed has been homed. Specifically, that a G28 command
  3077. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  3078. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  3079. * regenerated.
  3080. */
  3081. inline void gcode_M48() {
  3082. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS] || !axis_known_position[Z_AXIS]) {
  3083. unknown_position_error();
  3084. return;
  3085. }
  3086. double sum = 0.0, mean = 0.0, sigma = 0.0, sample_set[50];
  3087. uint8_t verbose_level = 1, n_samples = 10, n_legs = 0, schizoid_flag = 0;
  3088. if (code_seen('V')) {
  3089. verbose_level = code_value_short();
  3090. if (verbose_level < 0 || verbose_level > 4) {
  3091. SERIAL_PROTOCOLPGM("?Verbose Level not plausible (0-4).\n");
  3092. return;
  3093. }
  3094. }
  3095. if (verbose_level > 0)
  3096. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test\n");
  3097. if (code_seen('P')) {
  3098. n_samples = code_value_short();
  3099. if (n_samples < 4 || n_samples > 50) {
  3100. SERIAL_PROTOCOLPGM("?Sample size not plausible (4-50).\n");
  3101. return;
  3102. }
  3103. }
  3104. float X_current = current_position[X_AXIS],
  3105. Y_current = current_position[Y_AXIS],
  3106. Z_current = current_position[Z_AXIS],
  3107. X_probe_location = X_current + X_PROBE_OFFSET_FROM_EXTRUDER,
  3108. Y_probe_location = Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER,
  3109. Z_start_location = Z_current + Z_RAISE_BEFORE_PROBING;
  3110. bool deploy_probe_for_each_reading = code_seen('E');
  3111. if (code_seen('X')) {
  3112. X_probe_location = code_value();
  3113. #if DISABLED(DELTA)
  3114. if (X_probe_location < MIN_PROBE_X || X_probe_location > MAX_PROBE_X) {
  3115. out_of_range_error(PSTR("X"));
  3116. return;
  3117. }
  3118. #endif
  3119. }
  3120. if (code_seen('Y')) {
  3121. Y_probe_location = code_value();
  3122. #if DISABLED(DELTA)
  3123. if (Y_probe_location < MIN_PROBE_Y || Y_probe_location > MAX_PROBE_Y) {
  3124. out_of_range_error(PSTR("Y"));
  3125. return;
  3126. }
  3127. #endif
  3128. }
  3129. #if ENABLED(DELTA)
  3130. if (sqrt(X_probe_location * X_probe_location + Y_probe_location * Y_probe_location) > DELTA_PROBEABLE_RADIUS) {
  3131. SERIAL_PROTOCOLPGM("? (X,Y) location outside of probeable radius.\n");
  3132. return;
  3133. }
  3134. #endif
  3135. bool seen_L = code_seen('L');
  3136. if (seen_L) {
  3137. n_legs = code_value_short();
  3138. if (n_legs < 0 || n_legs > 15) {
  3139. SERIAL_PROTOCOLPGM("?Number of legs in movement not plausible (0-15).\n");
  3140. return;
  3141. }
  3142. if (n_legs == 1) n_legs = 2;
  3143. }
  3144. if (code_seen('S')) {
  3145. schizoid_flag++;
  3146. if (!seen_L) n_legs = 7;
  3147. }
  3148. // Now get everything to the specified probe point So we can safely do a probe to
  3149. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  3150. // use that as a starting point for each probe.
  3151. //
  3152. if (verbose_level > 2)
  3153. SERIAL_PROTOCOLPGM("Positioning the probe...\n");
  3154. #if ENABLED(DELTA)
  3155. reset_bed_level(); // we don't do bed level correction in M48 because we want the raw data when we probe
  3156. #else
  3157. plan_bed_level_matrix.set_to_identity(); // we don't do bed level correction in M48 because we wantthe raw data when we probe
  3158. #endif
  3159. if (Z_start_location < Z_RAISE_BEFORE_PROBING * 2.0)
  3160. do_blocking_move_to_z(Z_start_location);
  3161. do_blocking_move_to_xy(X_probe_location - X_PROBE_OFFSET_FROM_EXTRUDER, Y_probe_location - Y_PROBE_OFFSET_FROM_EXTRUDER);
  3162. //
  3163. // OK, do the initial probe to get us close to the bed.
  3164. // Then retrace the right amount and use that in subsequent probes
  3165. //
  3166. setup_for_endstop_move();
  3167. probe_pt(X_probe_location, Y_probe_location, Z_RAISE_BEFORE_PROBING,
  3168. deploy_probe_for_each_reading ? ProbeDeployAndStow : ProbeDeploy,
  3169. verbose_level);
  3170. raise_z_after_probing();
  3171. for (uint8_t n = 0; n < n_samples; n++) {
  3172. randomSeed(millis());
  3173. delay(500);
  3174. if (n_legs) {
  3175. float radius, angle = random(0.0, 360.0);
  3176. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  3177. radius = random(
  3178. #if ENABLED(DELTA)
  3179. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  3180. #else
  3181. 5, X_MAX_LENGTH / 8
  3182. #endif
  3183. );
  3184. if (verbose_level > 3) {
  3185. SERIAL_ECHOPAIR("Starting radius: ", radius);
  3186. SERIAL_ECHOPAIR(" angle: ", angle);
  3187. delay(100);
  3188. if (dir > 0)
  3189. SERIAL_ECHO(" Direction: Counter Clockwise \n");
  3190. else
  3191. SERIAL_ECHO(" Direction: Clockwise \n");
  3192. delay(100);
  3193. }
  3194. for (uint8_t l = 0; l < n_legs - 1; l++) {
  3195. double delta_angle;
  3196. if (schizoid_flag)
  3197. delta_angle = dir * 2.0 * 72.0; // The points of a 5 point star are 72 degrees apart. We need to
  3198. // skip a point and go to the next one on the star.
  3199. else
  3200. delta_angle = dir * (float) random(25, 45); // If we do this line, we are just trying to move further
  3201. // around the circle.
  3202. angle += delta_angle;
  3203. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  3204. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  3205. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  3206. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  3207. X_current = X_probe_location - X_PROBE_OFFSET_FROM_EXTRUDER + cos(RADIANS(angle)) * radius;
  3208. Y_current = Y_probe_location - Y_PROBE_OFFSET_FROM_EXTRUDER + sin(RADIANS(angle)) * radius;
  3209. #if DISABLED(DELTA)
  3210. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  3211. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  3212. #else
  3213. // If we have gone out too far, we can do a simple fix and scale the numbers
  3214. // back in closer to the origin.
  3215. while (sqrt(X_current * X_current + Y_current * Y_current) > DELTA_PROBEABLE_RADIUS) {
  3216. X_current /= 1.25;
  3217. Y_current /= 1.25;
  3218. if (verbose_level > 3) {
  3219. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  3220. SERIAL_ECHOPAIR(", ", Y_current);
  3221. SERIAL_EOL;
  3222. delay(50);
  3223. }
  3224. }
  3225. #endif
  3226. if (verbose_level > 3) {
  3227. SERIAL_PROTOCOL("Going to:");
  3228. SERIAL_ECHOPAIR("x: ", X_current);
  3229. SERIAL_ECHOPAIR("y: ", Y_current);
  3230. SERIAL_ECHOPAIR(" z: ", current_position[Z_AXIS]);
  3231. SERIAL_EOL;
  3232. delay(55);
  3233. }
  3234. do_blocking_move_to_xy(X_current, Y_current);
  3235. } // n_legs loop
  3236. } // n_legs
  3237. // We don't really have to do this move, but if we don't we can see a funny shift in the Z Height
  3238. // Because the user might not have the Z_RAISE_BEFORE_PROBING height identical to the
  3239. // Z_RAISE_BETWEEN_PROBING height. This gets us back to the probe location at the same height that
  3240. // we have been running around the circle at.
  3241. do_blocking_move_to_xy(X_probe_location - X_PROBE_OFFSET_FROM_EXTRUDER, Y_probe_location - Y_PROBE_OFFSET_FROM_EXTRUDER);
  3242. if (deploy_probe_for_each_reading)
  3243. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, Z_RAISE_BEFORE_PROBING, ProbeDeployAndStow, verbose_level);
  3244. else {
  3245. if (n == n_samples - 1)
  3246. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, Z_RAISE_BEFORE_PROBING, ProbeStow, verbose_level); else
  3247. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, Z_RAISE_BEFORE_PROBING, ProbeStay, verbose_level);
  3248. }
  3249. //
  3250. // Get the current mean for the data points we have so far
  3251. //
  3252. sum = 0.0;
  3253. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  3254. mean = sum / (n + 1);
  3255. //
  3256. // Now, use that mean to calculate the standard deviation for the
  3257. // data points we have so far
  3258. //
  3259. sum = 0.0;
  3260. for (uint8_t j = 0; j <= n; j++) {
  3261. float ss = sample_set[j] - mean;
  3262. sum += ss * ss;
  3263. }
  3264. sigma = sqrt(sum / (n + 1));
  3265. if (verbose_level > 1) {
  3266. SERIAL_PROTOCOL(n + 1);
  3267. SERIAL_PROTOCOLPGM(" of ");
  3268. SERIAL_PROTOCOL((int)n_samples);
  3269. SERIAL_PROTOCOLPGM(" z: ");
  3270. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  3271. delay(50);
  3272. if (verbose_level > 2) {
  3273. SERIAL_PROTOCOLPGM(" mean: ");
  3274. SERIAL_PROTOCOL_F(mean, 6);
  3275. SERIAL_PROTOCOLPGM(" sigma: ");
  3276. SERIAL_PROTOCOL_F(sigma, 6);
  3277. }
  3278. }
  3279. if (verbose_level > 0) SERIAL_EOL;
  3280. delay(50);
  3281. do_blocking_move_to_z(current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  3282. } // End of probe loop code
  3283. // raise_z_after_probing();
  3284. if (verbose_level > 0) {
  3285. SERIAL_PROTOCOLPGM("Mean: ");
  3286. SERIAL_PROTOCOL_F(mean, 6);
  3287. SERIAL_EOL;
  3288. delay(25);
  3289. }
  3290. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  3291. SERIAL_PROTOCOL_F(sigma, 6);
  3292. SERIAL_EOL; SERIAL_EOL;
  3293. delay(25);
  3294. clean_up_after_endstop_move();
  3295. }
  3296. #endif // AUTO_BED_LEVELING_FEATURE && Z_MIN_PROBE_REPEATABILITY_TEST
  3297. /**
  3298. * M104: Set hot end temperature
  3299. */
  3300. inline void gcode_M104() {
  3301. if (setTargetedHotend(104)) return;
  3302. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3303. if (code_seen('S')) {
  3304. float temp = code_value();
  3305. setTargetHotend(temp, target_extruder);
  3306. #if ENABLED(DUAL_X_CARRIAGE)
  3307. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  3308. setTargetHotend1(temp == 0.0 ? 0.0 : temp + duplicate_extruder_temp_offset);
  3309. #endif
  3310. }
  3311. }
  3312. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3313. void print_heaterstates() {
  3314. #if HAS_TEMP_0 || ENABLED(HEATER_0_USES_MAX6675)
  3315. SERIAL_PROTOCOLPGM(" T:");
  3316. SERIAL_PROTOCOL_F(degHotend(target_extruder), 1);
  3317. SERIAL_PROTOCOLPGM(" /");
  3318. SERIAL_PROTOCOL_F(degTargetHotend(target_extruder), 1);
  3319. #endif
  3320. #if HAS_TEMP_BED
  3321. SERIAL_PROTOCOLPGM(" B:");
  3322. SERIAL_PROTOCOL_F(degBed(), 1);
  3323. SERIAL_PROTOCOLPGM(" /");
  3324. SERIAL_PROTOCOL_F(degTargetBed(), 1);
  3325. #endif
  3326. #if EXTRUDERS > 1
  3327. for (int8_t e = 0; e < EXTRUDERS; ++e) {
  3328. SERIAL_PROTOCOLPGM(" T");
  3329. SERIAL_PROTOCOL(e);
  3330. SERIAL_PROTOCOLCHAR(':');
  3331. SERIAL_PROTOCOL_F(degHotend(e), 1);
  3332. SERIAL_PROTOCOLPGM(" /");
  3333. SERIAL_PROTOCOL_F(degTargetHotend(e), 1);
  3334. }
  3335. #endif
  3336. #if HAS_TEMP_BED
  3337. SERIAL_PROTOCOLPGM(" B@:");
  3338. #ifdef BED_WATTS
  3339. SERIAL_PROTOCOL(((BED_WATTS) * getHeaterPower(-1)) / 127);
  3340. SERIAL_PROTOCOLCHAR('W');
  3341. #else
  3342. SERIAL_PROTOCOL(getHeaterPower(-1));
  3343. #endif
  3344. #endif
  3345. SERIAL_PROTOCOLPGM(" @:");
  3346. #ifdef EXTRUDER_WATTS
  3347. SERIAL_PROTOCOL(((EXTRUDER_WATTS) * getHeaterPower(target_extruder)) / 127);
  3348. SERIAL_PROTOCOLCHAR('W');
  3349. #else
  3350. SERIAL_PROTOCOL(getHeaterPower(target_extruder));
  3351. #endif
  3352. #if EXTRUDERS > 1
  3353. for (int8_t e = 0; e < EXTRUDERS; ++e) {
  3354. SERIAL_PROTOCOLPGM(" @");
  3355. SERIAL_PROTOCOL(e);
  3356. SERIAL_PROTOCOLCHAR(':');
  3357. #ifdef EXTRUDER_WATTS
  3358. SERIAL_PROTOCOL(((EXTRUDER_WATTS) * getHeaterPower(e)) / 127);
  3359. SERIAL_PROTOCOLCHAR('W');
  3360. #else
  3361. SERIAL_PROTOCOL(getHeaterPower(e));
  3362. #endif
  3363. }
  3364. #endif
  3365. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  3366. #if HAS_TEMP_BED
  3367. SERIAL_PROTOCOLPGM(" ADC B:");
  3368. SERIAL_PROTOCOL_F(degBed(), 1);
  3369. SERIAL_PROTOCOLPGM("C->");
  3370. SERIAL_PROTOCOL_F(rawBedTemp() / OVERSAMPLENR, 0);
  3371. #endif
  3372. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  3373. SERIAL_PROTOCOLPGM(" T");
  3374. SERIAL_PROTOCOL(cur_extruder);
  3375. SERIAL_PROTOCOLCHAR(':');
  3376. SERIAL_PROTOCOL_F(degHotend(cur_extruder), 1);
  3377. SERIAL_PROTOCOLPGM("C->");
  3378. SERIAL_PROTOCOL_F(rawHotendTemp(cur_extruder) / OVERSAMPLENR, 0);
  3379. }
  3380. #endif
  3381. }
  3382. #endif
  3383. /**
  3384. * M105: Read hot end and bed temperature
  3385. */
  3386. inline void gcode_M105() {
  3387. if (setTargetedHotend(105)) return;
  3388. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3389. SERIAL_PROTOCOLPGM(MSG_OK);
  3390. print_heaterstates();
  3391. #else // !HAS_TEMP_0 && !HAS_TEMP_BED
  3392. SERIAL_ERROR_START;
  3393. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  3394. #endif
  3395. SERIAL_EOL;
  3396. }
  3397. #if FAN_COUNT > 0
  3398. /**
  3399. * M106: Set Fan Speed
  3400. *
  3401. * S<int> Speed between 0-255
  3402. * P<index> Fan index, if more than one fan
  3403. */
  3404. inline void gcode_M106() {
  3405. uint16_t s = code_seen('S') ? code_value_short() : 255,
  3406. p = code_seen('P') ? code_value_short() : 0;
  3407. NOMORE(s, 255);
  3408. if (p < FAN_COUNT) fanSpeeds[p] = s;
  3409. }
  3410. /**
  3411. * M107: Fan Off
  3412. */
  3413. inline void gcode_M107() {
  3414. uint16_t p = code_seen('P') ? code_value_short() : 0;
  3415. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  3416. }
  3417. #endif // FAN_COUNT > 0
  3418. /**
  3419. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  3420. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  3421. */
  3422. inline void gcode_M109() {
  3423. bool no_wait_for_cooling = true;
  3424. if (setTargetedHotend(109)) return;
  3425. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3426. LCD_MESSAGEPGM(MSG_HEATING);
  3427. no_wait_for_cooling = code_seen('S');
  3428. if (no_wait_for_cooling || code_seen('R')) {
  3429. float temp = code_value();
  3430. setTargetHotend(temp, target_extruder);
  3431. #if ENABLED(DUAL_X_CARRIAGE)
  3432. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  3433. setTargetHotend1(temp == 0.0 ? 0.0 : temp + duplicate_extruder_temp_offset);
  3434. #endif
  3435. }
  3436. #if ENABLED(AUTOTEMP)
  3437. autotemp_enabled = code_seen('F');
  3438. if (autotemp_enabled) autotemp_factor = code_value();
  3439. if (code_seen('S')) autotemp_min = code_value();
  3440. if (code_seen('B')) autotemp_max = code_value();
  3441. #endif
  3442. // Exit if the temperature is above target and not waiting for cooling
  3443. if (no_wait_for_cooling && !isHeatingHotend(target_extruder)) return;
  3444. // Prevents a wait-forever situation if R is misused i.e. M109 R0
  3445. // Try to calculate a ballpark safe margin by halving EXTRUDE_MINTEMP
  3446. if (degTargetHotend(target_extruder) < (EXTRUDE_MINTEMP/2)) return;
  3447. #ifdef TEMP_RESIDENCY_TIME
  3448. long residency_start_ms = -1;
  3449. // Loop until the temperature has stabilized
  3450. #define TEMP_CONDITIONS (residency_start_ms < 0 || now < residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL)
  3451. #else
  3452. // Loop until the temperature is very close target
  3453. #define TEMP_CONDITIONS (fabs(degHotend(target_extruder) - degTargetHotend(target_extruder)) < 0.75f)
  3454. #endif //TEMP_RESIDENCY_TIME
  3455. cancel_heatup = false;
  3456. millis_t now = millis(), next_temp_ms = now + 1000UL;
  3457. while (!cancel_heatup && TEMP_CONDITIONS) {
  3458. now = millis();
  3459. if (now > next_temp_ms) { //Print temp & remaining time every 1s while waiting
  3460. next_temp_ms = now + 1000UL;
  3461. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3462. print_heaterstates();
  3463. #endif
  3464. #ifdef TEMP_RESIDENCY_TIME
  3465. SERIAL_PROTOCOLPGM(" W:");
  3466. if (residency_start_ms >= 0) {
  3467. long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  3468. SERIAL_PROTOCOLLN(rem);
  3469. }
  3470. else {
  3471. SERIAL_PROTOCOLLNPGM("?");
  3472. }
  3473. #else
  3474. SERIAL_EOL;
  3475. #endif
  3476. }
  3477. idle();
  3478. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  3479. #ifdef TEMP_RESIDENCY_TIME
  3480. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  3481. // Restart the timer whenever the temperature falls outside the hysteresis.
  3482. if (labs(degHotend(target_extruder) - degTargetHotend(target_extruder)) > ((residency_start_ms < 0) ? TEMP_WINDOW : TEMP_HYSTERESIS))
  3483. residency_start_ms = millis();
  3484. #endif //TEMP_RESIDENCY_TIME
  3485. } // while(!cancel_heatup && TEMP_CONDITIONS)
  3486. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  3487. print_job_start_ms = previous_cmd_ms;
  3488. }
  3489. #if HAS_TEMP_BED
  3490. /**
  3491. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3492. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3493. */
  3494. inline void gcode_M190() {
  3495. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3496. LCD_MESSAGEPGM(MSG_BED_HEATING);
  3497. bool no_wait_for_cooling = code_seen('S');
  3498. if (no_wait_for_cooling || code_seen('R'))
  3499. setTargetBed(code_value());
  3500. // Exit if the temperature is above target and not waiting for cooling
  3501. if (no_wait_for_cooling && !isHeatingBed()) return;
  3502. cancel_heatup = false;
  3503. millis_t now = millis(), next_temp_ms = now + 1000UL;
  3504. while (!cancel_heatup && degTargetBed() != degBed()) {
  3505. millis_t now = millis();
  3506. if (now > next_temp_ms) { //Print Temp Reading every 1 second while heating up.
  3507. next_temp_ms = now + 1000UL;
  3508. print_heaterstates();
  3509. SERIAL_EOL;
  3510. }
  3511. idle();
  3512. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  3513. }
  3514. LCD_MESSAGEPGM(MSG_BED_DONE);
  3515. }
  3516. #endif // HAS_TEMP_BED
  3517. /**
  3518. * M110: Set Current Line Number
  3519. */
  3520. inline void gcode_M110() {
  3521. if (code_seen('N')) gcode_N = code_value_long();
  3522. }
  3523. /**
  3524. * M111: Set the debug level
  3525. */
  3526. inline void gcode_M111() {
  3527. marlin_debug_flags = code_seen('S') ? code_value_short() : DEBUG_INFO | DEBUG_COMMUNICATION;
  3528. if (marlin_debug_flags & DEBUG_ECHO) {
  3529. SERIAL_ECHO_START;
  3530. SERIAL_ECHOLNPGM(MSG_DEBUG_ECHO);
  3531. }
  3532. // FOR MOMENT NOT ACTIVE
  3533. //if (marlin_debug_flags & DEBUG_INFO) SERIAL_ECHOLNPGM(MSG_DEBUG_INFO);
  3534. //if (marlin_debug_flags & DEBUG_ERRORS) SERIAL_ECHOLNPGM(MSG_DEBUG_ERRORS);
  3535. if (marlin_debug_flags & DEBUG_DRYRUN) {
  3536. SERIAL_ECHO_START;
  3537. SERIAL_ECHOLNPGM(MSG_DEBUG_DRYRUN);
  3538. disable_all_heaters();
  3539. }
  3540. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3541. if (marlin_debug_flags & DEBUG_LEVELING) {
  3542. SERIAL_ECHO_START;
  3543. SERIAL_ECHOLNPGM(MSG_DEBUG_LEVELING);
  3544. }
  3545. #endif
  3546. }
  3547. /**
  3548. * M112: Emergency Stop
  3549. */
  3550. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  3551. #if ENABLED(BARICUDA)
  3552. #if HAS_HEATER_1
  3553. /**
  3554. * M126: Heater 1 valve open
  3555. */
  3556. inline void gcode_M126() { ValvePressure = code_seen('S') ? constrain(code_value(), 0, 255) : 255; }
  3557. /**
  3558. * M127: Heater 1 valve close
  3559. */
  3560. inline void gcode_M127() { ValvePressure = 0; }
  3561. #endif
  3562. #if HAS_HEATER_2
  3563. /**
  3564. * M128: Heater 2 valve open
  3565. */
  3566. inline void gcode_M128() { EtoPPressure = code_seen('S') ? constrain(code_value(), 0, 255) : 255; }
  3567. /**
  3568. * M129: Heater 2 valve close
  3569. */
  3570. inline void gcode_M129() { EtoPPressure = 0; }
  3571. #endif
  3572. #endif //BARICUDA
  3573. /**
  3574. * M140: Set bed temperature
  3575. */
  3576. inline void gcode_M140() {
  3577. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3578. if (code_seen('S')) setTargetBed(code_value());
  3579. }
  3580. #if ENABLED(ULTIPANEL)
  3581. /**
  3582. * M145: Set the heatup state for a material in the LCD menu
  3583. * S<material> (0=PLA, 1=ABS)
  3584. * H<hotend temp>
  3585. * B<bed temp>
  3586. * F<fan speed>
  3587. */
  3588. inline void gcode_M145() {
  3589. int8_t material = code_seen('S') ? code_value_short() : 0;
  3590. if (material < 0 || material > 1) {
  3591. SERIAL_ERROR_START;
  3592. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  3593. }
  3594. else {
  3595. int v;
  3596. switch (material) {
  3597. case 0:
  3598. if (code_seen('H')) {
  3599. v = code_value_short();
  3600. plaPreheatHotendTemp = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  3601. }
  3602. if (code_seen('F')) {
  3603. v = code_value_short();
  3604. plaPreheatFanSpeed = constrain(v, 0, 255);
  3605. }
  3606. #if TEMP_SENSOR_BED != 0
  3607. if (code_seen('B')) {
  3608. v = code_value_short();
  3609. plaPreheatHPBTemp = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  3610. }
  3611. #endif
  3612. break;
  3613. case 1:
  3614. if (code_seen('H')) {
  3615. v = code_value_short();
  3616. absPreheatHotendTemp = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  3617. }
  3618. if (code_seen('F')) {
  3619. v = code_value_short();
  3620. absPreheatFanSpeed = constrain(v, 0, 255);
  3621. }
  3622. #if TEMP_SENSOR_BED != 0
  3623. if (code_seen('B')) {
  3624. v = code_value_short();
  3625. absPreheatHPBTemp = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  3626. }
  3627. #endif
  3628. break;
  3629. }
  3630. }
  3631. }
  3632. #endif
  3633. #if HAS_POWER_SWITCH
  3634. /**
  3635. * M80: Turn on Power Supply
  3636. */
  3637. inline void gcode_M80() {
  3638. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); //GND
  3639. // If you have a switch on suicide pin, this is useful
  3640. // if you want to start another print with suicide feature after
  3641. // a print without suicide...
  3642. #if HAS_SUICIDE
  3643. OUT_WRITE(SUICIDE_PIN, HIGH);
  3644. #endif
  3645. #if ENABLED(ULTIPANEL)
  3646. powersupply = true;
  3647. LCD_MESSAGEPGM(WELCOME_MSG);
  3648. lcd_update();
  3649. #endif
  3650. }
  3651. #endif // HAS_POWER_SWITCH
  3652. /**
  3653. * M81: Turn off Power, including Power Supply, if there is one.
  3654. *
  3655. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  3656. */
  3657. inline void gcode_M81() {
  3658. disable_all_heaters();
  3659. finishAndDisableSteppers();
  3660. #if FAN_COUNT > 0
  3661. #if FAN_COUNT > 1
  3662. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  3663. #else
  3664. fanSpeeds[0] = 0;
  3665. #endif
  3666. #endif
  3667. delay(1000); // Wait 1 second before switching off
  3668. #if HAS_SUICIDE
  3669. st_synchronize();
  3670. suicide();
  3671. #elif HAS_POWER_SWITCH
  3672. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  3673. #endif
  3674. #if ENABLED(ULTIPANEL)
  3675. #if HAS_POWER_SWITCH
  3676. powersupply = false;
  3677. #endif
  3678. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  3679. lcd_update();
  3680. #endif
  3681. }
  3682. /**
  3683. * M82: Set E codes absolute (default)
  3684. */
  3685. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  3686. /**
  3687. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  3688. */
  3689. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  3690. /**
  3691. * M18, M84: Disable all stepper motors
  3692. */
  3693. inline void gcode_M18_M84() {
  3694. if (code_seen('S')) {
  3695. stepper_inactive_time = code_value() * 1000;
  3696. }
  3697. else {
  3698. bool all_axis = !((code_seen(axis_codes[X_AXIS])) || (code_seen(axis_codes[Y_AXIS])) || (code_seen(axis_codes[Z_AXIS])) || (code_seen(axis_codes[E_AXIS])));
  3699. if (all_axis) {
  3700. finishAndDisableSteppers();
  3701. }
  3702. else {
  3703. st_synchronize();
  3704. if (code_seen('X')) disable_x();
  3705. if (code_seen('Y')) disable_y();
  3706. if (code_seen('Z')) disable_z();
  3707. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  3708. if (code_seen('E')) {
  3709. disable_e0();
  3710. disable_e1();
  3711. disable_e2();
  3712. disable_e3();
  3713. }
  3714. #endif
  3715. }
  3716. }
  3717. }
  3718. /**
  3719. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3720. */
  3721. inline void gcode_M85() {
  3722. if (code_seen('S')) max_inactive_time = code_value() * 1000;
  3723. }
  3724. /**
  3725. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  3726. * (Follows the same syntax as G92)
  3727. */
  3728. inline void gcode_M92() {
  3729. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3730. if (code_seen(axis_codes[i])) {
  3731. if (i == E_AXIS) {
  3732. float value = code_value();
  3733. if (value < 20.0) {
  3734. float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  3735. max_e_jerk *= factor;
  3736. max_feedrate[i] *= factor;
  3737. axis_steps_per_sqr_second[i] *= factor;
  3738. }
  3739. axis_steps_per_unit[i] = value;
  3740. }
  3741. else {
  3742. axis_steps_per_unit[i] = code_value();
  3743. }
  3744. }
  3745. }
  3746. }
  3747. /**
  3748. * M114: Output current position to serial port
  3749. */
  3750. inline void gcode_M114() {
  3751. SERIAL_PROTOCOLPGM("X:");
  3752. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3753. SERIAL_PROTOCOLPGM(" Y:");
  3754. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3755. SERIAL_PROTOCOLPGM(" Z:");
  3756. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3757. SERIAL_PROTOCOLPGM(" E:");
  3758. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3759. CRITICAL_SECTION_START;
  3760. extern volatile long count_position[NUM_AXIS];
  3761. long xpos = count_position[X_AXIS],
  3762. ypos = count_position[Y_AXIS],
  3763. zpos = count_position[Z_AXIS];
  3764. CRITICAL_SECTION_END;
  3765. #if ENABLED(COREXY) || ENABLED(COREXZ)
  3766. SERIAL_PROTOCOLPGM(MSG_COUNT_A);
  3767. #else
  3768. SERIAL_PROTOCOLPGM(MSG_COUNT_X);
  3769. #endif
  3770. SERIAL_PROTOCOL(xpos);
  3771. #if ENABLED(COREXY)
  3772. SERIAL_PROTOCOLPGM(" B:");
  3773. #else
  3774. SERIAL_PROTOCOLPGM(" Y:");
  3775. #endif
  3776. SERIAL_PROTOCOL(ypos);
  3777. #if ENABLED(COREXZ)
  3778. SERIAL_PROTOCOLPGM(" C:");
  3779. #else
  3780. SERIAL_PROTOCOLPGM(" Z:");
  3781. #endif
  3782. SERIAL_PROTOCOL(zpos);
  3783. SERIAL_EOL;
  3784. #if ENABLED(SCARA)
  3785. SERIAL_PROTOCOLPGM("SCARA Theta:");
  3786. SERIAL_PROTOCOL(delta[X_AXIS]);
  3787. SERIAL_PROTOCOLPGM(" Psi+Theta:");
  3788. SERIAL_PROTOCOL(delta[Y_AXIS]);
  3789. SERIAL_EOL;
  3790. SERIAL_PROTOCOLPGM("SCARA Cal - Theta:");
  3791. SERIAL_PROTOCOL(delta[X_AXIS] + home_offset[X_AXIS]);
  3792. SERIAL_PROTOCOLPGM(" Psi+Theta (90):");
  3793. SERIAL_PROTOCOL(delta[Y_AXIS] - delta[X_AXIS] - 90 + home_offset[Y_AXIS]);
  3794. SERIAL_EOL;
  3795. SERIAL_PROTOCOLPGM("SCARA step Cal - Theta:");
  3796. SERIAL_PROTOCOL(delta[X_AXIS] / 90 * axis_steps_per_unit[X_AXIS]);
  3797. SERIAL_PROTOCOLPGM(" Psi+Theta:");
  3798. SERIAL_PROTOCOL((delta[Y_AXIS] - delta[X_AXIS]) / 90 * axis_steps_per_unit[Y_AXIS]);
  3799. SERIAL_EOL; SERIAL_EOL;
  3800. #endif
  3801. }
  3802. /**
  3803. * M115: Capabilities string
  3804. */
  3805. inline void gcode_M115() {
  3806. SERIAL_PROTOCOLPGM(MSG_M115_REPORT);
  3807. }
  3808. /**
  3809. * M117: Set LCD Status Message
  3810. */
  3811. inline void gcode_M117() {
  3812. lcd_setstatus(current_command_args);
  3813. }
  3814. /**
  3815. * M119: Output endstop states to serial output
  3816. */
  3817. inline void gcode_M119() {
  3818. SERIAL_PROTOCOLLN(MSG_M119_REPORT);
  3819. #if HAS_X_MIN
  3820. SERIAL_PROTOCOLPGM(MSG_X_MIN);
  3821. SERIAL_PROTOCOLLN(((READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3822. #endif
  3823. #if HAS_X_MAX
  3824. SERIAL_PROTOCOLPGM(MSG_X_MAX);
  3825. SERIAL_PROTOCOLLN(((READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3826. #endif
  3827. #if HAS_Y_MIN
  3828. SERIAL_PROTOCOLPGM(MSG_Y_MIN);
  3829. SERIAL_PROTOCOLLN(((READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3830. #endif
  3831. #if HAS_Y_MAX
  3832. SERIAL_PROTOCOLPGM(MSG_Y_MAX);
  3833. SERIAL_PROTOCOLLN(((READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3834. #endif
  3835. #if HAS_Z_MIN
  3836. SERIAL_PROTOCOLPGM(MSG_Z_MIN);
  3837. SERIAL_PROTOCOLLN(((READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3838. #endif
  3839. #if HAS_Z_MAX
  3840. SERIAL_PROTOCOLPGM(MSG_Z_MAX);
  3841. SERIAL_PROTOCOLLN(((READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3842. #endif
  3843. #if HAS_Z2_MAX
  3844. SERIAL_PROTOCOLPGM(MSG_Z2_MAX);
  3845. SERIAL_PROTOCOLLN(((READ(Z2_MAX_PIN)^Z2_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3846. #endif
  3847. #if HAS_Z_PROBE
  3848. SERIAL_PROTOCOLPGM(MSG_Z_PROBE);
  3849. SERIAL_PROTOCOLLN(((READ(Z_MIN_PROBE_PIN)^Z_MIN_PROBE_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3850. #endif
  3851. }
  3852. /**
  3853. * M120: Enable endstops
  3854. */
  3855. inline void gcode_M120() { enable_endstops(true); }
  3856. /**
  3857. * M121: Disable endstops
  3858. */
  3859. inline void gcode_M121() { enable_endstops(false); }
  3860. #if ENABLED(BLINKM)
  3861. /**
  3862. * M150: Set Status LED Color - Use R-U-B for R-G-B
  3863. */
  3864. inline void gcode_M150() {
  3865. SendColors(
  3866. code_seen('R') ? (byte)code_value_short() : 0,
  3867. code_seen('U') ? (byte)code_value_short() : 0,
  3868. code_seen('B') ? (byte)code_value_short() : 0
  3869. );
  3870. }
  3871. #endif // BLINKM
  3872. /**
  3873. * M200: Set filament diameter and set E axis units to cubic millimeters
  3874. *
  3875. * T<extruder> - Optional extruder number. Current extruder if omitted.
  3876. * D<mm> - Diameter of the filament. Use "D0" to set units back to millimeters.
  3877. */
  3878. inline void gcode_M200() {
  3879. if (setTargetedHotend(200)) return;
  3880. if (code_seen('D')) {
  3881. float diameter = code_value();
  3882. // setting any extruder filament size disables volumetric on the assumption that
  3883. // slicers either generate in extruder values as cubic mm or as as filament feeds
  3884. // for all extruders
  3885. volumetric_enabled = (diameter != 0.0);
  3886. if (volumetric_enabled) {
  3887. filament_size[target_extruder] = diameter;
  3888. // make sure all extruders have some sane value for the filament size
  3889. for (int i = 0; i < EXTRUDERS; i++)
  3890. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  3891. }
  3892. }
  3893. else {
  3894. //reserved for setting filament diameter via UFID or filament measuring device
  3895. return;
  3896. }
  3897. calculate_volumetric_multipliers();
  3898. }
  3899. /**
  3900. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3901. */
  3902. inline void gcode_M201() {
  3903. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3904. if (code_seen(axis_codes[i])) {
  3905. max_acceleration_units_per_sq_second[i] = code_value();
  3906. }
  3907. }
  3908. // 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)
  3909. reset_acceleration_rates();
  3910. }
  3911. #if 0 // Not used for Sprinter/grbl gen6
  3912. inline void gcode_M202() {
  3913. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3914. if (code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
  3915. }
  3916. }
  3917. #endif
  3918. /**
  3919. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3920. */
  3921. inline void gcode_M203() {
  3922. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3923. if (code_seen(axis_codes[i])) {
  3924. max_feedrate[i] = code_value();
  3925. }
  3926. }
  3927. }
  3928. /**
  3929. * M204: Set Accelerations in mm/sec^2 (M204 P1200 R3000 T3000)
  3930. *
  3931. * P = Printing moves
  3932. * R = Retract only (no X, Y, Z) moves
  3933. * T = Travel (non printing) moves
  3934. *
  3935. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  3936. */
  3937. inline void gcode_M204() {
  3938. if (code_seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  3939. travel_acceleration = acceleration = code_value();
  3940. SERIAL_ECHOPAIR("Setting Print and Travel Acceleration: ", acceleration);
  3941. SERIAL_EOL;
  3942. }
  3943. if (code_seen('P')) {
  3944. acceleration = code_value();
  3945. SERIAL_ECHOPAIR("Setting Print Acceleration: ", acceleration);
  3946. SERIAL_EOL;
  3947. }
  3948. if (code_seen('R')) {
  3949. retract_acceleration = code_value();
  3950. SERIAL_ECHOPAIR("Setting Retract Acceleration: ", retract_acceleration);
  3951. SERIAL_EOL;
  3952. }
  3953. if (code_seen('T')) {
  3954. travel_acceleration = code_value();
  3955. SERIAL_ECHOPAIR("Setting Travel Acceleration: ", travel_acceleration);
  3956. SERIAL_EOL;
  3957. }
  3958. }
  3959. /**
  3960. * M205: Set Advanced Settings
  3961. *
  3962. * S = Min Feed Rate (mm/s)
  3963. * T = Min Travel Feed Rate (mm/s)
  3964. * B = Min Segment Time (µs)
  3965. * X = Max XY Jerk (mm/s/s)
  3966. * Z = Max Z Jerk (mm/s/s)
  3967. * E = Max E Jerk (mm/s/s)
  3968. */
  3969. inline void gcode_M205() {
  3970. if (code_seen('S')) minimumfeedrate = code_value();
  3971. if (code_seen('T')) mintravelfeedrate = code_value();
  3972. if (code_seen('B')) minsegmenttime = code_value();
  3973. if (code_seen('X')) max_xy_jerk = code_value();
  3974. if (code_seen('Z')) max_z_jerk = code_value();
  3975. if (code_seen('E')) max_e_jerk = code_value();
  3976. }
  3977. /**
  3978. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  3979. */
  3980. inline void gcode_M206() {
  3981. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  3982. if (code_seen(axis_codes[i])) {
  3983. home_offset[i] = code_value();
  3984. }
  3985. }
  3986. #if ENABLED(SCARA)
  3987. if (code_seen('T')) home_offset[X_AXIS] = code_value(); // Theta
  3988. if (code_seen('P')) home_offset[Y_AXIS] = code_value(); // Psi
  3989. #endif
  3990. }
  3991. #if ENABLED(DELTA)
  3992. /**
  3993. * M665: Set delta configurations
  3994. *
  3995. * L = diagonal rod
  3996. * R = delta radius
  3997. * S = segments per second
  3998. * A = Alpha (Tower 1) diagonal rod trim
  3999. * B = Beta (Tower 2) diagonal rod trim
  4000. * C = Gamma (Tower 3) diagonal rod trim
  4001. */
  4002. inline void gcode_M665() {
  4003. if (code_seen('L')) delta_diagonal_rod = code_value();
  4004. if (code_seen('R')) delta_radius = code_value();
  4005. if (code_seen('S')) delta_segments_per_second = code_value();
  4006. if (code_seen('A')) delta_diagonal_rod_trim_tower_1 = code_value();
  4007. if (code_seen('B')) delta_diagonal_rod_trim_tower_2 = code_value();
  4008. if (code_seen('C')) delta_diagonal_rod_trim_tower_3 = code_value();
  4009. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4010. }
  4011. /**
  4012. * M666: Set delta endstop adjustment
  4013. */
  4014. inline void gcode_M666() {
  4015. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4016. if (marlin_debug_flags & DEBUG_LEVELING) {
  4017. SERIAL_ECHOLNPGM(">>> gcode_M666");
  4018. }
  4019. #endif
  4020. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  4021. if (code_seen(axis_codes[i])) {
  4022. endstop_adj[i] = code_value();
  4023. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4024. if (marlin_debug_flags & DEBUG_LEVELING) {
  4025. SERIAL_ECHOPGM("endstop_adj[");
  4026. SERIAL_ECHO(axis_codes[i]);
  4027. SERIAL_ECHOPAIR("] = ", endstop_adj[i]);
  4028. SERIAL_EOL;
  4029. }
  4030. #endif
  4031. }
  4032. }
  4033. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4034. if (marlin_debug_flags & DEBUG_LEVELING) {
  4035. SERIAL_ECHOLNPGM("<<< gcode_M666");
  4036. }
  4037. #endif
  4038. }
  4039. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  4040. /**
  4041. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  4042. */
  4043. inline void gcode_M666() {
  4044. if (code_seen('Z')) z_endstop_adj = code_value();
  4045. SERIAL_ECHOPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  4046. SERIAL_EOL;
  4047. }
  4048. #endif // !DELTA && Z_DUAL_ENDSTOPS
  4049. #if ENABLED(FWRETRACT)
  4050. /**
  4051. * M207: Set firmware retraction values
  4052. *
  4053. * S[+mm] retract_length
  4054. * W[+mm] retract_length_swap (multi-extruder)
  4055. * F[mm/min] retract_feedrate
  4056. * Z[mm] retract_zlift
  4057. */
  4058. inline void gcode_M207() {
  4059. if (code_seen('S')) retract_length = code_value();
  4060. if (code_seen('F')) retract_feedrate = code_value() / 60;
  4061. if (code_seen('Z')) retract_zlift = code_value();
  4062. #if EXTRUDERS > 1
  4063. if (code_seen('W')) retract_length_swap = code_value();
  4064. #endif
  4065. }
  4066. /**
  4067. * M208: Set firmware un-retraction values
  4068. *
  4069. * S[+mm] retract_recover_length (in addition to M207 S*)
  4070. * W[+mm] retract_recover_length_swap (multi-extruder)
  4071. * F[mm/min] retract_recover_feedrate
  4072. */
  4073. inline void gcode_M208() {
  4074. if (code_seen('S')) retract_recover_length = code_value();
  4075. if (code_seen('F')) retract_recover_feedrate = code_value() / 60;
  4076. #if EXTRUDERS > 1
  4077. if (code_seen('W')) retract_recover_length_swap = code_value();
  4078. #endif
  4079. }
  4080. /**
  4081. * M209: Enable automatic retract (M209 S1)
  4082. * detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  4083. */
  4084. inline void gcode_M209() {
  4085. if (code_seen('S')) {
  4086. int t = code_value_short();
  4087. switch (t) {
  4088. case 0:
  4089. autoretract_enabled = false;
  4090. break;
  4091. case 1:
  4092. autoretract_enabled = true;
  4093. break;
  4094. default:
  4095. unknown_command_error();
  4096. return;
  4097. }
  4098. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  4099. }
  4100. }
  4101. #endif // FWRETRACT
  4102. #if EXTRUDERS > 1
  4103. /**
  4104. * M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  4105. */
  4106. inline void gcode_M218() {
  4107. if (setTargetedHotend(218)) return;
  4108. if (code_seen('X')) extruder_offset[X_AXIS][target_extruder] = code_value();
  4109. if (code_seen('Y')) extruder_offset[Y_AXIS][target_extruder] = code_value();
  4110. #if ENABLED(DUAL_X_CARRIAGE)
  4111. if (code_seen('Z')) extruder_offset[Z_AXIS][target_extruder] = code_value();
  4112. #endif
  4113. SERIAL_ECHO_START;
  4114. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  4115. for (int e = 0; e < EXTRUDERS; e++) {
  4116. SERIAL_CHAR(' ');
  4117. SERIAL_ECHO(extruder_offset[X_AXIS][e]);
  4118. SERIAL_CHAR(',');
  4119. SERIAL_ECHO(extruder_offset[Y_AXIS][e]);
  4120. #if ENABLED(DUAL_X_CARRIAGE)
  4121. SERIAL_CHAR(',');
  4122. SERIAL_ECHO(extruder_offset[Z_AXIS][e]);
  4123. #endif
  4124. }
  4125. SERIAL_EOL;
  4126. }
  4127. #endif // EXTRUDERS > 1
  4128. /**
  4129. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  4130. */
  4131. inline void gcode_M220() {
  4132. if (code_seen('S')) feedrate_multiplier = code_value();
  4133. }
  4134. /**
  4135. * M221: Set extrusion percentage (M221 T0 S95)
  4136. */
  4137. inline void gcode_M221() {
  4138. if (code_seen('S')) {
  4139. int sval = code_value();
  4140. if (setTargetedHotend(221)) return;
  4141. extruder_multiplier[target_extruder] = sval;
  4142. }
  4143. }
  4144. /**
  4145. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  4146. */
  4147. inline void gcode_M226() {
  4148. if (code_seen('P')) {
  4149. int pin_number = code_value();
  4150. int pin_state = code_seen('S') ? code_value() : -1; // required pin state - default is inverted
  4151. if (pin_state >= -1 && pin_state <= 1) {
  4152. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++) {
  4153. if (sensitive_pins[i] == pin_number) {
  4154. pin_number = -1;
  4155. break;
  4156. }
  4157. }
  4158. if (pin_number > -1) {
  4159. int target = LOW;
  4160. st_synchronize();
  4161. pinMode(pin_number, INPUT);
  4162. switch (pin_state) {
  4163. case 1:
  4164. target = HIGH;
  4165. break;
  4166. case 0:
  4167. target = LOW;
  4168. break;
  4169. case -1:
  4170. target = !digitalRead(pin_number);
  4171. break;
  4172. }
  4173. while (digitalRead(pin_number) != target) idle();
  4174. } // pin_number > -1
  4175. } // pin_state -1 0 1
  4176. } // code_seen('P')
  4177. }
  4178. #if HAS_SERVOS
  4179. /**
  4180. * M280: Get or set servo position. P<index> S<angle>
  4181. */
  4182. inline void gcode_M280() {
  4183. int servo_index = code_seen('P') ? code_value_short() : -1;
  4184. int servo_position = 0;
  4185. if (code_seen('S')) {
  4186. servo_position = code_value_short();
  4187. if (servo_index >= 0 && servo_index < NUM_SERVOS)
  4188. servo[servo_index].move(servo_position);
  4189. else {
  4190. SERIAL_ERROR_START;
  4191. SERIAL_ERROR("Servo ");
  4192. SERIAL_ERROR(servo_index);
  4193. SERIAL_ERRORLN(" out of range");
  4194. }
  4195. }
  4196. else if (servo_index >= 0) {
  4197. SERIAL_ECHO_START;
  4198. SERIAL_ECHO(" Servo ");
  4199. SERIAL_ECHO(servo_index);
  4200. SERIAL_ECHO(": ");
  4201. SERIAL_ECHOLN(servo[servo_index].read());
  4202. }
  4203. }
  4204. #endif // HAS_SERVOS
  4205. #if HAS_BUZZER
  4206. /**
  4207. * M300: Play beep sound S<frequency Hz> P<duration ms>
  4208. */
  4209. inline void gcode_M300() {
  4210. uint16_t beepS = code_seen('S') ? code_value_short() : 110;
  4211. uint32_t beepP = code_seen('P') ? code_value_long() : 1000;
  4212. if (beepP > 5000) beepP = 5000; // limit to 5 seconds
  4213. buzz(beepP, beepS);
  4214. }
  4215. #endif // HAS_BUZZER
  4216. #if ENABLED(PIDTEMP)
  4217. /**
  4218. * M301: Set PID parameters P I D (and optionally C, L)
  4219. *
  4220. * P[float] Kp term
  4221. * I[float] Ki term (unscaled)
  4222. * D[float] Kd term (unscaled)
  4223. *
  4224. * With PID_ADD_EXTRUSION_RATE:
  4225. *
  4226. * C[float] Kc term
  4227. * L[float] LPQ length
  4228. */
  4229. inline void gcode_M301() {
  4230. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  4231. // default behaviour (omitting E parameter) is to update for extruder 0 only
  4232. int e = code_seen('E') ? code_value() : 0; // extruder being updated
  4233. if (e < EXTRUDERS) { // catch bad input value
  4234. if (code_seen('P')) PID_PARAM(Kp, e) = code_value();
  4235. if (code_seen('I')) PID_PARAM(Ki, e) = scalePID_i(code_value());
  4236. if (code_seen('D')) PID_PARAM(Kd, e) = scalePID_d(code_value());
  4237. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  4238. if (code_seen('C')) PID_PARAM(Kc, e) = code_value();
  4239. if (code_seen('L')) lpq_len = code_value();
  4240. NOMORE(lpq_len, LPQ_MAX_LEN);
  4241. #endif
  4242. updatePID();
  4243. SERIAL_ECHO_START;
  4244. #if ENABLED(PID_PARAMS_PER_EXTRUDER)
  4245. SERIAL_ECHO(" e:"); // specify extruder in serial output
  4246. SERIAL_ECHO(e);
  4247. #endif // PID_PARAMS_PER_EXTRUDER
  4248. SERIAL_ECHO(" p:");
  4249. SERIAL_ECHO(PID_PARAM(Kp, e));
  4250. SERIAL_ECHO(" i:");
  4251. SERIAL_ECHO(unscalePID_i(PID_PARAM(Ki, e)));
  4252. SERIAL_ECHO(" d:");
  4253. SERIAL_ECHO(unscalePID_d(PID_PARAM(Kd, e)));
  4254. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  4255. SERIAL_ECHO(" c:");
  4256. //Kc does not have scaling applied above, or in resetting defaults
  4257. SERIAL_ECHO(PID_PARAM(Kc, e));
  4258. #endif
  4259. SERIAL_EOL;
  4260. }
  4261. else {
  4262. SERIAL_ERROR_START;
  4263. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  4264. }
  4265. }
  4266. #endif // PIDTEMP
  4267. #if ENABLED(PIDTEMPBED)
  4268. inline void gcode_M304() {
  4269. if (code_seen('P')) bedKp = code_value();
  4270. if (code_seen('I')) bedKi = scalePID_i(code_value());
  4271. if (code_seen('D')) bedKd = scalePID_d(code_value());
  4272. updatePID();
  4273. SERIAL_ECHO_START;
  4274. SERIAL_ECHO(" p:");
  4275. SERIAL_ECHO(bedKp);
  4276. SERIAL_ECHO(" i:");
  4277. SERIAL_ECHO(unscalePID_i(bedKi));
  4278. SERIAL_ECHO(" d:");
  4279. SERIAL_ECHOLN(unscalePID_d(bedKd));
  4280. }
  4281. #endif // PIDTEMPBED
  4282. #if defined(CHDK) || HAS_PHOTOGRAPH
  4283. /**
  4284. * M240: Trigger a camera by emulating a Canon RC-1
  4285. * See http://www.doc-diy.net/photo/rc-1_hacked/
  4286. */
  4287. inline void gcode_M240() {
  4288. #ifdef CHDK
  4289. OUT_WRITE(CHDK, HIGH);
  4290. chdkHigh = millis();
  4291. chdkActive = true;
  4292. #elif HAS_PHOTOGRAPH
  4293. const uint8_t NUM_PULSES = 16;
  4294. const float PULSE_LENGTH = 0.01524;
  4295. for (int i = 0; i < NUM_PULSES; i++) {
  4296. WRITE(PHOTOGRAPH_PIN, HIGH);
  4297. _delay_ms(PULSE_LENGTH);
  4298. WRITE(PHOTOGRAPH_PIN, LOW);
  4299. _delay_ms(PULSE_LENGTH);
  4300. }
  4301. delay(7.33);
  4302. for (int i = 0; i < NUM_PULSES; i++) {
  4303. WRITE(PHOTOGRAPH_PIN, HIGH);
  4304. _delay_ms(PULSE_LENGTH);
  4305. WRITE(PHOTOGRAPH_PIN, LOW);
  4306. _delay_ms(PULSE_LENGTH);
  4307. }
  4308. #endif // !CHDK && HAS_PHOTOGRAPH
  4309. }
  4310. #endif // CHDK || PHOTOGRAPH_PIN
  4311. #if ENABLED(HAS_LCD_CONTRAST)
  4312. /**
  4313. * M250: Read and optionally set the LCD contrast
  4314. */
  4315. inline void gcode_M250() {
  4316. if (code_seen('C')) lcd_setcontrast(code_value_short() & 0x3F);
  4317. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  4318. SERIAL_PROTOCOL(lcd_contrast);
  4319. SERIAL_EOL;
  4320. }
  4321. #endif // HAS_LCD_CONTRAST
  4322. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  4323. void set_extrude_min_temp(float temp) { extrude_min_temp = temp; }
  4324. /**
  4325. * M302: Allow cold extrudes, or set the minimum extrude S<temperature>.
  4326. */
  4327. inline void gcode_M302() {
  4328. set_extrude_min_temp(code_seen('S') ? code_value() : 0);
  4329. }
  4330. #endif // PREVENT_DANGEROUS_EXTRUDE
  4331. /**
  4332. * M303: PID relay autotune
  4333. * S<temperature> sets the target temperature. (default target temperature = 150C)
  4334. * E<extruder> (-1 for the bed)
  4335. * C<cycles>
  4336. */
  4337. inline void gcode_M303() {
  4338. int e = code_seen('E') ? code_value_short() : 0;
  4339. int c = code_seen('C') ? code_value_short() : 5;
  4340. float temp = code_seen('S') ? code_value() : (e < 0 ? 70.0 : 150.0);
  4341. if (e >=0 && e < EXTRUDERS)
  4342. target_extruder = e;
  4343. KEEPALIVE_STATE(NOT_BUSY);
  4344. PID_autotune(temp, e, c);
  4345. }
  4346. #if ENABLED(SCARA)
  4347. bool SCARA_move_to_cal(uint8_t delta_x, uint8_t delta_y) {
  4348. //SoftEndsEnabled = false; // Ignore soft endstops during calibration
  4349. //SERIAL_ECHOLN(" Soft endstops disabled ");
  4350. if (IsRunning()) {
  4351. //gcode_get_destination(); // For X Y Z E F
  4352. delta[X_AXIS] = delta_x;
  4353. delta[Y_AXIS] = delta_y;
  4354. calculate_SCARA_forward_Transform(delta);
  4355. destination[X_AXIS] = delta[X_AXIS] / axis_scaling[X_AXIS];
  4356. destination[Y_AXIS] = delta[Y_AXIS] / axis_scaling[Y_AXIS];
  4357. prepare_move();
  4358. //ok_to_send();
  4359. return true;
  4360. }
  4361. return false;
  4362. }
  4363. /**
  4364. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  4365. */
  4366. inline bool gcode_M360() {
  4367. SERIAL_ECHOLN(" Cal: Theta 0 ");
  4368. return SCARA_move_to_cal(0, 120);
  4369. }
  4370. /**
  4371. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  4372. */
  4373. inline bool gcode_M361() {
  4374. SERIAL_ECHOLN(" Cal: Theta 90 ");
  4375. return SCARA_move_to_cal(90, 130);
  4376. }
  4377. /**
  4378. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  4379. */
  4380. inline bool gcode_M362() {
  4381. SERIAL_ECHOLN(" Cal: Psi 0 ");
  4382. return SCARA_move_to_cal(60, 180);
  4383. }
  4384. /**
  4385. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  4386. */
  4387. inline bool gcode_M363() {
  4388. SERIAL_ECHOLN(" Cal: Psi 90 ");
  4389. return SCARA_move_to_cal(50, 90);
  4390. }
  4391. /**
  4392. * M364: SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  4393. */
  4394. inline bool gcode_M364() {
  4395. SERIAL_ECHOLN(" Cal: Theta-Psi 90 ");
  4396. return SCARA_move_to_cal(45, 135);
  4397. }
  4398. /**
  4399. * M365: SCARA calibration: Scaling factor, X, Y, Z axis
  4400. */
  4401. inline void gcode_M365() {
  4402. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  4403. if (code_seen(axis_codes[i])) {
  4404. axis_scaling[i] = code_value();
  4405. }
  4406. }
  4407. }
  4408. #endif // SCARA
  4409. #if ENABLED(EXT_SOLENOID)
  4410. void enable_solenoid(uint8_t num) {
  4411. switch (num) {
  4412. case 0:
  4413. OUT_WRITE(SOL0_PIN, HIGH);
  4414. break;
  4415. #if HAS_SOLENOID_1
  4416. case 1:
  4417. OUT_WRITE(SOL1_PIN, HIGH);
  4418. break;
  4419. #endif
  4420. #if HAS_SOLENOID_2
  4421. case 2:
  4422. OUT_WRITE(SOL2_PIN, HIGH);
  4423. break;
  4424. #endif
  4425. #if HAS_SOLENOID_3
  4426. case 3:
  4427. OUT_WRITE(SOL3_PIN, HIGH);
  4428. break;
  4429. #endif
  4430. default:
  4431. SERIAL_ECHO_START;
  4432. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  4433. break;
  4434. }
  4435. }
  4436. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  4437. void disable_all_solenoids() {
  4438. OUT_WRITE(SOL0_PIN, LOW);
  4439. OUT_WRITE(SOL1_PIN, LOW);
  4440. OUT_WRITE(SOL2_PIN, LOW);
  4441. OUT_WRITE(SOL3_PIN, LOW);
  4442. }
  4443. /**
  4444. * M380: Enable solenoid on the active extruder
  4445. */
  4446. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  4447. /**
  4448. * M381: Disable all solenoids
  4449. */
  4450. inline void gcode_M381() { disable_all_solenoids(); }
  4451. #endif // EXT_SOLENOID
  4452. /**
  4453. * M400: Finish all moves
  4454. */
  4455. inline void gcode_M400() { st_synchronize(); }
  4456. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && DISABLED(Z_PROBE_SLED) && (HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY))
  4457. /**
  4458. * M401: Engage Z Servo endstop if available
  4459. */
  4460. inline void gcode_M401() {
  4461. #if HAS_SERVO_ENDSTOPS
  4462. raise_z_for_servo();
  4463. #endif
  4464. deploy_z_probe();
  4465. }
  4466. /**
  4467. * M402: Retract Z Servo endstop if enabled
  4468. */
  4469. inline void gcode_M402() {
  4470. #if HAS_SERVO_ENDSTOPS
  4471. raise_z_for_servo();
  4472. #endif
  4473. stow_z_probe(false);
  4474. }
  4475. #endif // AUTO_BED_LEVELING_FEATURE && (HAS_SERVO_ENDSTOPS || Z_PROBE_ALLEN_KEY) && !Z_PROBE_SLED
  4476. #if ENABLED(FILAMENT_SENSOR)
  4477. /**
  4478. * M404: Display or set the nominal filament width (3mm, 1.75mm ) W<3.0>
  4479. */
  4480. inline void gcode_M404() {
  4481. #if HAS_FILWIDTH
  4482. if (code_seen('W')) {
  4483. filament_width_nominal = code_value();
  4484. }
  4485. else {
  4486. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  4487. SERIAL_PROTOCOLLN(filament_width_nominal);
  4488. }
  4489. #endif
  4490. }
  4491. /**
  4492. * M405: Turn on filament sensor for control
  4493. */
  4494. inline void gcode_M405() {
  4495. if (code_seen('D')) meas_delay_cm = code_value();
  4496. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  4497. if (delay_index2 == -1) { //initialize the ring buffer if it has not been done since startup
  4498. int temp_ratio = widthFil_to_size_ratio();
  4499. for (delay_index1 = 0; delay_index1 < MAX_MEASUREMENT_DELAY + 1; ++delay_index1)
  4500. measurement_delay[delay_index1] = temp_ratio - 100; //subtract 100 to scale within a signed byte
  4501. delay_index1 = delay_index2 = 0;
  4502. }
  4503. filament_sensor = true;
  4504. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4505. //SERIAL_PROTOCOL(filament_width_meas);
  4506. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  4507. //SERIAL_PROTOCOL(extruder_multiplier[active_extruder]);
  4508. }
  4509. /**
  4510. * M406: Turn off filament sensor for control
  4511. */
  4512. inline void gcode_M406() { filament_sensor = false; }
  4513. /**
  4514. * M407: Get measured filament diameter on serial output
  4515. */
  4516. inline void gcode_M407() {
  4517. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4518. SERIAL_PROTOCOLLN(filament_width_meas);
  4519. }
  4520. #endif // FILAMENT_SENSOR
  4521. /**
  4522. * M410: Quickstop - Abort all planned moves
  4523. *
  4524. * This will stop the carriages mid-move, so most likely they
  4525. * will be out of sync with the stepper position after this.
  4526. */
  4527. inline void gcode_M410() { quickStop(); }
  4528. #if ENABLED(MESH_BED_LEVELING)
  4529. /**
  4530. * M420: Enable/Disable Mesh Bed Leveling
  4531. */
  4532. inline void gcode_M420() { if (code_seen('S') && code_has_value()) mbl.active = !!code_value_short(); }
  4533. /**
  4534. * M421: Set a single Mesh Bed Leveling Z coordinate
  4535. */
  4536. inline void gcode_M421() {
  4537. float x, y, z;
  4538. bool err = false, hasX, hasY, hasZ;
  4539. if ((hasX = code_seen('X'))) x = code_value();
  4540. if ((hasY = code_seen('Y'))) y = code_value();
  4541. if ((hasZ = code_seen('Z'))) z = code_value();
  4542. if (!hasX || !hasY || !hasZ) {
  4543. SERIAL_ERROR_START;
  4544. SERIAL_ERRORLNPGM(MSG_ERR_M421_REQUIRES_XYZ);
  4545. err = true;
  4546. }
  4547. if (x >= MESH_NUM_X_POINTS || y >= MESH_NUM_Y_POINTS) {
  4548. SERIAL_ERROR_START;
  4549. SERIAL_ERRORLNPGM(MSG_ERR_MESH_INDEX_OOB);
  4550. err = true;
  4551. }
  4552. if (!err) mbl.set_z(mbl.select_x_index(x), mbl.select_y_index(y), z);
  4553. }
  4554. #endif
  4555. /**
  4556. * M428: Set home_offset based on the distance between the
  4557. * current_position and the nearest "reference point."
  4558. * If an axis is past center its endstop position
  4559. * is the reference-point. Otherwise it uses 0. This allows
  4560. * the Z offset to be set near the bed when using a max endstop.
  4561. *
  4562. * M428 can't be used more than 2cm away from 0 or an endstop.
  4563. *
  4564. * Use M206 to set these values directly.
  4565. */
  4566. inline void gcode_M428() {
  4567. bool err = false;
  4568. float new_offs[3], new_pos[3];
  4569. memcpy(new_pos, current_position, sizeof(new_pos));
  4570. memcpy(new_offs, home_offset, sizeof(new_offs));
  4571. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  4572. if (axis_known_position[i]) {
  4573. float base = (new_pos[i] > (min_pos[i] + max_pos[i]) / 2) ? base_home_pos(i) : 0,
  4574. diff = new_pos[i] - base;
  4575. if (diff > -20 && diff < 20) {
  4576. new_offs[i] -= diff;
  4577. new_pos[i] = base;
  4578. }
  4579. else {
  4580. SERIAL_ERROR_START;
  4581. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  4582. LCD_ALERTMESSAGEPGM("Err: Too far!");
  4583. #if HAS_BUZZER
  4584. enqueue_and_echo_commands_P(PSTR("M300 S40 P200"));
  4585. #endif
  4586. err = true;
  4587. break;
  4588. }
  4589. }
  4590. }
  4591. if (!err) {
  4592. memcpy(current_position, new_pos, sizeof(new_pos));
  4593. memcpy(home_offset, new_offs, sizeof(new_offs));
  4594. sync_plan_position();
  4595. LCD_ALERTMESSAGEPGM("Offset applied.");
  4596. #if HAS_BUZZER
  4597. enqueue_and_echo_commands_P(PSTR("M300 S659 P200\nM300 S698 P200"));
  4598. #endif
  4599. }
  4600. }
  4601. /**
  4602. * M500: Store settings in EEPROM
  4603. */
  4604. inline void gcode_M500() {
  4605. Config_StoreSettings();
  4606. }
  4607. /**
  4608. * M501: Read settings from EEPROM
  4609. */
  4610. inline void gcode_M501() {
  4611. Config_RetrieveSettings();
  4612. }
  4613. /**
  4614. * M502: Revert to default settings
  4615. */
  4616. inline void gcode_M502() {
  4617. Config_ResetDefault();
  4618. }
  4619. /**
  4620. * M503: print settings currently in memory
  4621. */
  4622. inline void gcode_M503() {
  4623. Config_PrintSettings(code_seen('S') && code_value() == 0);
  4624. }
  4625. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  4626. /**
  4627. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  4628. */
  4629. inline void gcode_M540() {
  4630. if (code_seen('S')) abort_on_endstop_hit = (code_value() > 0);
  4631. }
  4632. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  4633. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4634. inline void gcode_SET_Z_PROBE_OFFSET() {
  4635. SERIAL_ECHO_START;
  4636. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET);
  4637. SERIAL_CHAR(' ');
  4638. if (code_seen('Z')) {
  4639. float value = code_value();
  4640. if (Z_PROBE_OFFSET_RANGE_MIN <= value && value <= Z_PROBE_OFFSET_RANGE_MAX) {
  4641. zprobe_zoffset = value;
  4642. SERIAL_ECHO(zprobe_zoffset);
  4643. }
  4644. else {
  4645. SERIAL_ECHOPGM(MSG_Z_MIN);
  4646. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  4647. SERIAL_ECHOPGM(MSG_Z_MAX);
  4648. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  4649. }
  4650. }
  4651. else {
  4652. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  4653. }
  4654. SERIAL_EOL;
  4655. }
  4656. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4657. #if ENABLED(FILAMENTCHANGEENABLE)
  4658. /**
  4659. * M600: Pause for filament change
  4660. *
  4661. * E[distance] - Retract the filament this far (negative value)
  4662. * Z[distance] - Move the Z axis by this distance
  4663. * X[position] - Move to this X position, with Y
  4664. * Y[position] - Move to this Y position, with X
  4665. * L[distance] - Retract distance for removal (manual reload)
  4666. *
  4667. * Default values are used for omitted arguments.
  4668. *
  4669. */
  4670. inline void gcode_M600() {
  4671. if (degHotend(active_extruder) < extrude_min_temp) {
  4672. SERIAL_ERROR_START;
  4673. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  4674. return;
  4675. }
  4676. float lastpos[NUM_AXIS], fr60 = feedrate / 60;
  4677. for (int i = 0; i < NUM_AXIS; i++)
  4678. lastpos[i] = destination[i] = current_position[i];
  4679. #if ENABLED(DELTA)
  4680. #define RUNPLAN calculate_delta(destination); \
  4681. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], fr60, active_extruder);
  4682. #else
  4683. #define RUNPLAN line_to_destination();
  4684. #endif
  4685. //retract by E
  4686. if (code_seen('E')) destination[E_AXIS] += code_value();
  4687. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  4688. else destination[E_AXIS] += FILAMENTCHANGE_FIRSTRETRACT;
  4689. #endif
  4690. RUNPLAN;
  4691. //lift Z
  4692. if (code_seen('Z')) destination[Z_AXIS] += code_value();
  4693. #ifdef FILAMENTCHANGE_ZADD
  4694. else destination[Z_AXIS] += FILAMENTCHANGE_ZADD;
  4695. #endif
  4696. RUNPLAN;
  4697. //move xy
  4698. if (code_seen('X')) destination[X_AXIS] = code_value();
  4699. #ifdef FILAMENTCHANGE_XPOS
  4700. else destination[X_AXIS] = FILAMENTCHANGE_XPOS;
  4701. #endif
  4702. if (code_seen('Y')) destination[Y_AXIS] = code_value();
  4703. #ifdef FILAMENTCHANGE_YPOS
  4704. else destination[Y_AXIS] = FILAMENTCHANGE_YPOS;
  4705. #endif
  4706. RUNPLAN;
  4707. if (code_seen('L')) destination[E_AXIS] += code_value();
  4708. #ifdef FILAMENTCHANGE_FINALRETRACT
  4709. else destination[E_AXIS] += FILAMENTCHANGE_FINALRETRACT;
  4710. #endif
  4711. RUNPLAN;
  4712. //finish moves
  4713. st_synchronize();
  4714. //disable extruder steppers so filament can be removed
  4715. disable_e0();
  4716. disable_e1();
  4717. disable_e2();
  4718. disable_e3();
  4719. delay(100);
  4720. LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE);
  4721. millis_t next_tick = 0;
  4722. KEEPALIVE_STATE(WAIT_FOR_USER);
  4723. while (!lcd_clicked()) {
  4724. #if DISABLED(AUTO_FILAMENT_CHANGE)
  4725. millis_t ms = millis();
  4726. if (ms >= next_tick) {
  4727. lcd_quick_feedback();
  4728. next_tick = ms + 2500; // feedback every 2.5s while waiting
  4729. }
  4730. idle(true);
  4731. #else
  4732. current_position[E_AXIS] += AUTO_FILAMENT_CHANGE_LENGTH;
  4733. destination[E_AXIS] = current_position[E_AXIS];
  4734. line_to_destination(AUTO_FILAMENT_CHANGE_FEEDRATE);
  4735. st_synchronize();
  4736. #endif
  4737. } // while(!lcd_clicked)
  4738. KEEPALIVE_STATE(IN_HANDLER);
  4739. lcd_quick_feedback(); // click sound feedback
  4740. #if ENABLED(AUTO_FILAMENT_CHANGE)
  4741. current_position[E_AXIS] = 0;
  4742. st_synchronize();
  4743. #endif
  4744. //return to normal
  4745. if (code_seen('L')) destination[E_AXIS] -= code_value();
  4746. #ifdef FILAMENTCHANGE_FINALRETRACT
  4747. else destination[E_AXIS] -= FILAMENTCHANGE_FINALRETRACT;
  4748. #endif
  4749. current_position[E_AXIS] = destination[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  4750. plan_set_e_position(current_position[E_AXIS]);
  4751. RUNPLAN; //should do nothing
  4752. lcd_reset_alert_level();
  4753. #if ENABLED(DELTA)
  4754. // Move XYZ to starting position, then E
  4755. calculate_delta(lastpos);
  4756. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], fr60, active_extruder);
  4757. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], lastpos[E_AXIS], fr60, active_extruder);
  4758. #else
  4759. // Move XY to starting position, then Z, then E
  4760. destination[X_AXIS] = lastpos[X_AXIS];
  4761. destination[Y_AXIS] = lastpos[Y_AXIS];
  4762. line_to_destination();
  4763. destination[Z_AXIS] = lastpos[Z_AXIS];
  4764. line_to_destination();
  4765. destination[E_AXIS] = lastpos[E_AXIS];
  4766. line_to_destination();
  4767. #endif
  4768. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  4769. filrunoutEnqueued = false;
  4770. #endif
  4771. }
  4772. #endif // FILAMENTCHANGEENABLE
  4773. #if ENABLED(DUAL_X_CARRIAGE)
  4774. /**
  4775. * M605: Set dual x-carriage movement mode
  4776. *
  4777. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  4778. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  4779. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  4780. * millimeters x-offset and an optional differential hotend temperature of
  4781. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  4782. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  4783. *
  4784. * Note: the X axis should be homed after changing dual x-carriage mode.
  4785. */
  4786. inline void gcode_M605() {
  4787. st_synchronize();
  4788. if (code_seen('S')) dual_x_carriage_mode = code_value();
  4789. switch (dual_x_carriage_mode) {
  4790. case DXC_DUPLICATION_MODE:
  4791. if (code_seen('X')) duplicate_extruder_x_offset = max(code_value(), X2_MIN_POS - x_home_pos(0));
  4792. if (code_seen('R')) duplicate_extruder_temp_offset = code_value();
  4793. SERIAL_ECHO_START;
  4794. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  4795. SERIAL_CHAR(' ');
  4796. SERIAL_ECHO(extruder_offset[X_AXIS][0]);
  4797. SERIAL_CHAR(',');
  4798. SERIAL_ECHO(extruder_offset[Y_AXIS][0]);
  4799. SERIAL_CHAR(' ');
  4800. SERIAL_ECHO(duplicate_extruder_x_offset);
  4801. SERIAL_CHAR(',');
  4802. SERIAL_ECHOLN(extruder_offset[Y_AXIS][1]);
  4803. break;
  4804. case DXC_FULL_CONTROL_MODE:
  4805. case DXC_AUTO_PARK_MODE:
  4806. break;
  4807. default:
  4808. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  4809. break;
  4810. }
  4811. active_extruder_parked = false;
  4812. extruder_duplication_enabled = false;
  4813. delayed_move_time = 0;
  4814. }
  4815. #endif // DUAL_X_CARRIAGE
  4816. /**
  4817. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  4818. */
  4819. inline void gcode_M907() {
  4820. #if HAS_DIGIPOTSS
  4821. for (int i = 0; i < NUM_AXIS; i++)
  4822. if (code_seen(axis_codes[i])) digipot_current(i, code_value());
  4823. if (code_seen('B')) digipot_current(4, code_value());
  4824. if (code_seen('S')) for (int i = 0; i <= 4; i++) digipot_current(i, code_value());
  4825. #endif
  4826. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  4827. if (code_seen('X')) digipot_current(0, code_value());
  4828. #endif
  4829. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  4830. if (code_seen('Z')) digipot_current(1, code_value());
  4831. #endif
  4832. #ifdef MOTOR_CURRENT_PWM_E_PIN
  4833. if (code_seen('E')) digipot_current(2, code_value());
  4834. #endif
  4835. #if ENABLED(DIGIPOT_I2C)
  4836. // this one uses actual amps in floating point
  4837. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value());
  4838. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  4839. for (int i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (code_seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, code_value());
  4840. #endif
  4841. }
  4842. #if HAS_DIGIPOTSS
  4843. /**
  4844. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  4845. */
  4846. inline void gcode_M908() {
  4847. digitalPotWrite(
  4848. code_seen('P') ? code_value() : 0,
  4849. code_seen('S') ? code_value() : 0
  4850. );
  4851. }
  4852. #endif // HAS_DIGIPOTSS
  4853. #if HAS_MICROSTEPS
  4854. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  4855. inline void gcode_M350() {
  4856. if (code_seen('S')) for (int i = 0; i <= 4; i++) microstep_mode(i, code_value());
  4857. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_mode(i, (uint8_t)code_value());
  4858. if (code_seen('B')) microstep_mode(4, code_value());
  4859. microstep_readings();
  4860. }
  4861. /**
  4862. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  4863. * S# determines MS1 or MS2, X# sets the pin high/low.
  4864. */
  4865. inline void gcode_M351() {
  4866. if (code_seen('S')) switch (code_value_short()) {
  4867. case 1:
  4868. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_ms(i, code_value(), -1);
  4869. if (code_seen('B')) microstep_ms(4, code_value(), -1);
  4870. break;
  4871. case 2:
  4872. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_ms(i, -1, code_value());
  4873. if (code_seen('B')) microstep_ms(4, -1, code_value());
  4874. break;
  4875. }
  4876. microstep_readings();
  4877. }
  4878. #endif // HAS_MICROSTEPS
  4879. /**
  4880. * M999: Restart after being stopped
  4881. */
  4882. inline void gcode_M999() {
  4883. Running = true;
  4884. lcd_reset_alert_level();
  4885. // gcode_LastN = Stopped_gcode_LastN;
  4886. FlushSerialRequestResend();
  4887. }
  4888. /**
  4889. * T0-T3: Switch tool, usually switching extruders
  4890. *
  4891. * F[mm/min] Set the movement feedrate
  4892. */
  4893. inline void gcode_T(uint8_t tmp_extruder) {
  4894. if (tmp_extruder >= EXTRUDERS) {
  4895. SERIAL_ECHO_START;
  4896. SERIAL_CHAR('T');
  4897. SERIAL_PROTOCOL_F(tmp_extruder, DEC);
  4898. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  4899. }
  4900. else {
  4901. target_extruder = tmp_extruder;
  4902. #if EXTRUDERS > 1
  4903. bool make_move = false;
  4904. #endif
  4905. if (code_seen('F')) {
  4906. #if EXTRUDERS > 1
  4907. make_move = true;
  4908. #endif
  4909. float next_feedrate = code_value();
  4910. if (next_feedrate > 0.0) feedrate = next_feedrate;
  4911. }
  4912. #if EXTRUDERS > 1
  4913. if (tmp_extruder != active_extruder) {
  4914. // Save current position to return to after applying extruder offset
  4915. set_destination_to_current();
  4916. #if ENABLED(DUAL_X_CARRIAGE)
  4917. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && IsRunning() &&
  4918. (delayed_move_time != 0 || current_position[X_AXIS] != x_home_pos(active_extruder))) {
  4919. // Park old head: 1) raise 2) move to park position 3) lower
  4920. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  4921. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  4922. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  4923. current_position[E_AXIS], max_feedrate[X_AXIS], active_extruder);
  4924. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS],
  4925. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  4926. st_synchronize();
  4927. }
  4928. // apply Y & Z extruder offset (x offset is already used in determining home pos)
  4929. current_position[Y_AXIS] -= extruder_offset[Y_AXIS][active_extruder] - extruder_offset[Y_AXIS][tmp_extruder];
  4930. current_position[Z_AXIS] -= extruder_offset[Z_AXIS][active_extruder] - extruder_offset[Z_AXIS][tmp_extruder];
  4931. active_extruder = tmp_extruder;
  4932. // This function resets the max/min values - the current position may be overwritten below.
  4933. set_axis_is_at_home(X_AXIS);
  4934. if (dual_x_carriage_mode == DXC_FULL_CONTROL_MODE) {
  4935. current_position[X_AXIS] = inactive_extruder_x_pos;
  4936. inactive_extruder_x_pos = destination[X_AXIS];
  4937. }
  4938. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  4939. active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position
  4940. if (active_extruder == 0 || active_extruder_parked)
  4941. current_position[X_AXIS] = inactive_extruder_x_pos;
  4942. else
  4943. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  4944. inactive_extruder_x_pos = destination[X_AXIS];
  4945. extruder_duplication_enabled = false;
  4946. }
  4947. else {
  4948. // record raised toolhead position for use by unpark
  4949. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  4950. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  4951. active_extruder_parked = true;
  4952. delayed_move_time = 0;
  4953. }
  4954. #else // !DUAL_X_CARRIAGE
  4955. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  4956. // Offset extruder, make sure to apply the bed level rotation matrix
  4957. vector_3 tmp_offset_vec = vector_3(extruder_offset[X_AXIS][tmp_extruder],
  4958. extruder_offset[Y_AXIS][tmp_extruder],
  4959. extruder_offset[Z_AXIS][tmp_extruder]),
  4960. act_offset_vec = vector_3(extruder_offset[X_AXIS][active_extruder],
  4961. extruder_offset[Y_AXIS][active_extruder],
  4962. extruder_offset[Z_AXIS][active_extruder]),
  4963. offset_vec = tmp_offset_vec - act_offset_vec;
  4964. offset_vec.apply_rotation(plan_bed_level_matrix.transpose(plan_bed_level_matrix));
  4965. current_position[X_AXIS] += offset_vec.x;
  4966. current_position[Y_AXIS] += offset_vec.y;
  4967. current_position[Z_AXIS] += offset_vec.z;
  4968. #else // !AUTO_BED_LEVELING_FEATURE
  4969. // Offset extruder (only by XY)
  4970. for (int i=X_AXIS; i<=Y_AXIS; i++)
  4971. current_position[i] += extruder_offset[i][tmp_extruder] - extruder_offset[i][active_extruder];
  4972. #endif // !AUTO_BED_LEVELING_FEATURE
  4973. // Set the new active extruder and position
  4974. active_extruder = tmp_extruder;
  4975. #endif // !DUAL_X_CARRIAGE
  4976. #if ENABLED(DELTA)
  4977. sync_plan_position_delta();
  4978. #else
  4979. sync_plan_position();
  4980. #endif
  4981. // Move to the old position if 'F' was in the parameters
  4982. if (make_move && IsRunning()) prepare_move();
  4983. }
  4984. #if ENABLED(EXT_SOLENOID)
  4985. st_synchronize();
  4986. disable_all_solenoids();
  4987. enable_solenoid_on_active_extruder();
  4988. #endif // EXT_SOLENOID
  4989. #endif // EXTRUDERS > 1
  4990. SERIAL_ECHO_START;
  4991. SERIAL_ECHO(MSG_ACTIVE_EXTRUDER);
  4992. SERIAL_PROTOCOLLN((int)active_extruder);
  4993. }
  4994. }
  4995. /**
  4996. * Process a single command and dispatch it to its handler
  4997. * This is called from the main loop()
  4998. */
  4999. void process_next_command() {
  5000. current_command = command_queue[cmd_queue_index_r];
  5001. if ((marlin_debug_flags & DEBUG_ECHO)) {
  5002. SERIAL_ECHO_START;
  5003. SERIAL_ECHOLN(current_command);
  5004. }
  5005. // Sanitize the current command:
  5006. // - Skip leading spaces
  5007. // - Bypass N[-0-9][0-9]*[ ]*
  5008. // - Overwrite * with nul to mark the end
  5009. while (*current_command == ' ') ++current_command;
  5010. if (*current_command == 'N' && ((current_command[1] >= '0' && current_command[1] <= '9') || current_command[1] == '-')) {
  5011. current_command += 2; // skip N[-0-9]
  5012. while (*current_command >= '0' && *current_command <= '9') ++current_command; // skip [0-9]*
  5013. while (*current_command == ' ') ++current_command; // skip [ ]*
  5014. }
  5015. char* starpos = strchr(current_command, '*'); // * should always be the last parameter
  5016. if (starpos) while (*starpos == ' ' || *starpos == '*') *starpos-- = '\0'; // nullify '*' and ' '
  5017. // Get the command code, which must be G, M, or T
  5018. char command_code = *current_command;
  5019. // Skip the letter-code and spaces to get the numeric part
  5020. current_command_args = current_command + 1;
  5021. while (*current_command_args == ' ') ++current_command_args;
  5022. // The code must have a numeric value
  5023. bool code_is_good = (*current_command_args >= '0' && *current_command_args <= '9');
  5024. int codenum; // define ahead of goto
  5025. // Bail early if there's no code
  5026. if (!code_is_good) goto ExitUnknownCommand;
  5027. // Args pointer optimizes code_seen, especially those taking XYZEF
  5028. // This wastes a little cpu on commands that expect no arguments.
  5029. while (*current_command_args == ' ' || (*current_command_args >= '0' && *current_command_args <= '9')) ++current_command_args;
  5030. // Interpret the code int
  5031. seen_pointer = current_command;
  5032. codenum = code_value_short();
  5033. KEEPALIVE_STATE(IN_HANDLER);
  5034. // Handle a known G, M, or T
  5035. switch (command_code) {
  5036. case 'G': switch (codenum) {
  5037. // G0, G1
  5038. case 0:
  5039. case 1:
  5040. gcode_G0_G1();
  5041. break;
  5042. // G2, G3
  5043. #if DISABLED(SCARA)
  5044. case 2: // G2 - CW ARC
  5045. case 3: // G3 - CCW ARC
  5046. gcode_G2_G3(codenum == 2);
  5047. break;
  5048. #endif
  5049. // G4 Dwell
  5050. case 4:
  5051. gcode_G4();
  5052. break;
  5053. #if ENABLED(FWRETRACT)
  5054. case 10: // G10: retract
  5055. case 11: // G11: retract_recover
  5056. gcode_G10_G11(codenum == 10);
  5057. break;
  5058. #endif //FWRETRACT
  5059. case 28: // G28: Home all axes, one at a time
  5060. gcode_G28();
  5061. break;
  5062. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  5063. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points.
  5064. gcode_G29();
  5065. break;
  5066. #endif
  5067. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5068. #if DISABLED(Z_PROBE_SLED)
  5069. case 30: // G30 Single Z probe
  5070. gcode_G30();
  5071. break;
  5072. #else // Z_PROBE_SLED
  5073. case 31: // G31: dock the sled
  5074. case 32: // G32: undock the sled
  5075. dock_sled(codenum == 31);
  5076. break;
  5077. #endif // Z_PROBE_SLED
  5078. #endif // AUTO_BED_LEVELING_FEATURE
  5079. case 90: // G90
  5080. relative_mode = false;
  5081. break;
  5082. case 91: // G91
  5083. relative_mode = true;
  5084. break;
  5085. case 92: // G92
  5086. gcode_G92();
  5087. break;
  5088. }
  5089. break;
  5090. case 'M': switch (codenum) {
  5091. #if ENABLED(ULTIPANEL)
  5092. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  5093. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  5094. gcode_M0_M1();
  5095. break;
  5096. #endif // ULTIPANEL
  5097. case 17:
  5098. gcode_M17();
  5099. break;
  5100. #if ENABLED(SDSUPPORT)
  5101. case 20: // M20 - list SD card
  5102. gcode_M20(); break;
  5103. case 21: // M21 - init SD card
  5104. gcode_M21(); break;
  5105. case 22: //M22 - release SD card
  5106. gcode_M22(); break;
  5107. case 23: //M23 - Select file
  5108. gcode_M23(); break;
  5109. case 24: //M24 - Start SD print
  5110. gcode_M24(); break;
  5111. case 25: //M25 - Pause SD print
  5112. gcode_M25(); break;
  5113. case 26: //M26 - Set SD index
  5114. gcode_M26(); break;
  5115. case 27: //M27 - Get SD status
  5116. gcode_M27(); break;
  5117. case 28: //M28 - Start SD write
  5118. gcode_M28(); break;
  5119. case 29: //M29 - Stop SD write
  5120. gcode_M29(); break;
  5121. case 30: //M30 <filename> Delete File
  5122. gcode_M30(); break;
  5123. case 32: //M32 - Select file and start SD print
  5124. gcode_M32(); break;
  5125. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5126. case 33: //M33 - Get the long full path to a file or folder
  5127. gcode_M33(); break;
  5128. #endif // LONG_FILENAME_HOST_SUPPORT
  5129. case 928: //M928 - Start SD write
  5130. gcode_M928(); break;
  5131. #endif //SDSUPPORT
  5132. case 31: //M31 take time since the start of the SD print or an M109 command
  5133. gcode_M31();
  5134. break;
  5135. case 42: //M42 -Change pin status via gcode
  5136. gcode_M42();
  5137. break;
  5138. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5139. case 48: // M48 Z probe repeatability
  5140. gcode_M48();
  5141. break;
  5142. #endif // AUTO_BED_LEVELING_FEATURE && Z_MIN_PROBE_REPEATABILITY_TEST
  5143. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  5144. case 100:
  5145. gcode_M100();
  5146. break;
  5147. #endif
  5148. case 104: // M104
  5149. gcode_M104();
  5150. break;
  5151. case 110: // M110: Set Current Line Number
  5152. gcode_M110();
  5153. break;
  5154. case 111: // M111: Set debug level
  5155. gcode_M111();
  5156. break;
  5157. case 112: // M112: Emergency Stop
  5158. gcode_M112();
  5159. break;
  5160. case 140: // M140: Set bed temp
  5161. gcode_M140();
  5162. break;
  5163. case 105: // M105: Read current temperature
  5164. gcode_M105();
  5165. return; // "ok" already printed
  5166. case 109: // M109: Wait for temperature
  5167. gcode_M109();
  5168. break;
  5169. #if HAS_TEMP_BED
  5170. case 190: // M190: Wait for bed heater to reach target
  5171. gcode_M190();
  5172. break;
  5173. #endif // HAS_TEMP_BED
  5174. #if FAN_COUNT > 0
  5175. case 106: // M106: Fan On
  5176. gcode_M106();
  5177. break;
  5178. case 107: // M107: Fan Off
  5179. gcode_M107();
  5180. break;
  5181. #endif // FAN_COUNT > 0
  5182. #if ENABLED(BARICUDA)
  5183. // PWM for HEATER_1_PIN
  5184. #if HAS_HEATER_1
  5185. case 126: // M126: valve open
  5186. gcode_M126();
  5187. break;
  5188. case 127: // M127: valve closed
  5189. gcode_M127();
  5190. break;
  5191. #endif // HAS_HEATER_1
  5192. // PWM for HEATER_2_PIN
  5193. #if HAS_HEATER_2
  5194. case 128: // M128: valve open
  5195. gcode_M128();
  5196. break;
  5197. case 129: // M129: valve closed
  5198. gcode_M129();
  5199. break;
  5200. #endif // HAS_HEATER_2
  5201. #endif // BARICUDA
  5202. #if HAS_POWER_SWITCH
  5203. case 80: // M80: Turn on Power Supply
  5204. gcode_M80();
  5205. break;
  5206. #endif // HAS_POWER_SWITCH
  5207. case 81: // M81: Turn off Power, including Power Supply, if possible
  5208. gcode_M81();
  5209. break;
  5210. case 82:
  5211. gcode_M82();
  5212. break;
  5213. case 83:
  5214. gcode_M83();
  5215. break;
  5216. case 18: // (for compatibility)
  5217. case 84: // M84
  5218. gcode_M18_M84();
  5219. break;
  5220. case 85: // M85
  5221. gcode_M85();
  5222. break;
  5223. case 92: // M92: Set the steps-per-unit for one or more axes
  5224. gcode_M92();
  5225. break;
  5226. case 115: // M115: Report capabilities
  5227. gcode_M115();
  5228. break;
  5229. case 117: // M117: Set LCD message text, if possible
  5230. gcode_M117();
  5231. break;
  5232. case 114: // M114: Report current position
  5233. gcode_M114();
  5234. break;
  5235. case 120: // M120: Enable endstops
  5236. gcode_M120();
  5237. break;
  5238. case 121: // M121: Disable endstops
  5239. gcode_M121();
  5240. break;
  5241. case 119: // M119: Report endstop states
  5242. gcode_M119();
  5243. break;
  5244. #if ENABLED(ULTIPANEL)
  5245. case 145: // M145: Set material heatup parameters
  5246. gcode_M145();
  5247. break;
  5248. #endif
  5249. #if ENABLED(BLINKM)
  5250. case 150: // M150
  5251. gcode_M150();
  5252. break;
  5253. #endif //BLINKM
  5254. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5255. gcode_M200();
  5256. break;
  5257. case 201: // M201
  5258. gcode_M201();
  5259. break;
  5260. #if 0 // Not used for Sprinter/grbl gen6
  5261. case 202: // M202
  5262. gcode_M202();
  5263. break;
  5264. #endif
  5265. case 203: // M203 max feedrate mm/sec
  5266. gcode_M203();
  5267. break;
  5268. case 204: // M204 acclereration S normal moves T filmanent only moves
  5269. gcode_M204();
  5270. break;
  5271. case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk
  5272. gcode_M205();
  5273. break;
  5274. case 206: // M206 additional homing offset
  5275. gcode_M206();
  5276. break;
  5277. #if ENABLED(DELTA)
  5278. case 665: // M665 set delta configurations L<diagonal_rod> R<delta_radius> S<segments_per_sec>
  5279. gcode_M665();
  5280. break;
  5281. #endif
  5282. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  5283. case 666: // M666 set delta / dual endstop adjustment
  5284. gcode_M666();
  5285. break;
  5286. #endif
  5287. #if ENABLED(FWRETRACT)
  5288. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  5289. gcode_M207();
  5290. break;
  5291. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  5292. gcode_M208();
  5293. break;
  5294. case 209: // M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  5295. gcode_M209();
  5296. break;
  5297. #endif // FWRETRACT
  5298. #if EXTRUDERS > 1
  5299. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  5300. gcode_M218();
  5301. break;
  5302. #endif
  5303. case 220: // M220 S<factor in percent>- set speed factor override percentage
  5304. gcode_M220();
  5305. break;
  5306. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  5307. gcode_M221();
  5308. break;
  5309. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  5310. gcode_M226();
  5311. break;
  5312. #if HAS_SERVOS
  5313. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  5314. gcode_M280();
  5315. break;
  5316. #endif // HAS_SERVOS
  5317. #if HAS_BUZZER
  5318. case 300: // M300 - Play beep tone
  5319. gcode_M300();
  5320. break;
  5321. #endif // HAS_BUZZER
  5322. #if ENABLED(PIDTEMP)
  5323. case 301: // M301
  5324. gcode_M301();
  5325. break;
  5326. #endif // PIDTEMP
  5327. #if ENABLED(PIDTEMPBED)
  5328. case 304: // M304
  5329. gcode_M304();
  5330. break;
  5331. #endif // PIDTEMPBED
  5332. #if defined(CHDK) || HAS_PHOTOGRAPH
  5333. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  5334. gcode_M240();
  5335. break;
  5336. #endif // CHDK || PHOTOGRAPH_PIN
  5337. #if ENABLED(HAS_LCD_CONTRAST)
  5338. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  5339. gcode_M250();
  5340. break;
  5341. #endif // HAS_LCD_CONTRAST
  5342. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5343. case 302: // allow cold extrudes, or set the minimum extrude temperature
  5344. gcode_M302();
  5345. break;
  5346. #endif // PREVENT_DANGEROUS_EXTRUDE
  5347. case 303: // M303 PID autotune
  5348. gcode_M303();
  5349. break;
  5350. #if ENABLED(SCARA)
  5351. case 360: // M360 SCARA Theta pos1
  5352. if (gcode_M360()) return;
  5353. break;
  5354. case 361: // M361 SCARA Theta pos2
  5355. if (gcode_M361()) return;
  5356. break;
  5357. case 362: // M362 SCARA Psi pos1
  5358. if (gcode_M362()) return;
  5359. break;
  5360. case 363: // M363 SCARA Psi pos2
  5361. if (gcode_M363()) return;
  5362. break;
  5363. case 364: // M364 SCARA Psi pos3 (90 deg to Theta)
  5364. if (gcode_M364()) return;
  5365. break;
  5366. case 365: // M365 Set SCARA scaling for X Y Z
  5367. gcode_M365();
  5368. break;
  5369. #endif // SCARA
  5370. case 400: // M400 finish all moves
  5371. gcode_M400();
  5372. break;
  5373. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && (HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY)) && DISABLED(Z_PROBE_SLED)
  5374. case 401:
  5375. gcode_M401();
  5376. break;
  5377. case 402:
  5378. gcode_M402();
  5379. break;
  5380. #endif // AUTO_BED_LEVELING_FEATURE && (HAS_SERVO_ENDSTOPS || Z_PROBE_ALLEN_KEY) && !Z_PROBE_SLED
  5381. #if ENABLED(FILAMENT_SENSOR)
  5382. case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  5383. gcode_M404();
  5384. break;
  5385. case 405: //M405 Turn on filament sensor for control
  5386. gcode_M405();
  5387. break;
  5388. case 406: //M406 Turn off filament sensor for control
  5389. gcode_M406();
  5390. break;
  5391. case 407: //M407 Display measured filament diameter
  5392. gcode_M407();
  5393. break;
  5394. #endif // FILAMENT_SENSOR
  5395. case 410: // M410 quickstop - Abort all the planned moves.
  5396. gcode_M410();
  5397. break;
  5398. #if ENABLED(MESH_BED_LEVELING)
  5399. case 420: // M420 Enable/Disable Mesh Bed Leveling
  5400. gcode_M420();
  5401. break;
  5402. case 421: // M421 Set a Mesh Bed Leveling Z coordinate
  5403. gcode_M421();
  5404. break;
  5405. #endif
  5406. case 428: // M428 Apply current_position to home_offset
  5407. gcode_M428();
  5408. break;
  5409. case 500: // M500 Store settings in EEPROM
  5410. gcode_M500();
  5411. break;
  5412. case 501: // M501 Read settings from EEPROM
  5413. gcode_M501();
  5414. break;
  5415. case 502: // M502 Revert to default settings
  5416. gcode_M502();
  5417. break;
  5418. case 503: // M503 print settings currently in memory
  5419. gcode_M503();
  5420. break;
  5421. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  5422. case 540:
  5423. gcode_M540();
  5424. break;
  5425. #endif
  5426. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5427. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  5428. gcode_SET_Z_PROBE_OFFSET();
  5429. break;
  5430. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5431. #if ENABLED(FILAMENTCHANGEENABLE)
  5432. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  5433. gcode_M600();
  5434. break;
  5435. #endif // FILAMENTCHANGEENABLE
  5436. #if ENABLED(DUAL_X_CARRIAGE)
  5437. case 605:
  5438. gcode_M605();
  5439. break;
  5440. #endif // DUAL_X_CARRIAGE
  5441. case 907: // M907 Set digital trimpot motor current using axis codes.
  5442. gcode_M907();
  5443. break;
  5444. #if HAS_DIGIPOTSS
  5445. case 908: // M908 Control digital trimpot directly.
  5446. gcode_M908();
  5447. break;
  5448. #endif // HAS_DIGIPOTSS
  5449. #if HAS_MICROSTEPS
  5450. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  5451. gcode_M350();
  5452. break;
  5453. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  5454. gcode_M351();
  5455. break;
  5456. #endif // HAS_MICROSTEPS
  5457. case 999: // M999: Restart after being Stopped
  5458. gcode_M999();
  5459. break;
  5460. }
  5461. break;
  5462. case 'T':
  5463. gcode_T(codenum);
  5464. break;
  5465. default: code_is_good = false;
  5466. }
  5467. KEEPALIVE_STATE(NOT_BUSY);
  5468. ExitUnknownCommand:
  5469. // Still unknown command? Throw an error
  5470. if (!code_is_good) unknown_command_error();
  5471. ok_to_send();
  5472. }
  5473. void FlushSerialRequestResend() {
  5474. //char command_queue[cmd_queue_index_r][100]="Resend:";
  5475. MYSERIAL.flush();
  5476. SERIAL_PROTOCOLPGM(MSG_RESEND);
  5477. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  5478. ok_to_send();
  5479. }
  5480. void ok_to_send() {
  5481. refresh_cmd_timeout();
  5482. if (!send_ok[cmd_queue_index_r]) return;
  5483. SERIAL_PROTOCOLPGM(MSG_OK);
  5484. #if ENABLED(ADVANCED_OK)
  5485. char* p = command_queue[cmd_queue_index_r];
  5486. if (*p == 'N') {
  5487. SERIAL_PROTOCOL(' ');
  5488. SERIAL_ECHO(*p++);
  5489. while ((*p >= '0' && *p <= '9') || *p == '-')
  5490. SERIAL_ECHO(*p++);
  5491. }
  5492. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - movesplanned() - 1));
  5493. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  5494. #endif
  5495. SERIAL_EOL;
  5496. }
  5497. void clamp_to_software_endstops(float target[3]) {
  5498. if (min_software_endstops) {
  5499. NOLESS(target[X_AXIS], min_pos[X_AXIS]);
  5500. NOLESS(target[Y_AXIS], min_pos[Y_AXIS]);
  5501. float negative_z_offset = 0;
  5502. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5503. if (zprobe_zoffset < 0) negative_z_offset += zprobe_zoffset;
  5504. if (home_offset[Z_AXIS] < 0) {
  5505. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5506. if (marlin_debug_flags & DEBUG_LEVELING) {
  5507. SERIAL_ECHOPAIR("> clamp_to_software_endstops > Add home_offset[Z_AXIS]:", home_offset[Z_AXIS]);
  5508. SERIAL_EOL;
  5509. }
  5510. #endif
  5511. negative_z_offset += home_offset[Z_AXIS];
  5512. }
  5513. #endif
  5514. NOLESS(target[Z_AXIS], min_pos[Z_AXIS] + negative_z_offset);
  5515. }
  5516. if (max_software_endstops) {
  5517. NOMORE(target[X_AXIS], max_pos[X_AXIS]);
  5518. NOMORE(target[Y_AXIS], max_pos[Y_AXIS]);
  5519. NOMORE(target[Z_AXIS], max_pos[Z_AXIS]);
  5520. }
  5521. }
  5522. #if ENABLED(DELTA)
  5523. void recalc_delta_settings(float radius, float diagonal_rod) {
  5524. delta_tower1_x = -SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  5525. delta_tower1_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1);
  5526. delta_tower2_x = SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  5527. delta_tower2_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2);
  5528. delta_tower3_x = 0.0; // back middle tower
  5529. delta_tower3_y = (radius + DELTA_RADIUS_TRIM_TOWER_3);
  5530. delta_diagonal_rod_2_tower_1 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_1);
  5531. delta_diagonal_rod_2_tower_2 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_2);
  5532. delta_diagonal_rod_2_tower_3 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_3);
  5533. }
  5534. void calculate_delta(float cartesian[3]) {
  5535. delta[TOWER_1] = sqrt(delta_diagonal_rod_2_tower_1
  5536. - sq(delta_tower1_x - cartesian[X_AXIS])
  5537. - sq(delta_tower1_y - cartesian[Y_AXIS])
  5538. ) + cartesian[Z_AXIS];
  5539. delta[TOWER_2] = sqrt(delta_diagonal_rod_2_tower_2
  5540. - sq(delta_tower2_x - cartesian[X_AXIS])
  5541. - sq(delta_tower2_y - cartesian[Y_AXIS])
  5542. ) + cartesian[Z_AXIS];
  5543. delta[TOWER_3] = sqrt(delta_diagonal_rod_2_tower_3
  5544. - sq(delta_tower3_x - cartesian[X_AXIS])
  5545. - sq(delta_tower3_y - cartesian[Y_AXIS])
  5546. ) + cartesian[Z_AXIS];
  5547. /*
  5548. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  5549. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  5550. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  5551. SERIAL_ECHOPGM("delta a="); SERIAL_ECHO(delta[TOWER_1]);
  5552. SERIAL_ECHOPGM(" b="); SERIAL_ECHO(delta[TOWER_2]);
  5553. SERIAL_ECHOPGM(" c="); SERIAL_ECHOLN(delta[TOWER_3]);
  5554. */
  5555. }
  5556. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5557. // Adjust print surface height by linear interpolation over the bed_level array.
  5558. void adjust_delta(float cartesian[3]) {
  5559. if (delta_grid_spacing[0] == 0 || delta_grid_spacing[1] == 0) return; // G29 not done!
  5560. int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2;
  5561. float h1 = 0.001 - half, h2 = half - 0.001,
  5562. grid_x = max(h1, min(h2, cartesian[X_AXIS] / delta_grid_spacing[0])),
  5563. grid_y = max(h1, min(h2, cartesian[Y_AXIS] / delta_grid_spacing[1]));
  5564. int floor_x = floor(grid_x), floor_y = floor(grid_y);
  5565. float ratio_x = grid_x - floor_x, ratio_y = grid_y - floor_y,
  5566. z1 = bed_level[floor_x + half][floor_y + half],
  5567. z2 = bed_level[floor_x + half][floor_y + half + 1],
  5568. z3 = bed_level[floor_x + half + 1][floor_y + half],
  5569. z4 = bed_level[floor_x + half + 1][floor_y + half + 1],
  5570. left = (1 - ratio_y) * z1 + ratio_y * z2,
  5571. right = (1 - ratio_y) * z3 + ratio_y * z4,
  5572. offset = (1 - ratio_x) * left + ratio_x * right;
  5573. delta[X_AXIS] += offset;
  5574. delta[Y_AXIS] += offset;
  5575. delta[Z_AXIS] += offset;
  5576. /*
  5577. SERIAL_ECHOPGM("grid_x="); SERIAL_ECHO(grid_x);
  5578. SERIAL_ECHOPGM(" grid_y="); SERIAL_ECHO(grid_y);
  5579. SERIAL_ECHOPGM(" floor_x="); SERIAL_ECHO(floor_x);
  5580. SERIAL_ECHOPGM(" floor_y="); SERIAL_ECHO(floor_y);
  5581. SERIAL_ECHOPGM(" ratio_x="); SERIAL_ECHO(ratio_x);
  5582. SERIAL_ECHOPGM(" ratio_y="); SERIAL_ECHO(ratio_y);
  5583. SERIAL_ECHOPGM(" z1="); SERIAL_ECHO(z1);
  5584. SERIAL_ECHOPGM(" z2="); SERIAL_ECHO(z2);
  5585. SERIAL_ECHOPGM(" z3="); SERIAL_ECHO(z3);
  5586. SERIAL_ECHOPGM(" z4="); SERIAL_ECHO(z4);
  5587. SERIAL_ECHOPGM(" left="); SERIAL_ECHO(left);
  5588. SERIAL_ECHOPGM(" right="); SERIAL_ECHO(right);
  5589. SERIAL_ECHOPGM(" offset="); SERIAL_ECHOLN(offset);
  5590. */
  5591. }
  5592. #endif // AUTO_BED_LEVELING_FEATURE
  5593. #endif // DELTA
  5594. #if ENABLED(MESH_BED_LEVELING)
  5595. // This function is used to split lines on mesh borders so each segment is only part of one mesh area
  5596. void mesh_plan_buffer_line(float x, float y, float z, const float e, float feed_rate, const uint8_t& extruder, uint8_t x_splits = 0xff, uint8_t y_splits = 0xff) {
  5597. if (!mbl.active) {
  5598. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5599. set_current_to_destination();
  5600. return;
  5601. }
  5602. int pix = mbl.select_x_index(current_position[X_AXIS]);
  5603. int piy = mbl.select_y_index(current_position[Y_AXIS]);
  5604. int ix = mbl.select_x_index(x);
  5605. int iy = mbl.select_y_index(y);
  5606. pix = min(pix, MESH_NUM_X_POINTS - 2);
  5607. piy = min(piy, MESH_NUM_Y_POINTS - 2);
  5608. ix = min(ix, MESH_NUM_X_POINTS - 2);
  5609. iy = min(iy, MESH_NUM_Y_POINTS - 2);
  5610. if (pix == ix && piy == iy) {
  5611. // Start and end on same mesh square
  5612. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5613. set_current_to_destination();
  5614. return;
  5615. }
  5616. float nx, ny, nz, ne, normalized_dist;
  5617. if (ix > pix && TEST(x_splits, ix)) {
  5618. nx = mbl.get_x(ix);
  5619. normalized_dist = (nx - current_position[X_AXIS]) / (x - current_position[X_AXIS]);
  5620. ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist;
  5621. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5622. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5623. CBI(x_splits, ix);
  5624. }
  5625. else if (ix < pix && TEST(x_splits, pix)) {
  5626. nx = mbl.get_x(pix);
  5627. normalized_dist = (nx - current_position[X_AXIS]) / (x - current_position[X_AXIS]);
  5628. ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist;
  5629. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5630. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5631. CBI(x_splits, pix);
  5632. }
  5633. else if (iy > piy && TEST(y_splits, iy)) {
  5634. ny = mbl.get_y(iy);
  5635. normalized_dist = (ny - current_position[Y_AXIS]) / (y - current_position[Y_AXIS]);
  5636. nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist;
  5637. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5638. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5639. CBI(y_splits, iy);
  5640. }
  5641. else if (iy < piy && TEST(y_splits, piy)) {
  5642. ny = mbl.get_y(piy);
  5643. normalized_dist = (ny - current_position[Y_AXIS]) / (y - current_position[Y_AXIS]);
  5644. nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist;
  5645. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5646. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5647. CBI(y_splits, piy);
  5648. }
  5649. else {
  5650. // Already split on a border
  5651. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5652. set_current_to_destination();
  5653. return;
  5654. }
  5655. // Do the split and look for more borders
  5656. destination[X_AXIS] = nx;
  5657. destination[Y_AXIS] = ny;
  5658. destination[Z_AXIS] = nz;
  5659. destination[E_AXIS] = ne;
  5660. mesh_plan_buffer_line(nx, ny, nz, ne, feed_rate, extruder, x_splits, y_splits);
  5661. destination[X_AXIS] = x;
  5662. destination[Y_AXIS] = y;
  5663. destination[Z_AXIS] = z;
  5664. destination[E_AXIS] = e;
  5665. mesh_plan_buffer_line(x, y, z, e, feed_rate, extruder, x_splits, y_splits);
  5666. }
  5667. #endif // MESH_BED_LEVELING
  5668. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5669. inline void prevent_dangerous_extrude(float& curr_e, float& dest_e) {
  5670. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  5671. float de = dest_e - curr_e;
  5672. if (de) {
  5673. if (degHotend(active_extruder) < extrude_min_temp) {
  5674. curr_e = dest_e; // Behave as if the move really took place, but ignore E part
  5675. SERIAL_ECHO_START;
  5676. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  5677. }
  5678. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  5679. if (labs(de) > EXTRUDE_MAXLENGTH) {
  5680. curr_e = dest_e; // Behave as if the move really took place, but ignore E part
  5681. SERIAL_ECHO_START;
  5682. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  5683. }
  5684. #endif
  5685. }
  5686. }
  5687. #endif // PREVENT_DANGEROUS_EXTRUDE
  5688. #if ENABLED(DELTA) || ENABLED(SCARA)
  5689. inline bool prepare_move_delta(float target[NUM_AXIS]) {
  5690. float difference[NUM_AXIS];
  5691. for (int8_t i = 0; i < NUM_AXIS; i++) difference[i] = target[i] - current_position[i];
  5692. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  5693. if (cartesian_mm < 0.000001) cartesian_mm = abs(difference[E_AXIS]);
  5694. if (cartesian_mm < 0.000001) return false;
  5695. float seconds = 6000 * cartesian_mm / feedrate / feedrate_multiplier;
  5696. int steps = max(1, int(delta_segments_per_second * seconds));
  5697. // SERIAL_ECHOPGM("mm="); SERIAL_ECHO(cartesian_mm);
  5698. // SERIAL_ECHOPGM(" seconds="); SERIAL_ECHO(seconds);
  5699. // SERIAL_ECHOPGM(" steps="); SERIAL_ECHOLN(steps);
  5700. for (int s = 1; s <= steps; s++) {
  5701. float fraction = float(s) / float(steps);
  5702. for (int8_t i = 0; i < NUM_AXIS; i++)
  5703. target[i] = current_position[i] + difference[i] * fraction;
  5704. calculate_delta(target);
  5705. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5706. adjust_delta(target);
  5707. #endif
  5708. //SERIAL_ECHOPGM("target[X_AXIS]="); SERIAL_ECHOLN(target[X_AXIS]);
  5709. //SERIAL_ECHOPGM("target[Y_AXIS]="); SERIAL_ECHOLN(target[Y_AXIS]);
  5710. //SERIAL_ECHOPGM("target[Z_AXIS]="); SERIAL_ECHOLN(target[Z_AXIS]);
  5711. //SERIAL_ECHOPGM("delta[X_AXIS]="); SERIAL_ECHOLN(delta[X_AXIS]);
  5712. //SERIAL_ECHOPGM("delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]);
  5713. //SERIAL_ECHOPGM("delta[Z_AXIS]="); SERIAL_ECHOLN(delta[Z_AXIS]);
  5714. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], feedrate / 60 * feedrate_multiplier / 100.0, active_extruder);
  5715. }
  5716. return true;
  5717. }
  5718. #endif // DELTA || SCARA
  5719. #if ENABLED(SCARA)
  5720. inline bool prepare_move_scara(float target[NUM_AXIS]) { return prepare_move_delta(target); }
  5721. #endif
  5722. #if ENABLED(DUAL_X_CARRIAGE)
  5723. inline bool prepare_move_dual_x_carriage() {
  5724. if (active_extruder_parked) {
  5725. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) {
  5726. // move duplicate extruder into correct duplication position.
  5727. plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  5728. plan_buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset,
  5729. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[X_AXIS], 1);
  5730. sync_plan_position();
  5731. st_synchronize();
  5732. extruder_duplication_enabled = true;
  5733. active_extruder_parked = false;
  5734. }
  5735. else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { // handle unparking of head
  5736. if (current_position[E_AXIS] == destination[E_AXIS]) {
  5737. // This is a travel move (with no extrusion)
  5738. // Skip it, but keep track of the current position
  5739. // (so it can be used as the start of the next non-travel move)
  5740. if (delayed_move_time != 0xFFFFFFFFUL) {
  5741. set_current_to_destination();
  5742. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  5743. delayed_move_time = millis();
  5744. return false;
  5745. }
  5746. }
  5747. delayed_move_time = 0;
  5748. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  5749. plan_buffer_line(raised_parked_position[X_AXIS], raised_parked_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  5750. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], min(max_feedrate[X_AXIS], max_feedrate[Y_AXIS]), active_extruder);
  5751. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  5752. active_extruder_parked = false;
  5753. }
  5754. }
  5755. return true;
  5756. }
  5757. #endif // DUAL_X_CARRIAGE
  5758. #if DISABLED(DELTA) && DISABLED(SCARA)
  5759. inline bool prepare_move_cartesian() {
  5760. // Do not use feedrate_multiplier for E or Z only moves
  5761. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS]) {
  5762. line_to_destination();
  5763. }
  5764. else {
  5765. #if ENABLED(MESH_BED_LEVELING)
  5766. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], (feedrate / 60) * (feedrate_multiplier / 100.0), active_extruder);
  5767. return false;
  5768. #else
  5769. line_to_destination(feedrate * feedrate_multiplier / 100.0);
  5770. #endif
  5771. }
  5772. return true;
  5773. }
  5774. #endif // !DELTA && !SCARA
  5775. /**
  5776. * Prepare a single move and get ready for the next one
  5777. *
  5778. * (This may call plan_buffer_line several times to put
  5779. * smaller moves into the planner for DELTA or SCARA.)
  5780. */
  5781. void prepare_move() {
  5782. clamp_to_software_endstops(destination);
  5783. refresh_cmd_timeout();
  5784. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5785. prevent_dangerous_extrude(current_position[E_AXIS], destination[E_AXIS]);
  5786. #endif
  5787. #if ENABLED(SCARA)
  5788. if (!prepare_move_scara(destination)) return;
  5789. #elif ENABLED(DELTA)
  5790. if (!prepare_move_delta(destination)) return;
  5791. #endif
  5792. #if ENABLED(DUAL_X_CARRIAGE)
  5793. if (!prepare_move_dual_x_carriage()) return;
  5794. #endif
  5795. #if DISABLED(DELTA) && DISABLED(SCARA)
  5796. if (!prepare_move_cartesian()) return;
  5797. #endif
  5798. set_current_to_destination();
  5799. }
  5800. /**
  5801. * Plan an arc in 2 dimensions
  5802. *
  5803. * The arc is approximated by generating many small linear segments.
  5804. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  5805. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  5806. * larger segments will tend to be more efficient. Your slicer should have
  5807. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  5808. */
  5809. void plan_arc(
  5810. float target[NUM_AXIS], // Destination position
  5811. float* offset, // Center of rotation relative to current_position
  5812. uint8_t clockwise // Clockwise?
  5813. ) {
  5814. float radius = hypot(offset[X_AXIS], offset[Y_AXIS]),
  5815. center_axis0 = current_position[X_AXIS] + offset[X_AXIS],
  5816. center_axis1 = current_position[Y_AXIS] + offset[Y_AXIS],
  5817. linear_travel = target[Z_AXIS] - current_position[Z_AXIS],
  5818. extruder_travel = target[E_AXIS] - current_position[E_AXIS],
  5819. r_axis0 = -offset[X_AXIS], // Radius vector from center to current location
  5820. r_axis1 = -offset[Y_AXIS],
  5821. rt_axis0 = target[X_AXIS] - center_axis0,
  5822. rt_axis1 = target[Y_AXIS] - center_axis1;
  5823. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  5824. float angular_travel = atan2(r_axis0 * rt_axis1 - r_axis1 * rt_axis0, r_axis0 * rt_axis0 + r_axis1 * rt_axis1);
  5825. if (angular_travel < 0) angular_travel += RADIANS(360);
  5826. if (clockwise) angular_travel -= RADIANS(360);
  5827. // Make a circle if the angular rotation is 0
  5828. if (current_position[X_AXIS] == target[X_AXIS] && current_position[Y_AXIS] == target[Y_AXIS] && angular_travel == 0)
  5829. angular_travel += RADIANS(360);
  5830. float mm_of_travel = hypot(angular_travel * radius, fabs(linear_travel));
  5831. if (mm_of_travel < 0.001) return;
  5832. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  5833. if (segments == 0) segments = 1;
  5834. float theta_per_segment = angular_travel / segments;
  5835. float linear_per_segment = linear_travel / segments;
  5836. float extruder_per_segment = extruder_travel / segments;
  5837. /* Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  5838. and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  5839. r_T = [cos(phi) -sin(phi);
  5840. sin(phi) cos(phi] * r ;
  5841. For arc generation, the center of the circle is the axis of rotation and the radius vector is
  5842. defined from the circle center to the initial position. Each line segment is formed by successive
  5843. vector rotations. This requires only two cos() and sin() computations to form the rotation
  5844. matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  5845. all double numbers are single precision on the Arduino. (True double precision will not have
  5846. round off issues for CNC applications.) Single precision error can accumulate to be greater than
  5847. tool precision in some cases. Therefore, arc path correction is implemented.
  5848. Small angle approximation may be used to reduce computation overhead further. This approximation
  5849. holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  5850. theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  5851. to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  5852. numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  5853. issue for CNC machines with the single precision Arduino calculations.
  5854. This approximation also allows plan_arc to immediately insert a line segment into the planner
  5855. without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  5856. a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  5857. This is important when there are successive arc motions.
  5858. */
  5859. // Vector rotation matrix values
  5860. float cos_T = 1 - 0.5 * theta_per_segment * theta_per_segment; // Small angle approximation
  5861. float sin_T = theta_per_segment;
  5862. float arc_target[NUM_AXIS];
  5863. float sin_Ti;
  5864. float cos_Ti;
  5865. float r_axisi;
  5866. uint16_t i;
  5867. int8_t count = 0;
  5868. // Initialize the linear axis
  5869. arc_target[Z_AXIS] = current_position[Z_AXIS];
  5870. // Initialize the extruder axis
  5871. arc_target[E_AXIS] = current_position[E_AXIS];
  5872. float feed_rate = feedrate * feedrate_multiplier / 60 / 100.0;
  5873. for (i = 1; i < segments; i++) { // Increment (segments-1)
  5874. if (count < N_ARC_CORRECTION) {
  5875. // Apply vector rotation matrix to previous r_axis0 / 1
  5876. r_axisi = r_axis0 * sin_T + r_axis1 * cos_T;
  5877. r_axis0 = r_axis0 * cos_T - r_axis1 * sin_T;
  5878. r_axis1 = r_axisi;
  5879. count++;
  5880. }
  5881. else {
  5882. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  5883. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  5884. cos_Ti = cos(i * theta_per_segment);
  5885. sin_Ti = sin(i * theta_per_segment);
  5886. r_axis0 = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  5887. r_axis1 = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  5888. count = 0;
  5889. }
  5890. // Update arc_target location
  5891. arc_target[X_AXIS] = center_axis0 + r_axis0;
  5892. arc_target[Y_AXIS] = center_axis1 + r_axis1;
  5893. arc_target[Z_AXIS] += linear_per_segment;
  5894. arc_target[E_AXIS] += extruder_per_segment;
  5895. clamp_to_software_endstops(arc_target);
  5896. #if ENABLED(DELTA) || ENABLED(SCARA)
  5897. calculate_delta(arc_target);
  5898. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5899. adjust_delta(arc_target);
  5900. #endif
  5901. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], arc_target[E_AXIS], feed_rate, active_extruder);
  5902. #else
  5903. plan_buffer_line(arc_target[X_AXIS], arc_target[Y_AXIS], arc_target[Z_AXIS], arc_target[E_AXIS], feed_rate, active_extruder);
  5904. #endif
  5905. }
  5906. // Ensure last segment arrives at target location.
  5907. #if ENABLED(DELTA) || ENABLED(SCARA)
  5908. calculate_delta(target);
  5909. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5910. adjust_delta(target);
  5911. #endif
  5912. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], feed_rate, active_extruder);
  5913. #else
  5914. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feed_rate, active_extruder);
  5915. #endif
  5916. // As far as the parser is concerned, the position is now == target. In reality the
  5917. // motion control system might still be processing the action and the real tool position
  5918. // in any intermediate location.
  5919. set_current_to_destination();
  5920. }
  5921. #if HAS_CONTROLLERFAN
  5922. void controllerFan() {
  5923. static millis_t lastMotor = 0; // Last time a motor was turned on
  5924. static millis_t lastMotorCheck = 0; // Last time the state was checked
  5925. millis_t ms = millis();
  5926. if (ms >= lastMotorCheck + 2500) { // Not a time critical function, so we only check every 2500ms
  5927. lastMotorCheck = ms;
  5928. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || soft_pwm_bed > 0
  5929. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  5930. #if EXTRUDERS > 1
  5931. || E1_ENABLE_READ == E_ENABLE_ON
  5932. #if HAS_X2_ENABLE
  5933. || X2_ENABLE_READ == X_ENABLE_ON
  5934. #endif
  5935. #if EXTRUDERS > 2
  5936. || E2_ENABLE_READ == E_ENABLE_ON
  5937. #if EXTRUDERS > 3
  5938. || E3_ENABLE_READ == E_ENABLE_ON
  5939. #endif
  5940. #endif
  5941. #endif
  5942. ) {
  5943. lastMotor = ms; //... set time to NOW so the fan will turn on
  5944. }
  5945. uint8_t speed = (lastMotor == 0 || ms >= lastMotor + ((CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  5946. // allows digital or PWM fan output to be used (see M42 handling)
  5947. digitalWrite(CONTROLLERFAN_PIN, speed);
  5948. analogWrite(CONTROLLERFAN_PIN, speed);
  5949. }
  5950. }
  5951. #endif // HAS_CONTROLLERFAN
  5952. #if ENABLED(SCARA)
  5953. void calculate_SCARA_forward_Transform(float f_scara[3]) {
  5954. // Perform forward kinematics, and place results in delta[3]
  5955. // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014
  5956. float x_sin, x_cos, y_sin, y_cos;
  5957. //SERIAL_ECHOPGM("f_delta x="); SERIAL_ECHO(f_scara[X_AXIS]);
  5958. //SERIAL_ECHOPGM(" y="); SERIAL_ECHO(f_scara[Y_AXIS]);
  5959. x_sin = sin(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1;
  5960. x_cos = cos(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1;
  5961. y_sin = sin(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2;
  5962. y_cos = cos(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2;
  5963. //SERIAL_ECHOPGM(" x_sin="); SERIAL_ECHO(x_sin);
  5964. //SERIAL_ECHOPGM(" x_cos="); SERIAL_ECHO(x_cos);
  5965. //SERIAL_ECHOPGM(" y_sin="); SERIAL_ECHO(y_sin);
  5966. //SERIAL_ECHOPGM(" y_cos="); SERIAL_ECHOLN(y_cos);
  5967. delta[X_AXIS] = x_cos + y_cos + SCARA_offset_x; //theta
  5968. delta[Y_AXIS] = x_sin + y_sin + SCARA_offset_y; //theta+phi
  5969. //SERIAL_ECHOPGM(" delta[X_AXIS]="); SERIAL_ECHO(delta[X_AXIS]);
  5970. //SERIAL_ECHOPGM(" delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]);
  5971. }
  5972. void calculate_delta(float cartesian[3]) {
  5973. //reverse kinematics.
  5974. // Perform reversed kinematics, and place results in delta[3]
  5975. // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014
  5976. float SCARA_pos[2];
  5977. static float SCARA_C2, SCARA_S2, SCARA_K1, SCARA_K2, SCARA_theta, SCARA_psi;
  5978. SCARA_pos[X_AXIS] = cartesian[X_AXIS] * axis_scaling[X_AXIS] - SCARA_offset_x; //Translate SCARA to standard X Y
  5979. SCARA_pos[Y_AXIS] = cartesian[Y_AXIS] * axis_scaling[Y_AXIS] - SCARA_offset_y; // With scaling factor.
  5980. #if (Linkage_1 == Linkage_2)
  5981. SCARA_C2 = ((sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS])) / (2 * (float)L1_2)) - 1;
  5982. #else
  5983. SCARA_C2 = (sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) - (float)L1_2 - (float)L2_2) / 45000;
  5984. #endif
  5985. SCARA_S2 = sqrt(1 - sq(SCARA_C2));
  5986. SCARA_K1 = Linkage_1 + Linkage_2 * SCARA_C2;
  5987. SCARA_K2 = Linkage_2 * SCARA_S2;
  5988. SCARA_theta = (atan2(SCARA_pos[X_AXIS], SCARA_pos[Y_AXIS]) - atan2(SCARA_K1, SCARA_K2)) * -1;
  5989. SCARA_psi = atan2(SCARA_S2, SCARA_C2);
  5990. delta[X_AXIS] = SCARA_theta * SCARA_RAD2DEG; // Multiply by 180/Pi - theta is support arm angle
  5991. delta[Y_AXIS] = (SCARA_theta + SCARA_psi) * SCARA_RAD2DEG; // - equal to sub arm angle (inverted motor)
  5992. delta[Z_AXIS] = cartesian[Z_AXIS];
  5993. /*
  5994. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  5995. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  5996. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  5997. SERIAL_ECHOPGM("scara x="); SERIAL_ECHO(SCARA_pos[X_AXIS]);
  5998. SERIAL_ECHOPGM(" y="); SERIAL_ECHOLN(SCARA_pos[Y_AXIS]);
  5999. SERIAL_ECHOPGM("delta x="); SERIAL_ECHO(delta[X_AXIS]);
  6000. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(delta[Y_AXIS]);
  6001. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(delta[Z_AXIS]);
  6002. SERIAL_ECHOPGM("C2="); SERIAL_ECHO(SCARA_C2);
  6003. SERIAL_ECHOPGM(" S2="); SERIAL_ECHO(SCARA_S2);
  6004. SERIAL_ECHOPGM(" Theta="); SERIAL_ECHO(SCARA_theta);
  6005. SERIAL_ECHOPGM(" Psi="); SERIAL_ECHOLN(SCARA_psi);
  6006. SERIAL_EOL;
  6007. */
  6008. }
  6009. #endif // SCARA
  6010. #if ENABLED(TEMP_STAT_LEDS)
  6011. static bool red_led = false;
  6012. static millis_t next_status_led_update_ms = 0;
  6013. void handle_status_leds(void) {
  6014. float max_temp = 0.0;
  6015. if (millis() > next_status_led_update_ms) {
  6016. next_status_led_update_ms += 500; // Update every 0.5s
  6017. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder)
  6018. max_temp = max(max(max_temp, degHotend(cur_extruder)), degTargetHotend(cur_extruder));
  6019. #if HAS_TEMP_BED
  6020. max_temp = max(max(max_temp, degTargetBed()), degBed());
  6021. #endif
  6022. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  6023. if (new_led != red_led) {
  6024. red_led = new_led;
  6025. digitalWrite(STAT_LED_RED, new_led ? HIGH : LOW);
  6026. digitalWrite(STAT_LED_BLUE, new_led ? LOW : HIGH);
  6027. }
  6028. }
  6029. }
  6030. #endif
  6031. void enable_all_steppers() {
  6032. enable_x();
  6033. enable_y();
  6034. enable_z();
  6035. enable_e0();
  6036. enable_e1();
  6037. enable_e2();
  6038. enable_e3();
  6039. }
  6040. void disable_all_steppers() {
  6041. disable_x();
  6042. disable_y();
  6043. disable_z();
  6044. disable_e0();
  6045. disable_e1();
  6046. disable_e2();
  6047. disable_e3();
  6048. }
  6049. /**
  6050. * Standard idle routine keeps the machine alive
  6051. */
  6052. void idle(
  6053. #if ENABLED(FILAMENTCHANGEENABLE)
  6054. bool no_stepper_sleep/*=false*/
  6055. #endif
  6056. ) {
  6057. manage_heater();
  6058. manage_inactivity(
  6059. #if ENABLED(FILAMENTCHANGEENABLE)
  6060. no_stepper_sleep
  6061. #endif
  6062. );
  6063. host_keepalive();
  6064. lcd_update();
  6065. }
  6066. /**
  6067. * Manage several activities:
  6068. * - Check for Filament Runout
  6069. * - Keep the command buffer full
  6070. * - Check for maximum inactive time between commands
  6071. * - Check for maximum inactive time between stepper commands
  6072. * - Check if pin CHDK needs to go LOW
  6073. * - Check for KILL button held down
  6074. * - Check for HOME button held down
  6075. * - Check if cooling fan needs to be switched on
  6076. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  6077. */
  6078. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  6079. #if HAS_FILRUNOUT
  6080. if (IS_SD_PRINTING && !(READ(FILRUNOUT_PIN) ^ FIL_RUNOUT_INVERTING))
  6081. filrunout();
  6082. #endif
  6083. if (commands_in_queue < BUFSIZE) get_command();
  6084. millis_t ms = millis();
  6085. if (max_inactive_time && ms > previous_cmd_ms + max_inactive_time) kill(PSTR(MSG_KILLED));
  6086. if (stepper_inactive_time && ms > previous_cmd_ms + stepper_inactive_time
  6087. && !ignore_stepper_queue && !blocks_queued()) {
  6088. #if ENABLED(DISABLE_INACTIVE_X)
  6089. disable_x();
  6090. #endif
  6091. #if ENABLED(DISABLE_INACTIVE_Y)
  6092. disable_y();
  6093. #endif
  6094. #if ENABLED(DISABLE_INACTIVE_Z)
  6095. disable_z();
  6096. #endif
  6097. #if ENABLED(DISABLE_INACTIVE_E)
  6098. disable_e0();
  6099. disable_e1();
  6100. disable_e2();
  6101. disable_e3();
  6102. #endif
  6103. }
  6104. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  6105. if (chdkActive && ms > chdkHigh + CHDK_DELAY) {
  6106. chdkActive = false;
  6107. WRITE(CHDK, LOW);
  6108. }
  6109. #endif
  6110. #if HAS_KILL
  6111. // Check if the kill button was pressed and wait just in case it was an accidental
  6112. // key kill key press
  6113. // -------------------------------------------------------------------------------
  6114. static int killCount = 0; // make the inactivity button a bit less responsive
  6115. const int KILL_DELAY = 750;
  6116. if (!READ(KILL_PIN))
  6117. killCount++;
  6118. else if (killCount > 0)
  6119. killCount--;
  6120. // Exceeded threshold and we can confirm that it was not accidental
  6121. // KILL the machine
  6122. // ----------------------------------------------------------------
  6123. if (killCount >= KILL_DELAY) kill(PSTR(MSG_KILLED));
  6124. #endif
  6125. #if HAS_HOME
  6126. // Check to see if we have to home, use poor man's debouncer
  6127. // ---------------------------------------------------------
  6128. static int homeDebounceCount = 0; // poor man's debouncing count
  6129. const int HOME_DEBOUNCE_DELAY = 2500;
  6130. if (!READ(HOME_PIN)) {
  6131. if (!homeDebounceCount) {
  6132. enqueue_and_echo_commands_P(PSTR("G28"));
  6133. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  6134. }
  6135. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  6136. homeDebounceCount++;
  6137. else
  6138. homeDebounceCount = 0;
  6139. }
  6140. #endif
  6141. #if HAS_CONTROLLERFAN
  6142. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  6143. #endif
  6144. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  6145. if (ms > previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000)
  6146. if (degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  6147. bool oldstatus;
  6148. switch (active_extruder) {
  6149. case 0:
  6150. oldstatus = E0_ENABLE_READ;
  6151. enable_e0();
  6152. break;
  6153. #if EXTRUDERS > 1
  6154. case 1:
  6155. oldstatus = E1_ENABLE_READ;
  6156. enable_e1();
  6157. break;
  6158. #if EXTRUDERS > 2
  6159. case 2:
  6160. oldstatus = E2_ENABLE_READ;
  6161. enable_e2();
  6162. break;
  6163. #if EXTRUDERS > 3
  6164. case 3:
  6165. oldstatus = E3_ENABLE_READ;
  6166. enable_e3();
  6167. break;
  6168. #endif
  6169. #endif
  6170. #endif
  6171. }
  6172. float oldepos = current_position[E_AXIS], oldedes = destination[E_AXIS];
  6173. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  6174. destination[E_AXIS] + (EXTRUDER_RUNOUT_EXTRUDE) * (EXTRUDER_RUNOUT_ESTEPS) / axis_steps_per_unit[E_AXIS],
  6175. (EXTRUDER_RUNOUT_SPEED) / 60. * (EXTRUDER_RUNOUT_ESTEPS) / axis_steps_per_unit[E_AXIS], active_extruder);
  6176. current_position[E_AXIS] = oldepos;
  6177. destination[E_AXIS] = oldedes;
  6178. plan_set_e_position(oldepos);
  6179. previous_cmd_ms = ms; // refresh_cmd_timeout()
  6180. st_synchronize();
  6181. switch (active_extruder) {
  6182. case 0:
  6183. E0_ENABLE_WRITE(oldstatus);
  6184. break;
  6185. #if EXTRUDERS > 1
  6186. case 1:
  6187. E1_ENABLE_WRITE(oldstatus);
  6188. break;
  6189. #if EXTRUDERS > 2
  6190. case 2:
  6191. E2_ENABLE_WRITE(oldstatus);
  6192. break;
  6193. #if EXTRUDERS > 3
  6194. case 3:
  6195. E3_ENABLE_WRITE(oldstatus);
  6196. break;
  6197. #endif
  6198. #endif
  6199. #endif
  6200. }
  6201. }
  6202. #endif
  6203. #if ENABLED(DUAL_X_CARRIAGE)
  6204. // handle delayed move timeout
  6205. if (delayed_move_time && ms > delayed_move_time + 1000 && IsRunning()) {
  6206. // travel moves have been received so enact them
  6207. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  6208. set_destination_to_current();
  6209. prepare_move();
  6210. }
  6211. #endif
  6212. #if ENABLED(TEMP_STAT_LEDS)
  6213. handle_status_leds();
  6214. #endif
  6215. check_axes_activity();
  6216. }
  6217. void kill(const char* lcd_msg) {
  6218. #if ENABLED(ULTRA_LCD)
  6219. lcd_setalertstatuspgm(lcd_msg);
  6220. #else
  6221. UNUSED(lcd_msg);
  6222. #endif
  6223. cli(); // Stop interrupts
  6224. disable_all_heaters();
  6225. disable_all_steppers();
  6226. #if HAS_POWER_SWITCH
  6227. pinMode(PS_ON_PIN, INPUT);
  6228. #endif
  6229. SERIAL_ERROR_START;
  6230. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  6231. // FMC small patch to update the LCD before ending
  6232. sei(); // enable interrupts
  6233. for (int i = 5; i--; lcd_update()) delay(200); // Wait a short time
  6234. cli(); // disable interrupts
  6235. suicide();
  6236. while (1) {
  6237. #if ENABLED(USE_WATCHDOG)
  6238. watchdog_reset();
  6239. #endif
  6240. } // Wait for reset
  6241. }
  6242. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6243. void filrunout() {
  6244. if (!filrunoutEnqueued) {
  6245. filrunoutEnqueued = true;
  6246. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  6247. st_synchronize();
  6248. }
  6249. }
  6250. #endif // FILAMENT_RUNOUT_SENSOR
  6251. #if ENABLED(FAST_PWM_FAN)
  6252. void setPwmFrequency(uint8_t pin, int val) {
  6253. val &= 0x07;
  6254. switch (digitalPinToTimer(pin)) {
  6255. #if defined(TCCR0A)
  6256. case TIMER0A:
  6257. case TIMER0B:
  6258. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  6259. // TCCR0B |= val;
  6260. break;
  6261. #endif
  6262. #if defined(TCCR1A)
  6263. case TIMER1A:
  6264. case TIMER1B:
  6265. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  6266. // TCCR1B |= val;
  6267. break;
  6268. #endif
  6269. #if defined(TCCR2)
  6270. case TIMER2:
  6271. case TIMER2:
  6272. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  6273. TCCR2 |= val;
  6274. break;
  6275. #endif
  6276. #if defined(TCCR2A)
  6277. case TIMER2A:
  6278. case TIMER2B:
  6279. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  6280. TCCR2B |= val;
  6281. break;
  6282. #endif
  6283. #if defined(TCCR3A)
  6284. case TIMER3A:
  6285. case TIMER3B:
  6286. case TIMER3C:
  6287. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  6288. TCCR3B |= val;
  6289. break;
  6290. #endif
  6291. #if defined(TCCR4A)
  6292. case TIMER4A:
  6293. case TIMER4B:
  6294. case TIMER4C:
  6295. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  6296. TCCR4B |= val;
  6297. break;
  6298. #endif
  6299. #if defined(TCCR5A)
  6300. case TIMER5A:
  6301. case TIMER5B:
  6302. case TIMER5C:
  6303. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  6304. TCCR5B |= val;
  6305. break;
  6306. #endif
  6307. }
  6308. }
  6309. #endif // FAST_PWM_FAN
  6310. void Stop() {
  6311. disable_all_heaters();
  6312. if (IsRunning()) {
  6313. Running = false;
  6314. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  6315. SERIAL_ERROR_START;
  6316. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  6317. LCD_MESSAGEPGM(MSG_STOPPED);
  6318. }
  6319. }
  6320. /**
  6321. * Set target_extruder from the T parameter or the active_extruder
  6322. *
  6323. * Returns TRUE if the target is invalid
  6324. */
  6325. bool setTargetedHotend(int code) {
  6326. target_extruder = active_extruder;
  6327. if (code_seen('T')) {
  6328. target_extruder = code_value_short();
  6329. if (target_extruder >= EXTRUDERS) {
  6330. SERIAL_ECHO_START;
  6331. SERIAL_CHAR('M');
  6332. SERIAL_ECHO(code);
  6333. SERIAL_ECHOPGM(" " MSG_INVALID_EXTRUDER " ");
  6334. SERIAL_ECHOLN(target_extruder);
  6335. return true;
  6336. }
  6337. }
  6338. return false;
  6339. }
  6340. float calculate_volumetric_multiplier(float diameter) {
  6341. if (!volumetric_enabled || diameter == 0) return 1.0;
  6342. float d2 = diameter * 0.5;
  6343. return 1.0 / (M_PI * d2 * d2);
  6344. }
  6345. void calculate_volumetric_multipliers() {
  6346. for (int i = 0; i < EXTRUDERS; i++)
  6347. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  6348. }