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

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