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

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