Marlin_main.cpp 387 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642
  1. /* -*- c++ -*- */
  2. /**
  3. * @file
  4. */
  5. /**
  6. * @mainpage Reprap 3D printer firmware based on Sprinter and grbl.
  7. *
  8. * @section intro_sec Introduction
  9. *
  10. * This firmware is a mashup between Sprinter and grbl.
  11. * https://github.com/kliment/Sprinter
  12. * https://github.com/simen/grbl/tree
  13. *
  14. * It has preliminary support for Matthew Roberts advance algorithm
  15. * http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  16. *
  17. * Prusa Research s.r.o. https://www.prusa3d.cz
  18. *
  19. * @section copyright_sec Copyright
  20. *
  21. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  22. *
  23. * This program is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation, either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  35. *
  36. * @section notes_sec Notes
  37. *
  38. * * Do not create static objects in global functions.
  39. * Otherwise constructor guard against concurrent calls is generated costing
  40. * about 8B RAM and 14B flash.
  41. *
  42. *
  43. */
  44. //-//
  45. #include "Configuration.h"
  46. #include "Marlin.h"
  47. #include "config.h"
  48. #include "macros.h"
  49. #ifdef ENABLE_AUTO_BED_LEVELING
  50. #include "vector_3.h"
  51. #ifdef AUTO_BED_LEVELING_GRID
  52. #include "qr_solve.h"
  53. #endif
  54. #endif // ENABLE_AUTO_BED_LEVELING
  55. #ifdef MESH_BED_LEVELING
  56. #include "mesh_bed_leveling.h"
  57. #include "mesh_bed_calibration.h"
  58. #endif
  59. #include "printers.h"
  60. #include "menu.h"
  61. #include "ultralcd.h"
  62. #include "backlight.h"
  63. #include "planner.h"
  64. #include "stepper.h"
  65. #include "temperature.h"
  66. #include "fancheck.h"
  67. #include "motion_control.h"
  68. #include "cardreader.h"
  69. #include "ConfigurationStore.h"
  70. #include "language.h"
  71. #include "math.h"
  72. #include "util.h"
  73. #include "Timer.h"
  74. #include "Prusa_farm.h"
  75. #include <avr/wdt.h>
  76. #include <util/atomic.h>
  77. #include <avr/pgmspace.h>
  78. #include "Tcodes.h"
  79. #include "Dcodes.h"
  80. #include "SpoolJoin.h"
  81. #ifndef LA_NOCOMPAT
  82. #include "la10compat.h"
  83. #endif
  84. #include "spi.h"
  85. #include "Filament_sensor.h"
  86. #ifdef TMC2130
  87. #include "tmc2130.h"
  88. #endif //TMC2130
  89. #ifdef XFLASH
  90. #include "xflash.h"
  91. #include "optiboot_xflash.h"
  92. #endif //XFLASH
  93. #include "xflash_dump.h"
  94. #ifdef BLINKM
  95. #include "BlinkM.h"
  96. #include "Wire.h"
  97. #endif
  98. #if NUM_SERVOS > 0
  99. #include "Servo.h"
  100. #endif
  101. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  102. #include <SPI.h>
  103. #endif
  104. #include "mmu2.h"
  105. #define VERSION_STRING "1.0.2"
  106. #include "sound.h"
  107. #include "cmdqueue.h"
  108. //Macro for print fan speed
  109. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  110. //filament types
  111. #define FILAMENT_DEFAULT 0
  112. #define FILAMENT_FLEX 1
  113. #define FILAMENT_PVA 2
  114. #define FILAMENT_UNDEFINED 255
  115. //Stepper Movement Variables
  116. //===========================================================================
  117. //=============================imported variables============================
  118. //===========================================================================
  119. //===========================================================================
  120. //=============================public variables=============================
  121. //===========================================================================
  122. #ifdef SDSUPPORT
  123. CardReader card;
  124. #endif
  125. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  126. //used for PINDA temp calibration and pause print
  127. #define DEFAULT_RETRACTION 1
  128. #define DEFAULT_RETRACTION_MM 4 //MM
  129. float default_retraction = DEFAULT_RETRACTION;
  130. float homing_feedrate[] = HOMING_FEEDRATE;
  131. //Although this flag and many others like this could be represented with a struct/bitfield for each axis (more readable and efficient code), the implementation
  132. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  133. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  134. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  135. uint8_t axis_relative_modes = 0;
  136. int feedmultiply=100; //100->1 200->2
  137. int extrudemultiply=100; //100->1 200->2
  138. int extruder_multiply[EXTRUDERS] = {100
  139. #if EXTRUDERS > 1
  140. , 100
  141. #if EXTRUDERS > 2
  142. , 100
  143. #endif
  144. #endif
  145. };
  146. bool homing_flag = false;
  147. unsigned long pause_time = 0;
  148. unsigned long start_pause_print = _millis();
  149. unsigned long t_fan_rising_edge = _millis();
  150. LongTimer safetyTimer;
  151. static LongTimer crashDetTimer;
  152. //unsigned long load_filament_time;
  153. bool mesh_bed_leveling_flag = false;
  154. unsigned long total_filament_used;
  155. HeatingStatus heating_status;
  156. uint8_t heating_status_counter;
  157. bool loading_flag = false;
  158. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  159. bool fan_state[2];
  160. int fan_edge_counter[2];
  161. int fan_speed[2];
  162. float extruder_multiplier[EXTRUDERS] = {1.0
  163. #if EXTRUDERS > 1
  164. , 1.0
  165. #if EXTRUDERS > 2
  166. , 1.0
  167. #endif
  168. #endif
  169. };
  170. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  171. //shortcuts for more readable code
  172. #define _x current_position[X_AXIS]
  173. #define _y current_position[Y_AXIS]
  174. #define _z current_position[Z_AXIS]
  175. #define _e current_position[E_AXIS]
  176. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  177. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  178. bool axis_known_position[3] = {false, false, false};
  179. // Extruder offset
  180. #if EXTRUDERS > 1
  181. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  182. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  183. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  184. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  185. #endif
  186. };
  187. #endif
  188. int fanSpeed=0;
  189. uint8_t newFanSpeed = 0;
  190. #ifdef FWRETRACT
  191. bool retracted[EXTRUDERS]={false
  192. #if EXTRUDERS > 1
  193. , false
  194. #if EXTRUDERS > 2
  195. , false
  196. #endif
  197. #endif
  198. };
  199. bool retracted_swap[EXTRUDERS]={false
  200. #if EXTRUDERS > 1
  201. , false
  202. #if EXTRUDERS > 2
  203. , false
  204. #endif
  205. #endif
  206. };
  207. float retract_length_swap = RETRACT_LENGTH_SWAP;
  208. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  209. #endif
  210. #ifdef PS_DEFAULT_OFF
  211. bool powersupply = false;
  212. #else
  213. bool powersupply = true;
  214. #endif
  215. bool cancel_heatup = false;
  216. int8_t busy_state = NOT_BUSY;
  217. static long prev_busy_signal_ms = -1;
  218. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  219. const char errormagic[] PROGMEM = "Error:";
  220. const char echomagic[] PROGMEM = "echo:";
  221. const char G28W0[] PROGMEM = "G28 W0";
  222. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  223. // that they can be used later for various logical checks
  224. #define X_COORD_INVALID (X_MIN_POS-1)
  225. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  226. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  227. uint16_t saved_segment_idx = 0;
  228. // storing estimated time to end of print counted by slicer
  229. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  230. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  231. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  232. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  233. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  234. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  235. uint32_t IP_address = 0;
  236. //===========================================================================
  237. //=============================Private Variables=============================
  238. //===========================================================================
  239. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  240. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  241. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  242. // For tracing an arc
  243. static float offset[3] = {0.0, 0.0, 0.0};
  244. // Current feedrate
  245. float feedrate = 1500.0;
  246. // Feedrate for the next move
  247. static float next_feedrate;
  248. // Original feedrate saved during homing moves
  249. static float saved_feedrate;
  250. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  251. //static float tt = 0;
  252. //static float bt = 0;
  253. //Inactivity shutdown variables
  254. static LongTimer previous_millis_cmd;
  255. unsigned long max_inactive_time = 0;
  256. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  257. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  258. unsigned long starttime=0;
  259. unsigned long stoptime=0;
  260. ShortTimer usb_timer;
  261. bool Stopped=false;
  262. #if NUM_SERVOS > 0
  263. Servo servos[NUM_SERVOS];
  264. #endif
  265. bool target_direction;
  266. //Insert variables if CHDK is defined
  267. #ifdef CHDK
  268. unsigned long chdkHigh = 0;
  269. bool chdkActive = false;
  270. #endif
  271. //! @name RAM save/restore printing
  272. //! @{
  273. bool saved_printing = false; //!< Print is paused and saved in RAM
  274. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  275. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  276. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  277. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  278. static int saved_feedmultiply2 = 0;
  279. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  280. float saved_bed_temperature = 0.0;
  281. static bool saved_extruder_relative_mode = false;
  282. int saved_fan_speed = 0; //!< Print fan speed
  283. //! @}
  284. static int saved_feedmultiply_mm = 100;
  285. class AutoReportFeatures {
  286. union {
  287. struct {
  288. uint8_t temp : 1; //Temperature flag
  289. uint8_t fans : 1; //Fans flag
  290. uint8_t pos: 1; //Position flag
  291. uint8_t ar4 : 1; //Unused
  292. uint8_t ar5 : 1; //Unused
  293. uint8_t ar6 : 1; //Unused
  294. uint8_t ar7 : 1; //Unused
  295. } __attribute__((packed)) bits;
  296. uint8_t byte;
  297. } arFunctionsActive;
  298. uint8_t auto_report_period;
  299. public:
  300. LongTimer auto_report_timer;
  301. AutoReportFeatures():auto_report_period(0){
  302. #if defined(AUTO_REPORT)
  303. arFunctionsActive.byte = 0xff;
  304. #else
  305. arFunctionsActive.byte = 0;
  306. #endif //AUTO_REPORT
  307. }
  308. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  309. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  310. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  311. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  312. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  313. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  314. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  315. /// sets the autoreporting timer's period
  316. /// setting it to zero stops the timer
  317. void SetPeriod(uint8_t p){
  318. auto_report_period = p;
  319. if (auto_report_period != 0){
  320. auto_report_timer.start();
  321. } else{
  322. auto_report_timer.stop();
  323. }
  324. }
  325. inline void TimerStart() { auto_report_timer.start(); }
  326. inline bool TimerRunning()const { return auto_report_timer.running(); }
  327. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  328. };
  329. AutoReportFeatures autoReportFeatures;
  330. //===========================================================================
  331. //=============================Routines======================================
  332. //===========================================================================
  333. static bool setTargetedHotend(int code, uint8_t &extruder);
  334. static void print_time_remaining_init();
  335. static void wait_for_heater(long codenum, uint8_t extruder);
  336. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  337. static void gcode_M105(uint8_t extruder);
  338. #ifndef PINDA_THERMISTOR
  339. static void temp_compensation_start();
  340. static void temp_compensation_apply();
  341. #endif
  342. #ifdef PRUSA_SN_SUPPORT
  343. static uint8_t get_PRUSA_SN(char* SN);
  344. #endif //PRUSA_SN_SUPPORT
  345. uint16_t gcode_in_progress = 0;
  346. uint16_t mcode_in_progress = 0;
  347. void serial_echopair_P(const char *s_P, float v)
  348. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  349. void serial_echopair_P(const char *s_P, double v)
  350. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  351. void serial_echopair_P(const char *s_P, unsigned long v)
  352. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  353. void serialprintPGM(const char *str) {
  354. while(uint8_t ch = pgm_read_byte(str)) {
  355. MYSERIAL.write((char)ch);
  356. ++str;
  357. }
  358. }
  359. void serialprintlnPGM(const char *str) {
  360. serialprintPGM(str);
  361. MYSERIAL.println();
  362. }
  363. #ifdef SDSUPPORT
  364. #include "SdFatUtil.h"
  365. int freeMemory() { return SdFatUtil::FreeRam(); }
  366. #else
  367. extern "C" {
  368. extern unsigned int __bss_end;
  369. extern unsigned int __heap_start;
  370. extern void *__brkval;
  371. int freeMemory() {
  372. int free_memory;
  373. if ((int)__brkval == 0)
  374. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  375. else
  376. free_memory = ((int)&free_memory) - ((int)__brkval);
  377. return free_memory;
  378. }
  379. }
  380. #endif //!SDSUPPORT
  381. void setup_killpin()
  382. {
  383. #if defined(KILL_PIN) && KILL_PIN > -1
  384. SET_INPUT(KILL_PIN);
  385. WRITE(KILL_PIN,HIGH);
  386. #endif
  387. }
  388. // Set home pin
  389. void setup_homepin(void)
  390. {
  391. #if defined(HOME_PIN) && HOME_PIN > -1
  392. SET_INPUT(HOME_PIN);
  393. WRITE(HOME_PIN,HIGH);
  394. #endif
  395. }
  396. void setup_photpin()
  397. {
  398. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  399. SET_OUTPUT(PHOTOGRAPH_PIN);
  400. WRITE(PHOTOGRAPH_PIN, LOW);
  401. #endif
  402. }
  403. void setup_powerhold()
  404. {
  405. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  406. SET_OUTPUT(SUICIDE_PIN);
  407. WRITE(SUICIDE_PIN, HIGH);
  408. #endif
  409. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  410. SET_OUTPUT(PS_ON_PIN);
  411. #if defined(PS_DEFAULT_OFF)
  412. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  413. #else
  414. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  415. #endif
  416. #endif
  417. }
  418. void suicide()
  419. {
  420. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  421. SET_OUTPUT(SUICIDE_PIN);
  422. WRITE(SUICIDE_PIN, LOW);
  423. #endif
  424. }
  425. void servo_init()
  426. {
  427. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  428. servos[0].attach(SERVO0_PIN);
  429. #endif
  430. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  431. servos[1].attach(SERVO1_PIN);
  432. #endif
  433. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  434. servos[2].attach(SERVO2_PIN);
  435. #endif
  436. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  437. servos[3].attach(SERVO3_PIN);
  438. #endif
  439. #if (NUM_SERVOS >= 5)
  440. #error "TODO: enter initalisation code for more servos"
  441. #endif
  442. }
  443. bool __attribute__((noinline)) printer_active() {
  444. return IS_SD_PRINTING
  445. || usb_timer.running()
  446. || isPrintPaused
  447. || (custom_message_type == CustomMsg::TempCal)
  448. || saved_printing
  449. || (lcd_commands_type == LcdCommands::Layer1Cal)
  450. || MMU2::mmu2.MMU_PRINT_SAVED()
  451. || homing_flag
  452. || mesh_bed_leveling_flag;
  453. }
  454. // Currently only used in one place, allowed to be inlined
  455. bool check_fsensor() {
  456. return (IS_SD_PRINTING || usb_timer.running())
  457. && mcode_in_progress != 600
  458. && !saved_printing
  459. && e_active();
  460. }
  461. bool fans_check_enabled = true;
  462. #ifdef TMC2130
  463. void crashdet_stop_and_save_print()
  464. {
  465. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  466. }
  467. void crashdet_restore_print_and_continue()
  468. {
  469. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  470. // babystep_apply();
  471. }
  472. void crashdet_fmt_error(char* buf, uint8_t mask)
  473. {
  474. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  475. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  476. *buf++ = ' ';
  477. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  478. }
  479. void crashdet_detected(uint8_t mask)
  480. {
  481. st_synchronize();
  482. static uint8_t crashDet_counter = 0;
  483. static uint8_t crashDet_axes = 0;
  484. bool automatic_recovery_after_crash = true;
  485. char msg[LCD_WIDTH+1] = "";
  486. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  487. crashDet_counter = 0;
  488. }
  489. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  490. automatic_recovery_after_crash = false;
  491. }
  492. crashDetTimer.start();
  493. crashDet_axes |= mask;
  494. lcd_update_enable(true);
  495. lcd_clear();
  496. lcd_update(2);
  497. if (mask & X_AXIS_MASK)
  498. {
  499. eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_X);
  500. eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT);
  501. }
  502. if (mask & Y_AXIS_MASK)
  503. {
  504. eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_Y);
  505. eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT);
  506. }
  507. lcd_update_enable(true);
  508. lcd_update(2);
  509. // prepare the status message with the _current_ axes status
  510. crashdet_fmt_error(msg, mask);
  511. lcd_setstatus(msg);
  512. gcode_G28(true, true, false); //home X and Y
  513. if (automatic_recovery_after_crash) {
  514. enquecommand_P(PSTR("CRASH_RECOVER"));
  515. }else{
  516. setTargetHotend(0, active_extruder);
  517. // notify the user of *all* the axes previously affected, not just the last one
  518. lcd_update_enable(false);
  519. lcd_clear();
  520. crashdet_fmt_error(msg, crashDet_axes);
  521. crashDet_axes = 0;
  522. lcd_print(msg);
  523. // ask whether to resume printing
  524. lcd_set_cursor(0, 1);
  525. lcd_puts_P(_T(MSG_RESUME_PRINT));
  526. lcd_putc('?');
  527. uint8_t yesno = lcd_show_yes_no_and_wait(false);
  528. if (yesno == LCD_LEFT_BUTTON_CHOICE)
  529. {
  530. enquecommand_P(PSTR("CRASH_RECOVER"));
  531. }
  532. else // LCD_MIDDLE_BUTTON_CHOICE
  533. {
  534. enquecommand_P(PSTR("CRASH_CANCEL"));
  535. }
  536. }
  537. }
  538. void crashdet_recover()
  539. {
  540. crashdet_restore_print_and_continue();
  541. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  542. }
  543. void crashdet_cancel()
  544. {
  545. saved_printing = false;
  546. tmc2130_sg_stop_on_crash = true;
  547. if (saved_printing_type == PRINTING_TYPE_SD) {
  548. print_stop();
  549. }else if(saved_printing_type == PRINTING_TYPE_USB){
  550. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  551. cmdqueue_reset();
  552. }
  553. }
  554. #endif //TMC2130
  555. void failstats_reset_print()
  556. {
  557. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  558. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  559. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  560. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  561. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  562. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  563. }
  564. void watchdogEarlyDisable(void) {
  565. // Regardless if the watchdog support is enabled or not, disable the watchdog very early
  566. // after the program starts since there's no danger in doing this.
  567. // The reason for this is because old bootloaders might not handle the watchdog timer at all,
  568. // leaving it enabled when jumping to the program. This could cause another watchdog reset
  569. // during setup() if not handled properly. So to avoid any issue of this kind, stop the
  570. // watchdog timer manually.
  571. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  572. wdt_reset();
  573. MCUSR &= ~_BV(WDRF);
  574. wdt_disable();
  575. }
  576. }
  577. void softReset(void) {
  578. cli();
  579. #ifdef WATCHDOG
  580. // If the watchdog support is enabled, use that for resetting. The timeout value is customized
  581. // for each board since the miniRambo ships with a bootloader which doesn't properly handle the
  582. // WDT. In order to avoid bootlooping, the watchdog is set to a value large enough for the
  583. // usual timeout of the bootloader to pass.
  584. wdt_enable(WATCHDOG_SOFT_RESET_VALUE);
  585. #else
  586. #warning WATCHDOG not defined. See the following comment for more details about the implications
  587. // In case the watchdog is not enabled, the reset is acomplished by jumping to the bootloader
  588. // vector manually. This however is somewhat dangerous since the peripherals don't get reset
  589. // by this operation. Considering this is not going to be used in any production firmware,
  590. // it can be left as is and just be cautious with it. The only way to accomplish a peripheral
  591. // reset is by an external reset, by a watchdog reset or by a power cycle. All of these options
  592. // can't be accomplished just from software. One way to minimize the dangers of this is by
  593. // setting all dangerous pins to INPUT before jumping to the bootloader, but that still doesn't
  594. // reset other peripherals such as UART, timers, INT, PCINT, etc...
  595. asm volatile("jmp 0x3E000");
  596. #endif
  597. while(1);
  598. }
  599. #ifdef MESH_BED_LEVELING
  600. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  601. #endif
  602. static void factory_reset_stats(){
  603. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  604. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  605. failstats_reset_print();
  606. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  607. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  608. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  609. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  610. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  611. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  612. eeprom_update_dword((uint32_t *)EEPROM_TOTAL_TOOLCHANGE_COUNT, 0);
  613. }
  614. // Factory reset function
  615. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  616. // Level input parameter sets depth of reset
  617. static void factory_reset(char level)
  618. {
  619. lcd_clear();
  620. Sound_MakeCustom(100,0,false);
  621. switch (level) {
  622. case 0: // Level 0: Language reset
  623. lang_reset();
  624. break;
  625. case 1: //Level 1: Reset statistics
  626. factory_reset_stats();
  627. lcd_menu_statistics();
  628. break;
  629. case 2: // Level 2: Prepare for shipping
  630. factory_reset_stats();
  631. // FALLTHRU
  632. case 3: // Level 3: Preparation after being serviced
  633. // Force language selection at the next boot up.
  634. lang_reset();
  635. // Force the "Follow calibration flow" message at the next boot up.
  636. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  637. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  638. farm_disable();
  639. #ifdef FILAMENT_SENSOR
  640. fsensor.setEnabled(true);
  641. fsensor.setAutoLoadEnabled(true, true);
  642. fsensor.setRunoutEnabled(true, true);
  643. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  644. fsensor.setJamDetectionEnabled(true, true);
  645. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  646. #endif //FILAMENT_SENSOR
  647. break;
  648. case 4:
  649. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  650. // Erase EEPROM
  651. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  652. eeprom_update_byte((uint8_t*)i, 0xFF);
  653. menu_progressbar_update(i);
  654. }
  655. menu_progressbar_finish();
  656. softReset();
  657. break;
  658. default:
  659. break;
  660. }
  661. }
  662. extern "C" {
  663. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  664. }
  665. int uart_putchar(char c, FILE *)
  666. {
  667. MYSERIAL.write(c);
  668. return 0;
  669. }
  670. void lcd_splash()
  671. {
  672. lcd_clear(); // clears display and homes screen
  673. lcd_printf_P(PSTR("\n Original Prusa i3\n Prusa Research\n%20.20S"), PSTR(FW_VERSION));
  674. }
  675. void factory_reset()
  676. {
  677. KEEPALIVE_STATE(PAUSED_FOR_USER);
  678. if (!READ(BTN_ENC))
  679. {
  680. _delay_ms(1000);
  681. if (!READ(BTN_ENC))
  682. {
  683. lcd_clear();
  684. lcd_puts_P(PSTR("Factory RESET"));
  685. SET_OUTPUT(BEEPER);
  686. if(eSoundMode!=e_SOUND_MODE_SILENT)
  687. WRITE(BEEPER, HIGH);
  688. while (!READ(BTN_ENC));
  689. WRITE(BEEPER, LOW);
  690. _delay_ms(2000);
  691. char level = reset_menu();
  692. factory_reset(level);
  693. switch (level) {
  694. case 0:
  695. case 1:
  696. case 2:
  697. case 3:
  698. case 4: _delay_ms(0); break;
  699. }
  700. }
  701. }
  702. KEEPALIVE_STATE(IN_HANDLER);
  703. }
  704. #if 0
  705. void show_fw_version_warnings() {
  706. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  707. switch (FW_DEV_VERSION) {
  708. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(MSG_FW_VERSION_BETA); break;
  709. case(FW_VERSION_ALPHA):
  710. case(FW_VERSION_DEVEL):
  711. case(FW_VERSION_DEBUG):
  712. lcd_update_enable(false);
  713. lcd_clear();
  714. #if (FW_DEV_VERSION == FW_VERSION_DEVEL || FW_DEV_VERSION == FW_VERSION_ALPHA)
  715. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  716. #else
  717. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  718. #endif
  719. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  720. lcd_puts_at_P(0, 2, PSTR("FW")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  721. lcd_puts_at_P(0, 3, PSTR("Repo: ")); lcd_puts_P(PSTR(FW_REPOSITORY));
  722. lcd_wait_for_click();
  723. break;
  724. // default: lcd_show_fullscreen_message_and_wait_P(_i("WARNING: This is an unofficial, unsupported build. Use at your own risk!")); break;////MSG_FW_VERSION_UNKNOWN c=20 r=8
  725. }
  726. lcd_update_enable(true);
  727. }
  728. #endif
  729. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  730. //! @brief try to check if firmware is on right type of printer
  731. static void check_if_fw_is_on_right_printer() {
  732. if (fsensor.probeOtherType()) {
  733. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  734. }
  735. }
  736. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  737. uint8_t check_printer_version()
  738. {
  739. uint8_t version_changed = 0;
  740. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  741. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  742. if (printer_type != PRINTER_TYPE) {
  743. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  744. else version_changed |= 0b10;
  745. }
  746. if (motherboard != MOTHERBOARD) {
  747. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  748. else version_changed |= 0b01;
  749. }
  750. return version_changed;
  751. }
  752. #ifdef BOOTAPP
  753. #include "bootapp.h" //bootloader support
  754. #endif //BOOTAPP
  755. #if (LANG_MODE != 0) //secondary language support
  756. #ifdef XFLASH
  757. // language update from external flash
  758. #define LANGBOOT_BLOCKSIZE 0x1000u
  759. #define LANGBOOT_RAMBUFFER 0x0800
  760. void update_sec_lang_from_external_flash()
  761. {
  762. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  763. {
  764. uint8_t lang = boot_reserved >> 3;
  765. uint8_t state = boot_reserved & 0x07;
  766. lang_table_header_t header;
  767. uint32_t src_addr;
  768. if (lang_get_header(lang, &header, &src_addr))
  769. {
  770. lcd_puts_at_P(1,3,PSTR("Language update."));
  771. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  772. _delay(100);
  773. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  774. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  775. {
  776. cli();
  777. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  778. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  779. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  780. if (state == 0)
  781. {
  782. //TODO - check header integrity
  783. }
  784. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  785. }
  786. else
  787. {
  788. //TODO - check sec lang data integrity
  789. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  790. }
  791. }
  792. }
  793. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  794. }
  795. #ifdef DEBUG_XFLASH
  796. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  797. {
  798. lang_table_header_t header;
  799. uint8_t count = 0;
  800. uint32_t addr = 0x00000;
  801. while (1)
  802. {
  803. printf_P(_n("LANGTABLE%d:"), count);
  804. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  805. if (header.magic != LANG_MAGIC)
  806. {
  807. puts_P(_n("NG!"));
  808. break;
  809. }
  810. puts_P(_n("OK"));
  811. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  812. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  813. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  814. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  815. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  816. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  817. addr += header.size;
  818. codes[count] = header.code;
  819. count ++;
  820. }
  821. return count;
  822. }
  823. void list_sec_lang_from_external_flash()
  824. {
  825. uint16_t codes[8];
  826. uint8_t count = lang_xflash_enum_codes(codes);
  827. printf_P(_n("XFlash lang count = %hhd\n"), count);
  828. }
  829. #endif //DEBUG_XFLASH
  830. #endif //XFLASH
  831. #endif //(LANG_MODE != 0)
  832. static void fw_crash_init()
  833. {
  834. #ifdef XFLASH_DUMP
  835. dump_crash_reason crash_reason;
  836. if(xfdump_check_state(&crash_reason))
  837. {
  838. // always signal to the host that a dump is available for retrieval
  839. puts_P(_N("// action:dump_available"));
  840. #ifdef EMERGENCY_DUMP
  841. if(crash_reason != dump_crash_reason::manual &&
  842. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  843. {
  844. lcd_show_fullscreen_message_and_wait_P(
  845. _n("FW crash detected! "
  846. "You can continue printing. "
  847. "Debug data available for analysis. "
  848. "Contact support to submit details."));
  849. }
  850. #endif
  851. }
  852. #else //XFLASH_DUMP
  853. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  854. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  855. {
  856. lcd_beeper_quick_feedback();
  857. lcd_clear();
  858. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  859. switch(crash_reason)
  860. {
  861. case dump_crash_reason::stack_error:
  862. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  863. break;
  864. case dump_crash_reason::watchdog:
  865. lcd_puts_P(_n("Watchdog timeout"));
  866. break;
  867. case dump_crash_reason::bad_isr:
  868. lcd_puts_P(_n("Bad interrupt"));
  869. break;
  870. default:
  871. lcd_print((uint8_t)crash_reason);
  872. break;
  873. }
  874. lcd_wait_for_click();
  875. }
  876. #endif //XFLASH_DUMP
  877. // prevent crash prompts to reappear once acknowledged
  878. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  879. }
  880. static void xflash_err_msg()
  881. {
  882. puts_P(_n("XFLASH not responding."));
  883. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  884. }
  885. // "Setup" function is called by the Arduino framework on startup.
  886. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  887. // are initialized by the main() routine provided by the Arduino framework.
  888. void setup()
  889. {
  890. watchdogEarlyDisable();
  891. timer2_init(); // enables functional millis
  892. ultralcd_init();
  893. spi_init();
  894. lcd_splash();
  895. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  896. selectedSerialPort = eeprom_init_default_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, 0);
  897. MYSERIAL.begin(BAUDRATE);
  898. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  899. stdout = uartout;
  900. #ifdef XFLASH
  901. bool xflash_success = xflash_init();
  902. uint8_t optiboot_status = 1;
  903. if (xflash_success)
  904. {
  905. optiboot_status = optiboot_xflash_enter();
  906. #if (LANG_MODE != 0) //secondary language support
  907. update_sec_lang_from_external_flash();
  908. #endif //(LANG_MODE != 0)
  909. }
  910. #else
  911. const bool xflash_success = true;
  912. #endif //XFLASH
  913. setup_killpin();
  914. setup_powerhold();
  915. farm_mode_init();
  916. #ifdef TMC2130
  917. if( FarmOrUserECool() ){
  918. //increased extruder current (PFW363)
  919. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  920. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  921. }
  922. #endif //TMC2130
  923. #ifdef PRUSA_SN_SUPPORT
  924. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  925. //SN is valid only if it is NULL terminated and starts with "CZPX".
  926. {
  927. char SN[20];
  928. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  929. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  930. {
  931. if (!get_PRUSA_SN(SN))
  932. {
  933. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  934. puts_P(PSTR("SN updated"));
  935. }
  936. else
  937. puts_P(PSTR("SN update failed"));
  938. }
  939. }
  940. #endif //PRUSA_SN_SUPPORT
  941. #ifndef XFLASH
  942. SERIAL_PROTOCOLLNPGM("start");
  943. #else
  944. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  945. SERIAL_PROTOCOLLNPGM("start");
  946. #endif
  947. SERIAL_ECHO_START;
  948. puts_P(PSTR(" " FW_VERSION_FULL));
  949. if (eeprom_read_byte((uint8_t *)EEPROM_MMU_ENABLED)) {
  950. MMU2::mmu2.Start();
  951. }
  952. SpoolJoin::spooljoin.initSpoolJoinStatus();
  953. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  954. #ifdef DEBUG_SEC_LANG
  955. lang_table_header_t header;
  956. uint32_t src_addr = 0x00000;
  957. if (lang_get_header(1, &header, &src_addr))
  958. {
  959. printf_P(
  960. _n(
  961. " _src_addr = 0x%08lx\n"
  962. " _lt_magic = 0x%08lx %S\n"
  963. " _lt_size = 0x%04x (%d)\n"
  964. " _lt_count = 0x%04x (%d)\n"
  965. " _lt_chsum = 0x%04x\n"
  966. " _lt_code = 0x%04x (%c%c)\n"
  967. " _lt_resv1 = 0x%08lx\n"
  968. ),
  969. src_addr,
  970. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  971. header.size, header.size,
  972. header.count, header.count,
  973. header.checksum,
  974. header.code, header.code >> 8, header.code & 0xff,
  975. header.signature
  976. );
  977. #if 0
  978. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  979. for (uint16_t i = 0; i < 1024; i++)
  980. {
  981. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  982. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  983. if ((i % 16) == 15) putchar('\n');
  984. }
  985. #endif
  986. uint16_t sum = 0;
  987. for (uint16_t i = 0; i < header.size; i++)
  988. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  989. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  990. sum -= header.checksum; //subtract checksum
  991. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  992. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  993. if (sum == header.checksum)
  994. puts_P(_n("Checksum OK"));
  995. else
  996. puts_P(_n("Checksum NG"));
  997. }
  998. else
  999. puts_P(_n("lang_get_header failed!"));
  1000. #if 0
  1001. for (uint16_t i = 0; i < 1024*10; i++)
  1002. {
  1003. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  1004. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  1005. if ((i % 16) == 15) putchar('\n');
  1006. }
  1007. #endif
  1008. #if 0
  1009. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  1010. for (int i = 0; i < 4096; ++i) {
  1011. int b = eeprom_read_byte((unsigned char*)i);
  1012. if (b != 255) {
  1013. SERIAL_ECHO(i);
  1014. SERIAL_ECHO(":");
  1015. SERIAL_ECHO(b);
  1016. SERIAL_ECHOLN("");
  1017. }
  1018. }
  1019. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  1020. #endif
  1021. #endif //DEBUG_SEC_LANG
  1022. // Check startup - does nothing if bootloader sets MCUSR to 0
  1023. byte mcu = MCUSR;
  1024. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  1025. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  1026. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  1027. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1028. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1029. if (mcu & 1) puts_P(MSG_POWERUP);
  1030. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1031. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1032. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1033. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1034. MCUSR = 0;
  1035. //SERIAL_ECHORPGM(MSG_MARLIN);
  1036. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1037. #ifdef STRING_VERSION_CONFIG_H
  1038. #ifdef STRING_CONFIG_H_AUTHOR
  1039. SERIAL_ECHO_START;
  1040. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1041. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1042. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1043. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1044. #endif
  1045. #endif
  1046. SERIAL_ECHO_START;
  1047. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1048. SERIAL_ECHO(freeMemory());
  1049. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1050. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1051. //lcd_update_enable(false); // why do we need this?? - andre
  1052. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1053. bool previous_settings_retrieved = false;
  1054. uint8_t hw_changed = check_printer_version();
  1055. if (!(hw_changed & 0b10)) { //if printer version wasn't changed, check for eeprom version and retrieve settings from eeprom in case that version wasn't changed
  1056. previous_settings_retrieved = Config_RetrieveSettings();
  1057. }
  1058. else { //printer version was changed so use default settings
  1059. Config_ResetDefault();
  1060. }
  1061. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1062. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1063. // performed inside the soft_pwm_isr)
  1064. SdFatUtil::set_stack_guard();
  1065. // Initialize pwm/temperature loops
  1066. soft_pwm_init();
  1067. temp_mgr_init();
  1068. #ifdef EXTRUDER_ALTFAN_DETECT
  1069. SERIAL_ECHORPGM(_n("Hotend fan type: "));
  1070. if (extruder_altfan_detect())
  1071. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1072. else
  1073. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1074. #endif //EXTRUDER_ALTFAN_DETECT
  1075. plan_init(); // Initialize planner;
  1076. factory_reset();
  1077. eeprom_init_default_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1078. eeprom_init_default_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard if uninitialized
  1079. lcd_encoder_diff=0;
  1080. #ifdef TMC2130
  1081. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1082. if (silentMode == 0xff) silentMode = 0;
  1083. tmc2130_mode = TMC2130_MODE_NORMAL;
  1084. if (lcd_crash_detect_enabled() && !farm_mode)
  1085. {
  1086. lcd_crash_detect_enable();
  1087. puts_P(_N("CrashDetect ENABLED!"));
  1088. }
  1089. else
  1090. {
  1091. lcd_crash_detect_disable();
  1092. puts_P(_N("CrashDetect DISABLED"));
  1093. }
  1094. #ifdef TMC2130_LINEARITY_CORRECTION
  1095. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1096. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1097. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1098. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1099. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1100. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1101. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1102. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1103. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1104. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1105. #endif //TMC2130_LINEARITY_CORRECTION
  1106. #ifdef TMC2130_VARIABLE_RESOLUTION
  1107. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1108. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1109. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1110. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1111. #else //TMC2130_VARIABLE_RESOLUTION
  1112. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1113. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1114. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1115. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1116. #endif //TMC2130_VARIABLE_RESOLUTION
  1117. #endif //TMC2130
  1118. st_init(); // Initialize stepper, this enables interrupts!
  1119. #ifdef TMC2130
  1120. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1121. update_mode_profile();
  1122. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1123. #endif //TMC2130
  1124. #ifdef PSU_Delta
  1125. init_force_z(); // ! important for correct Z-axis initialization
  1126. #endif // PSU_Delta
  1127. setup_photpin();
  1128. #if 0
  1129. servo_init();
  1130. #endif
  1131. // Reset the machine correction matrix.
  1132. // It does not make sense to load the correction matrix until the machine is homed.
  1133. world2machine_reset();
  1134. // Initialize current_position accounting for software endstops to
  1135. // avoid unexpected initial shifts on the first move
  1136. clamp_to_software_endstops(current_position);
  1137. plan_set_position_curposXYZE();
  1138. // Show the xflash error message now that serial, lcd and encoder are available
  1139. if (!xflash_success)
  1140. xflash_err_msg();
  1141. #ifdef FILAMENT_SENSOR
  1142. fsensor.init();
  1143. #endif //FILAMENT_SENSOR
  1144. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1145. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1146. #endif
  1147. setup_homepin();
  1148. #if defined(Z_AXIS_ALWAYS_ON)
  1149. enable_z();
  1150. #endif
  1151. // The farm monitoring SW may accidentally expect
  1152. // 2 messages of "printer started" to consider a printer working.
  1153. prusa_statistics(8);
  1154. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1155. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1156. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1157. // but this times out if a blocking dialog is shown in setup().
  1158. card.initsd();
  1159. #ifdef DEBUG_SD_SPEED_TEST
  1160. if (card.cardOK)
  1161. {
  1162. uint8_t* buff = (uint8_t*)block_buffer;
  1163. uint32_t block = 0;
  1164. uint32_t sumr = 0;
  1165. uint32_t sumw = 0;
  1166. for (int i = 0; i < 1024; i++)
  1167. {
  1168. uint32_t u = _micros();
  1169. bool res = card.card.readBlock(i, buff);
  1170. u = _micros() - u;
  1171. if (res)
  1172. {
  1173. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1174. sumr += u;
  1175. u = _micros();
  1176. res = card.card.writeBlock(i, buff);
  1177. u = _micros() - u;
  1178. if (res)
  1179. {
  1180. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1181. sumw += u;
  1182. }
  1183. else
  1184. {
  1185. printf_P(PSTR("writeBlock %4d error\n"), i);
  1186. break;
  1187. }
  1188. }
  1189. else
  1190. {
  1191. printf_P(PSTR("readBlock %4d error\n"), i);
  1192. break;
  1193. }
  1194. }
  1195. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1196. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1197. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1198. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1199. }
  1200. else
  1201. printf_P(PSTR("Card NG!\n"));
  1202. #endif //DEBUG_SD_SPEED_TEST
  1203. eeprom_init();
  1204. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1205. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1206. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1207. #if (LANG_MODE != 0) //secondary language support
  1208. #ifdef DEBUG_XFLASH
  1209. XFLASH_SPI_ENTER();
  1210. uint8_t uid[8]; // 64bit unique id
  1211. xflash_rd_uid(uid);
  1212. puts_P(_n("XFLASH UID="));
  1213. for (uint8_t i = 0; i < 8; i ++)
  1214. printf_P(PSTR("%02x"), uid[i]);
  1215. putchar('\n');
  1216. list_sec_lang_from_external_flash();
  1217. #endif //DEBUG_XFLASH
  1218. // lang_reset();
  1219. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1220. lcd_language();
  1221. #ifdef DEBUG_SEC_LANG
  1222. uint16_t sec_lang_code = lang_get_code(1);
  1223. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1224. printf_P(_n("lang_selected=%d\nlang_table=0x%04x\nSEC_LANG_CODE=0x%04x (%c%c)\n"), lang_selected, ui, sec_lang_code, sec_lang_code >> 8, sec_lang_code & 0xff);
  1225. lang_print_sec_lang(uartout);
  1226. #endif //DEBUG_SEC_LANG
  1227. #endif //(LANG_MODE != 0)
  1228. eeprom_init_default_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1229. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1230. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1231. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1232. int16_t z_shift = 0;
  1233. for (uint8_t i = 0; i < 5; i++) {
  1234. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1235. }
  1236. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1237. }
  1238. eeprom_init_default_byte((uint8_t*)EEPROM_UVLO, 0);
  1239. eeprom_init_default_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1240. //mbl_mode_init();
  1241. mbl_settings_init();
  1242. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1243. if (SilentModeMenu_MMU == 255) {
  1244. SilentModeMenu_MMU = 1;
  1245. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1246. }
  1247. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1248. setup_fan_interrupt();
  1249. #endif //DEBUG_DISABLE_FANCHECK
  1250. #ifndef DEBUG_DISABLE_STARTMSGS
  1251. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1252. if (!farm_mode) {
  1253. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1254. check_if_fw_is_on_right_printer();
  1255. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1256. #if 0
  1257. show_fw_version_warnings();
  1258. #endif
  1259. }
  1260. switch (hw_changed) {
  1261. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1262. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1263. case(0b01):
  1264. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1265. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1266. break;
  1267. case(0b10):
  1268. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1269. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1270. break;
  1271. case(0b11):
  1272. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1273. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1274. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1275. break;
  1276. default: break; //no change, show no message
  1277. }
  1278. if (!previous_settings_retrieved) {
  1279. lcd_show_fullscreen_message_and_wait_P(_i("Old settings found. Default PID, Esteps etc. will be set.")); //if EEPROM version or printer type was changed, inform user that default setting were loaded////MSG_DEFAULT_SETTINGS_LOADED c=20 r=6
  1280. Config_StoreSettings();
  1281. }
  1282. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1283. lcd_wizard(WizState::Run);
  1284. }
  1285. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1286. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1287. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1288. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1289. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1290. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1291. // Show the message.
  1292. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1293. }
  1294. #ifdef TEMP_MODEL
  1295. else if (calibration_status() == CALIBRATION_STATUS_TEMP_MODEL_CALIBRATION) {
  1296. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TM_NOT_CAL));
  1297. lcd_update_enable(true);
  1298. }
  1299. #endif //TEMP_MODEL
  1300. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1301. // Show the message.
  1302. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1303. lcd_update_enable(true);
  1304. }
  1305. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1306. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1307. lcd_update_enable(true);
  1308. }
  1309. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1310. // Show the message.
  1311. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1312. }
  1313. }
  1314. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1315. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1316. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1317. update_current_firmware_version_to_eeprom();
  1318. lcd_selftest();
  1319. }
  1320. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1321. KEEPALIVE_STATE(IN_PROCESS);
  1322. #endif //DEBUG_DISABLE_STARTMSGS
  1323. lcd_update_enable(true);
  1324. lcd_clear();
  1325. lcd_update(2);
  1326. // Store the currently running firmware into an eeprom,
  1327. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1328. update_current_firmware_version_to_eeprom();
  1329. #ifdef TMC2130
  1330. tmc2130_home_origin[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN, 0);
  1331. tmc2130_home_bsteps[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS, 48);
  1332. tmc2130_home_fsteps[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS, 48);
  1333. tmc2130_home_origin[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN, 0);
  1334. tmc2130_home_bsteps[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS, 48);
  1335. tmc2130_home_fsteps[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS, 48);
  1336. tmc2130_home_enabled = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED, 0);
  1337. #endif //TMC2130
  1338. // report crash failures
  1339. fw_crash_init();
  1340. #ifdef UVLO_SUPPORT
  1341. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1342. /*
  1343. if (!lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1344. else {
  1345. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1346. lcd_update_enable(true);
  1347. lcd_update(2);
  1348. lcd_setstatuspgm(MSG_WELCOME);
  1349. }
  1350. */
  1351. manage_heater(); // Update temperatures
  1352. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1353. printf_P(_N("Power panic detected!\nCurrent bed temp:%d\nSaved bed temp:%d\n"), (int)degBed(), eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED));
  1354. #endif
  1355. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1356. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1357. puts_P(_N("Automatic recovery!"));
  1358. #endif
  1359. recover_print(1);
  1360. }
  1361. else{
  1362. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1363. puts_P(_N("Normal recovery!"));
  1364. #endif
  1365. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) == LCD_LEFT_BUTTON_CHOICE) {
  1366. recover_print(0);
  1367. } else {
  1368. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1369. lcd_update_enable(true);
  1370. lcd_update(2);
  1371. lcd_setstatuspgm(MSG_WELCOME);
  1372. }
  1373. }
  1374. }
  1375. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1376. // the entire state machine initialized.
  1377. setup_uvlo_interrupt();
  1378. #endif //UVLO_SUPPORT
  1379. fCheckModeInit();
  1380. KEEPALIVE_STATE(NOT_BUSY);
  1381. #ifdef WATCHDOG
  1382. wdt_enable(WDTO_4S);
  1383. #ifdef EMERGENCY_HANDLERS
  1384. WDTCSR |= (1 << WDIE);
  1385. #endif //EMERGENCY_HANDLERS
  1386. #endif //WATCHDOG
  1387. }
  1388. static inline void crash_and_burn(dump_crash_reason reason)
  1389. {
  1390. WRITE(BEEPER, HIGH);
  1391. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1392. #ifdef EMERGENCY_DUMP
  1393. xfdump_full_dump_and_reset(reason);
  1394. #elif defined(EMERGENCY_SERIAL_DUMP)
  1395. if(emergency_serial_dump)
  1396. serial_dump_and_reset(reason);
  1397. #endif
  1398. softReset();
  1399. }
  1400. #ifdef EMERGENCY_HANDLERS
  1401. #ifdef WATCHDOG
  1402. ISR(WDT_vect)
  1403. {
  1404. crash_and_burn(dump_crash_reason::watchdog);
  1405. }
  1406. #endif
  1407. ISR(BADISR_vect)
  1408. {
  1409. crash_and_burn(dump_crash_reason::bad_isr);
  1410. }
  1411. #endif //EMERGENCY_HANDLERS
  1412. void stack_error() {
  1413. crash_and_burn(dump_crash_reason::stack_error);
  1414. }
  1415. /**
  1416. * Output autoreport values according to features requested in M155
  1417. */
  1418. #if defined(AUTO_REPORT)
  1419. void host_autoreport()
  1420. {
  1421. if (autoReportFeatures.TimerExpired())
  1422. {
  1423. if(autoReportFeatures.Temp()){
  1424. gcode_M105(active_extruder);
  1425. }
  1426. if(autoReportFeatures.Pos()){
  1427. gcode_M114();
  1428. }
  1429. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1430. if(autoReportFeatures.Fans()){
  1431. gcode_M123();
  1432. }
  1433. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1434. autoReportFeatures.TimerStart();
  1435. }
  1436. }
  1437. #endif //AUTO_REPORT
  1438. /**
  1439. * Output a "busy" message at regular intervals
  1440. * while the machine is not accepting commands.
  1441. */
  1442. void host_keepalive() {
  1443. #ifndef HOST_KEEPALIVE_FEATURE
  1444. return;
  1445. #endif //HOST_KEEPALIVE_FEATURE
  1446. if (farm_mode) return;
  1447. long ms = _millis();
  1448. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1449. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1450. switch (busy_state) {
  1451. case IN_HANDLER:
  1452. case IN_PROCESS:
  1453. SERIAL_ECHO_START;
  1454. SERIAL_ECHOLNPGM("busy: processing");
  1455. break;
  1456. case PAUSED_FOR_USER:
  1457. SERIAL_ECHO_START;
  1458. SERIAL_ECHOLNPGM("busy: paused for user");
  1459. break;
  1460. case PAUSED_FOR_INPUT:
  1461. SERIAL_ECHO_START;
  1462. SERIAL_ECHOLNPGM("busy: paused for input");
  1463. break;
  1464. default:
  1465. break;
  1466. }
  1467. }
  1468. prev_busy_signal_ms = ms;
  1469. }
  1470. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1471. // Before loop(), the setup() function is called by the main() routine.
  1472. void loop()
  1473. {
  1474. // Reset a previously aborted command, we can now start processing motion again
  1475. planner_aborted = false;
  1476. if(Stopped) {
  1477. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1478. // Signal to the host that we're currently busy waiting for supervision.
  1479. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1480. } else {
  1481. // Printer is available for processing, reset state
  1482. KEEPALIVE_STATE(NOT_BUSY);
  1483. }
  1484. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1485. usb_timer.start();
  1486. }
  1487. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1488. ;
  1489. }
  1490. #ifdef PRUSA_M28
  1491. if (prusa_sd_card_upload)
  1492. {
  1493. //we read byte-by byte
  1494. serial_read_stream();
  1495. }
  1496. else
  1497. #endif
  1498. {
  1499. get_command();
  1500. #ifdef SDSUPPORT
  1501. card.checkautostart(false);
  1502. #endif
  1503. if(buflen)
  1504. {
  1505. cmdbuffer_front_already_processed = false;
  1506. #ifdef SDSUPPORT
  1507. if(card.saving)
  1508. {
  1509. // Saving a G-code file onto an SD-card is in progress.
  1510. // Saving starts with M28, saving until M29 is seen.
  1511. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1512. card.write_command(CMDBUFFER_CURRENT_STRING);
  1513. if(card.logging)
  1514. process_commands();
  1515. else
  1516. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1517. } else {
  1518. card.closefile();
  1519. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1520. }
  1521. } else {
  1522. process_commands();
  1523. }
  1524. #else
  1525. process_commands();
  1526. #endif //SDSUPPORT
  1527. if (! cmdbuffer_front_already_processed && buflen)
  1528. {
  1529. // ptr points to the start of the block currently being processed.
  1530. // The first character in the block is the block type.
  1531. char *ptr = cmdbuffer + bufindr;
  1532. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1533. // To support power panic, move the length of the command on the SD card to a planner buffer.
  1534. union {
  1535. struct {
  1536. char lo;
  1537. char hi;
  1538. } lohi;
  1539. uint16_t value;
  1540. } sdlen;
  1541. sdlen.value = 0;
  1542. {
  1543. // This block locks the interrupts globally for 3.25 us,
  1544. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1545. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1546. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1547. cli();
  1548. // Reset the command to something, which will be ignored by the power panic routine,
  1549. // so this buffer length will not be counted twice.
  1550. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1551. // Extract the current buffer length.
  1552. sdlen.lohi.lo = *ptr ++;
  1553. sdlen.lohi.hi = *ptr;
  1554. // and pass it to the planner queue.
  1555. planner_add_sd_length(sdlen.value);
  1556. sei();
  1557. }
  1558. }
  1559. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1560. cli();
  1561. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1562. // and one for each command to previous block in the planner queue.
  1563. planner_add_sd_length(1);
  1564. sei();
  1565. }
  1566. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1567. // this block's SD card length will not be counted twice as its command type has been replaced
  1568. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1569. cmdqueue_pop_front();
  1570. }
  1571. host_keepalive();
  1572. }
  1573. }
  1574. //check heater every n milliseconds
  1575. manage_heater();
  1576. manage_inactivity(isPrintPaused);
  1577. checkHitEndstops();
  1578. lcd_update(0);
  1579. #ifdef TMC2130
  1580. tmc2130_check_overtemp();
  1581. if (tmc2130_sg_crash)
  1582. {
  1583. uint8_t crash = tmc2130_sg_crash;
  1584. tmc2130_sg_crash = 0;
  1585. // crashdet_stop_and_save_print();
  1586. switch (crash)
  1587. {
  1588. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1589. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1590. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1591. }
  1592. }
  1593. #endif //TMC2130
  1594. MMU2::mmu2.mmu_loop();
  1595. }
  1596. #define DEFINE_PGM_READ_ANY(type, reader) \
  1597. static inline type pgm_read_any(const type *p) \
  1598. { return pgm_read_##reader##_near(p); }
  1599. DEFINE_PGM_READ_ANY(float, float);
  1600. DEFINE_PGM_READ_ANY(signed char, byte);
  1601. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1602. static const PROGMEM type array##_P[3] = \
  1603. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1604. static inline type array(uint8_t axis) \
  1605. { return pgm_read_any(&array##_P[axis]); } \
  1606. type array##_ext(uint8_t axis) \
  1607. { return pgm_read_any(&array##_P[axis]); }
  1608. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1609. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1610. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1611. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1612. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1613. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1614. static void axis_is_at_home(uint8_t axis) {
  1615. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1616. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1617. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1618. }
  1619. //! @return original feedmultiply
  1620. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1621. saved_feedrate = feedrate;
  1622. int l_feedmultiply = feedmultiply;
  1623. feedmultiply = 100;
  1624. previous_millis_cmd.start();
  1625. enable_endstops(enable_endstops_now);
  1626. return l_feedmultiply;
  1627. }
  1628. //! @param original_feedmultiply feedmultiply to restore
  1629. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1630. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1631. enable_endstops(false);
  1632. #endif
  1633. feedrate = saved_feedrate;
  1634. feedmultiply = original_feedmultiply;
  1635. previous_millis_cmd.start();
  1636. }
  1637. #ifdef ENABLE_AUTO_BED_LEVELING
  1638. #ifdef AUTO_BED_LEVELING_GRID
  1639. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1640. {
  1641. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1642. planeNormal.debug("planeNormal");
  1643. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1644. //bedLevel.debug("bedLevel");
  1645. //plan_bed_level_matrix.debug("bed level before");
  1646. //vector_3 uncorrected_position = plan_get_position_mm();
  1647. //uncorrected_position.debug("position before");
  1648. vector_3 corrected_position = plan_get_position();
  1649. // corrected_position.debug("position after");
  1650. current_position[X_AXIS] = corrected_position.x;
  1651. current_position[Y_AXIS] = corrected_position.y;
  1652. current_position[Z_AXIS] = corrected_position.z;
  1653. // put the bed at 0 so we don't go below it.
  1654. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1655. plan_set_position_curposXYZE();
  1656. }
  1657. #else // not AUTO_BED_LEVELING_GRID
  1658. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1659. plan_bed_level_matrix.set_to_identity();
  1660. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1661. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1662. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1663. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1664. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1665. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1666. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1667. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1668. vector_3 corrected_position = plan_get_position();
  1669. current_position[X_AXIS] = corrected_position.x;
  1670. current_position[Y_AXIS] = corrected_position.y;
  1671. current_position[Z_AXIS] = corrected_position.z;
  1672. // put the bed at 0 so we don't go below it.
  1673. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1674. plan_set_position_curposXYZE();
  1675. }
  1676. #endif // AUTO_BED_LEVELING_GRID
  1677. static void run_z_probe() {
  1678. plan_bed_level_matrix.set_to_identity();
  1679. feedrate = homing_feedrate[Z_AXIS];
  1680. // move down until you find the bed
  1681. float zPosition = -10;
  1682. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1683. st_synchronize();
  1684. // we have to let the planner know where we are right now as it is not where we said to go.
  1685. zPosition = st_get_position_mm(Z_AXIS);
  1686. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1687. // move up the retract distance
  1688. zPosition += home_retract_mm(Z_AXIS);
  1689. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1690. st_synchronize();
  1691. // move back down slowly to find bed
  1692. feedrate = homing_feedrate[Z_AXIS]/4;
  1693. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1694. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1695. st_synchronize();
  1696. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1697. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1698. plan_set_position_curposXYZE();
  1699. }
  1700. static void do_blocking_move_to(float x, float y, float z) {
  1701. float oldFeedRate = feedrate;
  1702. feedrate = homing_feedrate[Z_AXIS];
  1703. current_position[Z_AXIS] = z;
  1704. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1705. st_synchronize();
  1706. feedrate = XY_TRAVEL_SPEED;
  1707. current_position[X_AXIS] = x;
  1708. current_position[Y_AXIS] = y;
  1709. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1710. st_synchronize();
  1711. feedrate = oldFeedRate;
  1712. }
  1713. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1714. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1715. }
  1716. /// Probe bed height at position (x,y), returns the measured z value
  1717. static float probe_pt(float x, float y, float z_before) {
  1718. // move to right place
  1719. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1720. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1721. run_z_probe();
  1722. float measured_z = current_position[Z_AXIS];
  1723. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1724. SERIAL_PROTOCOLPGM(" x: ");
  1725. SERIAL_PROTOCOL(x);
  1726. SERIAL_PROTOCOLPGM(" y: ");
  1727. SERIAL_PROTOCOL(y);
  1728. SERIAL_PROTOCOLPGM(" z: ");
  1729. SERIAL_PROTOCOL(measured_z);
  1730. SERIAL_PROTOCOLPGM("\n");
  1731. return measured_z;
  1732. }
  1733. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1734. #ifdef LIN_ADVANCE
  1735. /**
  1736. * M900: Set and/or Get advance K factor
  1737. *
  1738. * K<factor> Set advance K factor
  1739. */
  1740. inline void gcode_M900() {
  1741. float newK = code_seen('K') ? code_value_float() : -2;
  1742. #ifdef LA_NOCOMPAT
  1743. if (newK >= 0 && newK < LA_K_MAX)
  1744. extruder_advance_K = newK;
  1745. else
  1746. SERIAL_ECHOLNPGM("K out of allowed range!");
  1747. #else
  1748. if (newK == 0)
  1749. {
  1750. extruder_advance_K = 0;
  1751. la10c_reset();
  1752. }
  1753. else
  1754. {
  1755. newK = la10c_value(newK);
  1756. if (newK < 0)
  1757. SERIAL_ECHOLNPGM("K out of allowed range!");
  1758. else
  1759. extruder_advance_K = newK;
  1760. }
  1761. #endif
  1762. SERIAL_ECHO_START;
  1763. SERIAL_ECHOPGM("Advance K=");
  1764. SERIAL_ECHOLN(extruder_advance_K);
  1765. }
  1766. #endif // LIN_ADVANCE
  1767. bool check_commands() {
  1768. bool end_command_found = false;
  1769. while (buflen)
  1770. {
  1771. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1772. if (!cmdbuffer_front_already_processed)
  1773. cmdqueue_pop_front();
  1774. cmdbuffer_front_already_processed = false;
  1775. }
  1776. return end_command_found;
  1777. }
  1778. /// @brief Safely move Z-axis by distance delta (mm)
  1779. /// @param delta travel distance in mm
  1780. /// @returns The actual travel distance in mm. Endstop may limit the requested move.
  1781. float raise_z(float delta)
  1782. {
  1783. float travel_z = current_position[Z_AXIS];
  1784. // Prepare to move Z axis
  1785. current_position[Z_AXIS] += delta;
  1786. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1787. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1788. #else
  1789. bool z_min_endstop = false;
  1790. #endif
  1791. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1792. {
  1793. // current position is known or very low, it's safe to raise Z
  1794. clamp_to_software_endstops(current_position);
  1795. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1796. st_synchronize();
  1797. // Get the final travel distance
  1798. travel_z = current_position[Z_AXIS] - travel_z;
  1799. } else {
  1800. // ensure Z is powered in normal mode to overcome initial load
  1801. enable_z();
  1802. st_synchronize();
  1803. // rely on crashguard to limit damage
  1804. bool z_endstop_enabled = enable_z_endstop(true);
  1805. #ifdef TMC2130
  1806. tmc2130_home_enter(Z_AXIS_MASK);
  1807. #endif //TMC2130
  1808. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1809. st_synchronize();
  1810. // Get the final travel distance
  1811. travel_z = st_get_position_mm(Z_AXIS) - travel_z;
  1812. #ifdef TMC2130
  1813. if (endstop_z_hit_on_purpose())
  1814. {
  1815. // not necessarily exact, but will avoid further vertical moves
  1816. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1817. plan_set_position_curposXYZE();
  1818. }
  1819. tmc2130_home_exit();
  1820. #endif //TMC2130
  1821. enable_z_endstop(z_endstop_enabled);
  1822. }
  1823. return travel_z;
  1824. }
  1825. // raise_z_above: slowly raise Z to the requested height
  1826. //
  1827. // contrarily to a simple move, this function will carefully plan a move
  1828. // when the current Z position is unknown. In such cases, stallguard is
  1829. // enabled and will prevent prolonged pushing against the Z tops
  1830. void raise_z_above(float target)
  1831. {
  1832. if (current_position[Z_AXIS] >= target)
  1833. return;
  1834. // Use absolute value in case the current position is unknown
  1835. raise_z(fabs(current_position[Z_AXIS] - target));
  1836. }
  1837. #ifdef TMC2130
  1838. bool calibrate_z_auto()
  1839. {
  1840. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1841. lcd_clear();
  1842. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1843. bool endstops_enabled = enable_endstops(true);
  1844. int axis_up_dir = -home_dir(Z_AXIS);
  1845. tmc2130_home_enter(Z_AXIS_MASK);
  1846. current_position[Z_AXIS] = 0;
  1847. plan_set_position_curposXYZE();
  1848. set_destination_to_current();
  1849. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1850. feedrate = homing_feedrate[Z_AXIS];
  1851. plan_buffer_line_destinationXYZE(feedrate / 60);
  1852. st_synchronize();
  1853. // current_position[axis] = 0;
  1854. // plan_set_position_curposXYZE();
  1855. tmc2130_home_exit();
  1856. enable_endstops(false);
  1857. current_position[Z_AXIS] = 0;
  1858. plan_set_position_curposXYZE();
  1859. set_destination_to_current();
  1860. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1861. feedrate = homing_feedrate[Z_AXIS] / 2;
  1862. plan_buffer_line_destinationXYZE(feedrate / 60);
  1863. st_synchronize();
  1864. enable_endstops(endstops_enabled);
  1865. if (PRINTER_TYPE == PRINTER_MK3) {
  1866. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1867. }
  1868. else {
  1869. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1870. }
  1871. plan_set_position_curposXYZE();
  1872. return true;
  1873. }
  1874. #endif //TMC2130
  1875. #ifdef TMC2130
  1876. static void check_Z_crash(void)
  1877. {
  1878. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1879. FORCE_HIGH_POWER_END;
  1880. current_position[Z_AXIS] = 0;
  1881. plan_set_position_curposXYZE();
  1882. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1883. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1884. st_synchronize();
  1885. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1886. }
  1887. }
  1888. #endif //TMC2130
  1889. #ifdef TMC2130
  1890. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1891. #else
  1892. void homeaxis(uint8_t axis, uint8_t cnt)
  1893. #endif //TMC2130
  1894. {
  1895. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1896. #define HOMEAXIS_DO(LETTER) \
  1897. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1898. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1899. {
  1900. int axis_home_dir = home_dir(axis);
  1901. feedrate = homing_feedrate[axis];
  1902. #ifdef TMC2130
  1903. tmc2130_home_enter(X_AXIS_MASK << axis);
  1904. #endif //TMC2130
  1905. // Move away a bit, so that the print head does not touch the end position,
  1906. // and the following movement to endstop has a chance to achieve the required velocity
  1907. // for the stall guard to work.
  1908. current_position[axis] = 0;
  1909. plan_set_position_curposXYZE();
  1910. set_destination_to_current();
  1911. // destination[axis] = 11.f;
  1912. destination[axis] = -3.f * axis_home_dir;
  1913. plan_buffer_line_destinationXYZE(feedrate/60);
  1914. st_synchronize();
  1915. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1916. endstops_hit_on_purpose();
  1917. enable_endstops(false);
  1918. current_position[axis] = 0;
  1919. plan_set_position_curposXYZE();
  1920. destination[axis] = 1. * axis_home_dir;
  1921. plan_buffer_line_destinationXYZE(feedrate/60);
  1922. st_synchronize();
  1923. // Now continue to move up to the left end stop with the collision detection enabled.
  1924. enable_endstops(true);
  1925. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1926. plan_buffer_line_destinationXYZE(feedrate/60);
  1927. st_synchronize();
  1928. for (uint8_t i = 0; i < cnt; i++)
  1929. {
  1930. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1931. endstops_hit_on_purpose();
  1932. enable_endstops(false);
  1933. current_position[axis] = 0;
  1934. plan_set_position_curposXYZE();
  1935. destination[axis] = -10.f * axis_home_dir;
  1936. plan_buffer_line_destinationXYZE(feedrate/60);
  1937. st_synchronize();
  1938. endstops_hit_on_purpose();
  1939. // Now move left up to the collision, this time with a repeatable velocity.
  1940. enable_endstops(true);
  1941. destination[axis] = 11.f * axis_home_dir;
  1942. #ifdef TMC2130
  1943. feedrate = homing_feedrate[axis];
  1944. #else //TMC2130
  1945. feedrate = homing_feedrate[axis] / 2;
  1946. #endif //TMC2130
  1947. plan_buffer_line_destinationXYZE(feedrate/60);
  1948. st_synchronize();
  1949. #ifdef TMC2130
  1950. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1951. if (pstep) pstep[i] = mscnt >> 4;
  1952. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1953. #endif //TMC2130
  1954. }
  1955. endstops_hit_on_purpose();
  1956. enable_endstops(false);
  1957. #ifdef TMC2130
  1958. uint8_t orig = tmc2130_home_origin[axis];
  1959. uint8_t back = tmc2130_home_bsteps[axis];
  1960. if (tmc2130_home_enabled && (orig <= 63))
  1961. {
  1962. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1963. if (back > 0)
  1964. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1965. }
  1966. else
  1967. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1968. tmc2130_home_exit();
  1969. #endif //TMC2130
  1970. axis_is_at_home(axis);
  1971. axis_known_position[axis] = true;
  1972. // Move from minimum
  1973. #ifdef TMC2130
  1974. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1975. #else //TMC2130
  1976. float dist = - axis_home_dir * 0.01f * 64;
  1977. #endif //TMC2130
  1978. current_position[axis] -= dist;
  1979. plan_set_position_curposXYZE();
  1980. current_position[axis] += dist;
  1981. destination[axis] = current_position[axis];
  1982. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1983. st_synchronize();
  1984. feedrate = 0.0;
  1985. }
  1986. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1987. {
  1988. #ifdef TMC2130
  1989. FORCE_HIGH_POWER_START;
  1990. #endif
  1991. int axis_home_dir = home_dir(axis);
  1992. current_position[axis] = 0;
  1993. plan_set_position_curposXYZE();
  1994. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1995. feedrate = homing_feedrate[axis];
  1996. plan_buffer_line_destinationXYZE(feedrate/60);
  1997. st_synchronize();
  1998. #ifdef TMC2130
  1999. check_Z_crash();
  2000. #endif //TMC2130
  2001. current_position[axis] = 0;
  2002. plan_set_position_curposXYZE();
  2003. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  2004. plan_buffer_line_destinationXYZE(feedrate/60);
  2005. st_synchronize();
  2006. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  2007. feedrate = homing_feedrate[axis]/2 ;
  2008. plan_buffer_line_destinationXYZE(feedrate/60);
  2009. st_synchronize();
  2010. #ifdef TMC2130
  2011. check_Z_crash();
  2012. #endif //TMC2130
  2013. axis_is_at_home(axis);
  2014. destination[axis] = current_position[axis];
  2015. feedrate = 0.0;
  2016. endstops_hit_on_purpose();
  2017. axis_known_position[axis] = true;
  2018. #ifdef TMC2130
  2019. FORCE_HIGH_POWER_END;
  2020. #endif
  2021. }
  2022. enable_endstops(endstops_enabled);
  2023. }
  2024. /**/
  2025. void home_xy()
  2026. {
  2027. set_destination_to_current();
  2028. homeaxis(X_AXIS);
  2029. homeaxis(Y_AXIS);
  2030. plan_set_position_curposXYZE();
  2031. endstops_hit_on_purpose();
  2032. }
  2033. void refresh_cmd_timeout(void)
  2034. {
  2035. previous_millis_cmd.start();
  2036. }
  2037. #ifdef FWRETRACT
  2038. void retract(bool retracting, bool swapretract = false) {
  2039. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2040. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2041. // position, which requires a sync
  2042. if(retracting && !retracted[active_extruder]) {
  2043. st_synchronize();
  2044. set_destination_to_current();
  2045. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2046. plan_set_e_position(current_position[E_AXIS]);
  2047. float oldFeedrate = feedrate;
  2048. feedrate=cs.retract_feedrate*60;
  2049. retracted[active_extruder]=true;
  2050. prepare_move();
  2051. if(cs.retract_zlift) {
  2052. st_synchronize();
  2053. current_position[Z_AXIS]-=cs.retract_zlift;
  2054. plan_set_position_curposXYZE();
  2055. prepare_move();
  2056. }
  2057. feedrate = oldFeedrate;
  2058. } else if(!retracting && retracted[active_extruder]) {
  2059. st_synchronize();
  2060. set_destination_to_current();
  2061. float oldFeedrate = feedrate;
  2062. feedrate=cs.retract_recover_feedrate*60;
  2063. if(cs.retract_zlift) {
  2064. current_position[Z_AXIS]+=cs.retract_zlift;
  2065. plan_set_position_curposXYZE();
  2066. prepare_move();
  2067. st_synchronize();
  2068. }
  2069. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2070. plan_set_e_position(current_position[E_AXIS]);
  2071. retracted[active_extruder]=false;
  2072. prepare_move();
  2073. feedrate = oldFeedrate;
  2074. }
  2075. } //retract
  2076. #endif //FWRETRACT
  2077. #ifdef TMC2130
  2078. void force_high_power_mode(bool start_high_power_section) {
  2079. #ifdef PSU_Delta
  2080. if (start_high_power_section == true) enable_force_z();
  2081. #endif //PSU_Delta
  2082. uint8_t silent;
  2083. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2084. if (silent == 1) {
  2085. //we are in silent mode, set to normal mode to enable crash detection
  2086. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2087. st_synchronize();
  2088. cli();
  2089. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2090. update_mode_profile();
  2091. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2092. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2093. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2094. st_reset_timer();
  2095. sei();
  2096. }
  2097. }
  2098. #endif //TMC2130
  2099. void gcode_M105(uint8_t extruder)
  2100. {
  2101. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2102. SERIAL_PROTOCOLPGM("T:");
  2103. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2104. SERIAL_PROTOCOLPGM(" /");
  2105. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2106. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2107. SERIAL_PROTOCOLPGM(" B:");
  2108. SERIAL_PROTOCOL_F(degBed(),1);
  2109. SERIAL_PROTOCOLPGM(" /");
  2110. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2111. #endif //TEMP_BED_PIN
  2112. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2113. SERIAL_PROTOCOLPGM(" T");
  2114. SERIAL_PROTOCOL(cur_extruder);
  2115. SERIAL_PROTOCOL(':');
  2116. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2117. SERIAL_PROTOCOLPGM(" /");
  2118. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2119. }
  2120. #else
  2121. SERIAL_ERROR_START;
  2122. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2123. #endif
  2124. SERIAL_PROTOCOLPGM(" @:");
  2125. #ifdef EXTRUDER_WATTS
  2126. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2127. SERIAL_PROTOCOLPGM("W");
  2128. #else
  2129. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2130. #endif
  2131. SERIAL_PROTOCOLPGM(" B@:");
  2132. #ifdef BED_WATTS
  2133. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2134. SERIAL_PROTOCOLPGM("W");
  2135. #else
  2136. SERIAL_PROTOCOL(getHeaterPower(-1));
  2137. #endif
  2138. #ifdef PINDA_THERMISTOR
  2139. SERIAL_PROTOCOLPGM(" P:");
  2140. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2141. #endif //PINDA_THERMISTOR
  2142. #ifdef AMBIENT_THERMISTOR
  2143. SERIAL_PROTOCOLPGM(" A:");
  2144. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2145. #endif //AMBIENT_THERMISTOR
  2146. #ifdef SHOW_TEMP_ADC_VALUES
  2147. {
  2148. float raw = 0.0;
  2149. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2150. SERIAL_PROTOCOLPGM(" ADC B:");
  2151. SERIAL_PROTOCOL_F(degBed(),1);
  2152. SERIAL_PROTOCOLPGM("C->");
  2153. raw = rawBedTemp();
  2154. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2155. SERIAL_PROTOCOLPGM(" Rb->");
  2156. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2157. SERIAL_PROTOCOLPGM(" Rxb->");
  2158. SERIAL_PROTOCOL_F(raw, 5);
  2159. #endif
  2160. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2161. SERIAL_PROTOCOLPGM(" T");
  2162. SERIAL_PROTOCOL(cur_extruder);
  2163. SERIAL_PROTOCOLPGM(":");
  2164. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2165. SERIAL_PROTOCOLPGM("C->");
  2166. raw = rawHotendTemp(cur_extruder);
  2167. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2168. SERIAL_PROTOCOLPGM(" Rt");
  2169. SERIAL_PROTOCOL(cur_extruder);
  2170. SERIAL_PROTOCOLPGM("->");
  2171. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2172. SERIAL_PROTOCOLPGM(" Rx");
  2173. SERIAL_PROTOCOL(cur_extruder);
  2174. SERIAL_PROTOCOLPGM("->");
  2175. SERIAL_PROTOCOL_F(raw, 5);
  2176. }
  2177. }
  2178. #endif
  2179. SERIAL_PROTOCOLLN();
  2180. }
  2181. #ifdef TMC2130
  2182. static void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_y_value, bool home_z_axis, long home_z_value, bool calib, bool without_mbl)
  2183. #else
  2184. static void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_y_value, bool home_z_axis, long home_z_value, bool without_mbl)
  2185. #endif //TMC2130
  2186. {
  2187. // Flag for the display update routine and to disable the print cancelation during homing.
  2188. st_synchronize();
  2189. homing_flag = true;
  2190. #if 0
  2191. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2192. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2193. #endif
  2194. // Which axes should be homed?
  2195. bool home_x = home_x_axis;
  2196. bool home_y = home_y_axis;
  2197. bool home_z = home_z_axis;
  2198. // Either all X,Y,Z codes are present, or none of them.
  2199. bool home_all_axes = home_x == home_y && home_x == home_z;
  2200. if (home_all_axes)
  2201. // No X/Y/Z code provided means to home all axes.
  2202. home_x = home_y = home_z = true;
  2203. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2204. if (home_all_axes) {
  2205. raise_z_above(MESH_HOME_Z_SEARCH);
  2206. }
  2207. #ifdef ENABLE_AUTO_BED_LEVELING
  2208. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2209. #endif //ENABLE_AUTO_BED_LEVELING
  2210. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2211. // the planner will not perform any adjustments in the XY plane.
  2212. // Wait for the motors to stop and update the current position with the absolute values.
  2213. world2machine_revert_to_uncorrected();
  2214. // For mesh bed leveling deactivate the matrix temporarily.
  2215. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2216. // in a single axis only.
  2217. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2218. #ifdef MESH_BED_LEVELING
  2219. uint8_t mbl_was_active = mbl.active;
  2220. mbl.active = 0;
  2221. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2222. #endif
  2223. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2224. if (home_z)
  2225. babystep_undo();
  2226. int l_feedmultiply = setup_for_endstop_move();
  2227. set_destination_to_current();
  2228. feedrate = 0.0;
  2229. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2230. if(home_z)
  2231. homeaxis(Z_AXIS);
  2232. #endif
  2233. #ifdef QUICK_HOME
  2234. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2235. if(home_x && home_y) //first diagonal move
  2236. {
  2237. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2238. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2239. plan_set_position_curposXYZE();
  2240. destination[X_AXIS] = 1.5 * max_length(X_AXIS) * x_axis_home_dir;destination[Y_AXIS] = 1.5 * max_length(Y_AXIS) * home_dir(Y_AXIS);
  2241. feedrate = homing_feedrate[X_AXIS];
  2242. if(homing_feedrate[Y_AXIS]<feedrate)
  2243. feedrate = homing_feedrate[Y_AXIS];
  2244. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2245. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2246. } else {
  2247. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2248. }
  2249. plan_buffer_line_destinationXYZE(feedrate/60);
  2250. st_synchronize();
  2251. axis_is_at_home(X_AXIS);
  2252. axis_is_at_home(Y_AXIS);
  2253. plan_set_position_curposXYZE();
  2254. destination[X_AXIS] = current_position[X_AXIS];
  2255. destination[Y_AXIS] = current_position[Y_AXIS];
  2256. plan_buffer_line_destinationXYZE(feedrate/60);
  2257. feedrate = 0.0;
  2258. st_synchronize();
  2259. endstops_hit_on_purpose();
  2260. current_position[X_AXIS] = destination[X_AXIS];
  2261. current_position[Y_AXIS] = destination[Y_AXIS];
  2262. current_position[Z_AXIS] = destination[Z_AXIS];
  2263. }
  2264. #endif /* QUICK_HOME */
  2265. #ifdef TMC2130
  2266. if(home_x)
  2267. {
  2268. if (!calib)
  2269. homeaxis(X_AXIS);
  2270. else
  2271. tmc2130_home_calibrate(X_AXIS);
  2272. }
  2273. if(home_y)
  2274. {
  2275. if (!calib)
  2276. homeaxis(Y_AXIS);
  2277. else
  2278. tmc2130_home_calibrate(Y_AXIS);
  2279. }
  2280. #else //TMC2130
  2281. if(home_x) homeaxis(X_AXIS);
  2282. if(home_y) homeaxis(Y_AXIS);
  2283. #endif //TMC2130
  2284. if(home_x_axis && home_x_value != 0)
  2285. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2286. if(home_y_axis && home_y_value != 0)
  2287. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2288. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2289. #ifndef Z_SAFE_HOMING
  2290. if(home_z) {
  2291. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2292. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2293. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2294. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2295. raise_z_above(MESH_HOME_Z_SEARCH);
  2296. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2297. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2298. // 1st mesh bed leveling measurement point, corrected.
  2299. world2machine_initialize();
  2300. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2301. world2machine_reset();
  2302. if (destination[Y_AXIS] < Y_MIN_POS)
  2303. destination[Y_AXIS] = Y_MIN_POS;
  2304. feedrate = homing_feedrate[X_AXIS] / 20;
  2305. enable_endstops(false);
  2306. #ifdef DEBUG_BUILD
  2307. SERIAL_ECHOLNPGM("plan_set_position()");
  2308. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2309. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2310. #endif
  2311. plan_set_position_curposXYZE();
  2312. #ifdef DEBUG_BUILD
  2313. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2314. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2315. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2316. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2317. #endif
  2318. plan_buffer_line_destinationXYZE(feedrate);
  2319. st_synchronize();
  2320. current_position[X_AXIS] = destination[X_AXIS];
  2321. current_position[Y_AXIS] = destination[Y_AXIS];
  2322. enable_endstops(true);
  2323. endstops_hit_on_purpose();
  2324. homeaxis(Z_AXIS);
  2325. #else // MESH_BED_LEVELING
  2326. homeaxis(Z_AXIS);
  2327. #endif // MESH_BED_LEVELING
  2328. }
  2329. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2330. if(home_all_axes) {
  2331. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2332. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2333. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2334. feedrate = XY_TRAVEL_SPEED/60;
  2335. current_position[Z_AXIS] = 0;
  2336. plan_set_position_curposXYZE();
  2337. plan_buffer_line_destinationXYZE(feedrate);
  2338. st_synchronize();
  2339. current_position[X_AXIS] = destination[X_AXIS];
  2340. current_position[Y_AXIS] = destination[Y_AXIS];
  2341. homeaxis(Z_AXIS);
  2342. }
  2343. // Let's see if X and Y are homed and probe is inside bed area.
  2344. if(home_z) {
  2345. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2346. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2347. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2348. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2349. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2350. current_position[Z_AXIS] = 0;
  2351. plan_set_position_curposXYZE();
  2352. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2353. feedrate = max_feedrate[Z_AXIS];
  2354. plan_buffer_line_destinationXYZE(feedrate);
  2355. st_synchronize();
  2356. homeaxis(Z_AXIS);
  2357. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2358. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2359. SERIAL_ECHO_START;
  2360. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2361. } else {
  2362. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2363. SERIAL_ECHO_START;
  2364. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2365. }
  2366. }
  2367. #endif // Z_SAFE_HOMING
  2368. #endif // Z_HOME_DIR < 0
  2369. if(home_z_axis && home_z_value != 0)
  2370. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2371. #ifdef ENABLE_AUTO_BED_LEVELING
  2372. if(home_z)
  2373. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2374. #endif
  2375. // Set the planner and stepper routine positions.
  2376. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2377. // contains the machine coordinates.
  2378. plan_set_position_curposXYZE();
  2379. clean_up_after_endstop_move(l_feedmultiply);
  2380. endstops_hit_on_purpose();
  2381. // Load the machine correction matrix
  2382. world2machine_initialize();
  2383. // and correct the current_position XY axes to match the transformed coordinate system.
  2384. world2machine_update_current();
  2385. #ifdef MESH_BED_LEVELING
  2386. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2387. {
  2388. if (! home_z && mbl_was_active) {
  2389. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2390. mbl.active = true;
  2391. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2392. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2393. }
  2394. }
  2395. #endif
  2396. prusa_statistics(20);
  2397. st_synchronize();
  2398. homing_flag = false;
  2399. #if 0
  2400. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2401. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2402. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2403. #endif
  2404. }
  2405. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2406. {
  2407. #ifdef TMC2130
  2408. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2409. #else
  2410. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2411. #endif //TMC2130
  2412. }
  2413. // G80 - Automatic mesh bed leveling
  2414. static void gcode_G80()
  2415. {
  2416. st_synchronize();
  2417. if (planner_aborted)
  2418. return;
  2419. mesh_bed_leveling_flag = true;
  2420. #ifndef PINDA_THERMISTOR
  2421. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2422. #endif // ndef PINDA_THERMISTOR
  2423. #ifdef SUPPORT_VERBOSITY
  2424. int8_t verbosity_level = 0;
  2425. if (code_seen('V')) {
  2426. // Just 'V' without a number counts as V1.
  2427. char c = strchr_pointer[1];
  2428. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2429. }
  2430. #endif //SUPPORT_VERBOSITY
  2431. // Firstly check if we know where we are
  2432. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2433. // We don't know where we are! HOME!
  2434. // Push the commands to the front of the message queue in the reverse order!
  2435. // There shall be always enough space reserved for these commands.
  2436. repeatcommand_front(); // repeat G80 with all its parameters
  2437. enquecommand_front_P(G28W0);
  2438. return;
  2439. }
  2440. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2441. if (code_seen('N')) {
  2442. nMeasPoints = code_value_uint8();
  2443. if (nMeasPoints != 7) {
  2444. nMeasPoints = 3;
  2445. }
  2446. }
  2447. else {
  2448. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2449. }
  2450. uint8_t nProbeRetry = 3;
  2451. if (code_seen('R')) {
  2452. nProbeRetry = code_value_uint8();
  2453. if (nProbeRetry > 10) {
  2454. nProbeRetry = 10;
  2455. }
  2456. }
  2457. else {
  2458. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2459. }
  2460. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2461. #ifndef PINDA_THERMISTOR
  2462. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2463. {
  2464. temp_compensation_start();
  2465. run = true;
  2466. repeatcommand_front(); // repeat G80 with all its parameters
  2467. enquecommand_front_P(G28W0);
  2468. break;
  2469. }
  2470. run = false;
  2471. #endif //PINDA_THERMISTOR
  2472. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2473. CustomMsg custom_message_type_old = custom_message_type;
  2474. uint8_t custom_message_state_old = custom_message_state;
  2475. custom_message_type = CustomMsg::MeshBedLeveling;
  2476. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2477. lcd_update(1);
  2478. mbl.reset(); //reset mesh bed leveling
  2479. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2480. babystep_undo();
  2481. // Cycle through all points and probe them
  2482. // First move up. During this first movement, the babystepping will be reverted.
  2483. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2484. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2485. // The move to the first calibration point.
  2486. current_position[X_AXIS] = BED_X0;
  2487. current_position[Y_AXIS] = BED_Y0;
  2488. #ifdef SUPPORT_VERBOSITY
  2489. if (verbosity_level >= 1)
  2490. {
  2491. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2492. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2493. }
  2494. #else //SUPPORT_VERBOSITY
  2495. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2496. #endif //SUPPORT_VERBOSITY
  2497. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2498. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2499. // Wait until the move is finished.
  2500. st_synchronize();
  2501. if (planner_aborted)
  2502. {
  2503. custom_message_type = custom_message_type_old;
  2504. custom_message_state = custom_message_state_old;
  2505. return;
  2506. }
  2507. uint8_t mesh_point = 0; //index number of calibration point
  2508. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2509. bool has_z = is_bed_z_jitter_data_valid(); //checks if we have data from Z calibration (offsets of the Z heiths of the 8 calibration points from the first point)
  2510. #ifdef SUPPORT_VERBOSITY
  2511. if (verbosity_level >= 1) {
  2512. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2513. }
  2514. #endif // SUPPORT_VERBOSITY
  2515. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2516. while (mesh_point != nMeasPoints * nMeasPoints) {
  2517. // Get coords of a measuring point.
  2518. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2519. uint8_t iy = mesh_point / nMeasPoints;
  2520. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2521. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2522. custom_message_state--;
  2523. mesh_point++;
  2524. continue; //skip
  2525. }*/
  2526. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2527. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2528. {
  2529. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2530. }
  2531. float z0 = 0.f;
  2532. if (has_z && (mesh_point > 0)) {
  2533. uint16_t z_offset_u = 0;
  2534. if (nMeasPoints == 7) {
  2535. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2536. }
  2537. else {
  2538. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2539. }
  2540. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2541. #ifdef SUPPORT_VERBOSITY
  2542. if (verbosity_level >= 1) {
  2543. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2544. }
  2545. #endif // SUPPORT_VERBOSITY
  2546. }
  2547. // Move Z up to MESH_HOME_Z_SEARCH.
  2548. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2549. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2550. float init_z_bckp = current_position[Z_AXIS];
  2551. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2552. st_synchronize();
  2553. // Move to XY position of the sensor point.
  2554. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2555. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2556. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2557. #ifdef SUPPORT_VERBOSITY
  2558. if (verbosity_level >= 1) {
  2559. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2560. SERIAL_PROTOCOL(mesh_point);
  2561. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2562. }
  2563. #else //SUPPORT_VERBOSITY
  2564. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2565. #endif // SUPPORT_VERBOSITY
  2566. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2567. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2568. st_synchronize();
  2569. if (planner_aborted)
  2570. {
  2571. custom_message_type = custom_message_type_old;
  2572. custom_message_state = custom_message_state_old;
  2573. return;
  2574. }
  2575. // Go down until endstop is hit
  2576. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2577. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  2578. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2579. break;
  2580. }
  2581. if (init_z_bckp - current_position[Z_AXIS] < 0.1f) { //broken cable or initial Z coordinate too low. Go to MESH_HOME_Z_SEARCH and repeat last step (z-probe) again to distinguish between these two cases.
  2582. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2583. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2584. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2585. st_synchronize();
  2586. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  2587. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2588. break;
  2589. }
  2590. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2591. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2592. break;
  2593. }
  2594. }
  2595. if (has_z && fabs(z0 - current_position[Z_AXIS]) > Z_CALIBRATION_THRESHOLD) { //if we have data from z calibration, max. allowed difference is 1mm for each point
  2596. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2597. break;
  2598. }
  2599. #ifdef SUPPORT_VERBOSITY
  2600. if (verbosity_level >= 10) {
  2601. SERIAL_ECHOPGM("X: ");
  2602. MYSERIAL.print(current_position[X_AXIS], 5);
  2603. SERIAL_ECHOLNPGM("");
  2604. SERIAL_ECHOPGM("Y: ");
  2605. MYSERIAL.print(current_position[Y_AXIS], 5);
  2606. SERIAL_PROTOCOLPGM("\n");
  2607. }
  2608. #endif // SUPPORT_VERBOSITY
  2609. float offset_z = 0;
  2610. #ifdef PINDA_THERMISTOR
  2611. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2612. #endif //PINDA_THERMISTOR
  2613. // #ifdef SUPPORT_VERBOSITY
  2614. /* if (verbosity_level >= 1)
  2615. {
  2616. SERIAL_ECHOPGM("mesh bed leveling: ");
  2617. MYSERIAL.print(current_position[Z_AXIS], 5);
  2618. SERIAL_ECHOPGM(" offset: ");
  2619. MYSERIAL.print(offset_z, 5);
  2620. SERIAL_ECHOLNPGM("");
  2621. }*/
  2622. // #endif // SUPPORT_VERBOSITY
  2623. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2624. custom_message_state--;
  2625. mesh_point++;
  2626. lcd_update(1);
  2627. }
  2628. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2629. #ifdef SUPPORT_VERBOSITY
  2630. if (verbosity_level >= 20) {
  2631. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2632. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2633. MYSERIAL.print(current_position[Z_AXIS], 5);
  2634. }
  2635. #endif // SUPPORT_VERBOSITY
  2636. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2637. st_synchronize();
  2638. if (mesh_point != nMeasPoints * nMeasPoints) {
  2639. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2640. bool bState;
  2641. do { // repeat until Z-leveling o.k.
  2642. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2643. #ifdef TMC2130
  2644. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2645. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2646. #else // TMC2130
  2647. lcd_wait_for_click_delay(0); // ~ no timeout
  2648. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2649. #endif // TMC2130
  2650. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2651. bState=enable_z_endstop(false);
  2652. raise_z(-1);
  2653. enable_z_endstop(true);
  2654. #ifdef TMC2130
  2655. tmc2130_home_enter(Z_AXIS_MASK);
  2656. #endif // TMC2130
  2657. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2658. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2659. st_synchronize();
  2660. #ifdef TMC2130
  2661. tmc2130_home_exit();
  2662. #endif // TMC2130
  2663. enable_z_endstop(bState);
  2664. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2665. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2666. custom_message_type = custom_message_type_old;
  2667. custom_message_state = custom_message_state_old;
  2668. lcd_update_enable(true); // display / status-line recovery
  2669. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2670. repeatcommand_front(); // re-run (i.e. of "G80")
  2671. return;
  2672. }
  2673. clean_up_after_endstop_move(l_feedmultiply);
  2674. // SERIAL_ECHOLNPGM("clean up finished ");
  2675. #ifndef PINDA_THERMISTOR
  2676. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2677. #endif
  2678. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2679. // SERIAL_ECHOLNPGM("babystep applied");
  2680. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2681. #ifdef SUPPORT_VERBOSITY
  2682. if (verbosity_level >= 1) {
  2683. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2684. }
  2685. #endif // SUPPORT_VERBOSITY
  2686. for (uint8_t i = 0; i < 4; ++i) {
  2687. static const char codes[4] PROGMEM = { 'L', 'R', 'F', 'B' };
  2688. static uint8_t *const eep_addresses[4] PROGMEM = {
  2689. (uint8_t*)EEPROM_BED_CORRECTION_LEFT,
  2690. (uint8_t*)EEPROM_BED_CORRECTION_RIGHT,
  2691. (uint8_t*)EEPROM_BED_CORRECTION_FRONT,
  2692. (uint8_t*)EEPROM_BED_CORRECTION_REAR,
  2693. };
  2694. long correction = 0;
  2695. if (code_seen(pgm_read_byte(&codes[i])))
  2696. correction = code_value_long();
  2697. else if (eeprom_bed_correction_valid)
  2698. correction = (int8_t)eeprom_read_byte((uint8_t*)pgm_read_ptr(&eep_addresses[i]));
  2699. if (correction == 0)
  2700. continue;
  2701. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2702. SERIAL_ERROR_START;
  2703. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2704. SERIAL_ECHO(correction);
  2705. SERIAL_ECHOLNPGM(" microns");
  2706. }
  2707. else {
  2708. float offset = float(correction) * 0.001f;
  2709. switch (i) {
  2710. case 0:
  2711. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2712. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2713. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2714. }
  2715. }
  2716. break;
  2717. case 1:
  2718. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2719. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2720. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2721. }
  2722. }
  2723. break;
  2724. case 2:
  2725. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2726. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2727. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2728. }
  2729. }
  2730. break;
  2731. case 3:
  2732. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2733. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2734. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2735. }
  2736. }
  2737. break;
  2738. }
  2739. }
  2740. }
  2741. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2742. if (nMeasPoints == 3) {
  2743. mbl.upsample_3x3(); //interpolation from 3x3 to 7x7 points using largrangian polynomials while using the same array z_values[iy][ix] for storing (just coppying measured data to new destination and interpolating between them)
  2744. }
  2745. /*
  2746. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2747. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2748. SERIAL_PROTOCOLPGM(",");
  2749. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2750. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2751. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2752. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2753. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2754. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2755. SERIAL_PROTOCOLPGM(" ");
  2756. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2757. }
  2758. SERIAL_PROTOCOLPGM("\n");
  2759. }
  2760. */
  2761. if (nMeasPoints == 7 && magnet_elimination) {
  2762. mbl_interpolation(nMeasPoints);
  2763. }
  2764. /*
  2765. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2766. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2767. SERIAL_PROTOCOLPGM(",");
  2768. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2769. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2770. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2771. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2772. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2773. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2774. SERIAL_PROTOCOLPGM(" ");
  2775. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2776. }
  2777. SERIAL_PROTOCOLPGM("\n");
  2778. }
  2779. */
  2780. // SERIAL_ECHOLNPGM("Upsample finished");
  2781. mbl.active = 1; //activate mesh bed leveling
  2782. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2783. go_home_with_z_lift();
  2784. // SERIAL_ECHOLNPGM("Go home finished");
  2785. //unretract (after PINDA preheat retraction)
  2786. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2787. current_position[E_AXIS] += default_retraction;
  2788. plan_buffer_line_curposXYZE(400);
  2789. }
  2790. KEEPALIVE_STATE(NOT_BUSY);
  2791. // Restore custom message state
  2792. lcd_setstatuspgm(MSG_WELCOME);
  2793. custom_message_type = custom_message_type_old;
  2794. custom_message_state = custom_message_state_old;
  2795. lcd_update(2);
  2796. st_synchronize();
  2797. mesh_bed_leveling_flag = false;
  2798. }
  2799. void adjust_bed_reset()
  2800. {
  2801. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2802. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2803. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2804. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2805. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2806. }
  2807. //! @brief Calibrate XYZ
  2808. //! @param onlyZ if true, calibrate only Z axis
  2809. //! @param verbosity_level
  2810. //! @retval true Succeeded
  2811. //! @retval false Failed
  2812. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2813. {
  2814. bool final_result = false;
  2815. #ifdef TMC2130
  2816. FORCE_HIGH_POWER_START;
  2817. #endif // TMC2130
  2818. FORCE_BL_ON_START;
  2819. // Only Z calibration?
  2820. if (!onlyZ)
  2821. {
  2822. setTargetBed(0);
  2823. setAllTargetHotends(0);
  2824. adjust_bed_reset(); //reset bed level correction
  2825. }
  2826. // Disable the default update procedure of the display. We will do a modal dialog.
  2827. lcd_update_enable(false);
  2828. // Let the planner use the uncorrected coordinates.
  2829. mbl.reset();
  2830. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2831. // the planner will not perform any adjustments in the XY plane.
  2832. // Wait for the motors to stop and update the current position with the absolute values.
  2833. world2machine_revert_to_uncorrected();
  2834. // Reset the baby step value applied without moving the axes.
  2835. babystep_reset();
  2836. // Mark all axes as in a need for homing.
  2837. memset(axis_known_position, 0, sizeof(axis_known_position));
  2838. // Home in the XY plane.
  2839. //set_destination_to_current();
  2840. int l_feedmultiply = setup_for_endstop_move();
  2841. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2842. raise_z_above(MESH_HOME_Z_SEARCH);
  2843. home_xy();
  2844. enable_endstops(false);
  2845. current_position[X_AXIS] += 5;
  2846. current_position[Y_AXIS] += 5;
  2847. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2848. st_synchronize();
  2849. // Let the user move the Z axes up to the end stoppers.
  2850. #ifdef TMC2130
  2851. if (calibrate_z_auto())
  2852. {
  2853. #else //TMC2130
  2854. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2855. {
  2856. #endif //TMC2130
  2857. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2858. if(onlyZ){
  2859. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2860. lcd_puts_at_P(0,3,_n("1/9"));
  2861. }else{
  2862. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2863. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2864. lcd_puts_at_P(0,3,_n("1/4"));
  2865. }
  2866. refresh_cmd_timeout();
  2867. #ifndef STEEL_SHEET
  2868. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2869. {
  2870. lcd_wait_for_cool_down();
  2871. }
  2872. #endif //STEEL_SHEET
  2873. if(!onlyZ)
  2874. {
  2875. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2876. #ifdef STEEL_SHEET
  2877. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  2878. if(result == LCD_LEFT_BUTTON_CHOICE) {
  2879. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2880. }
  2881. #endif //STEEL_SHEET
  2882. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2883. KEEPALIVE_STATE(IN_HANDLER);
  2884. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2885. lcd_puts_at_P(0,3,_n("1/4"));
  2886. }
  2887. bool endstops_enabled = enable_endstops(false);
  2888. raise_z(-1);
  2889. // Move the print head close to the bed.
  2890. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2891. enable_endstops(true);
  2892. #ifdef TMC2130
  2893. tmc2130_home_enter(Z_AXIS_MASK);
  2894. #endif //TMC2130
  2895. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2896. st_synchronize();
  2897. #ifdef TMC2130
  2898. tmc2130_home_exit();
  2899. #endif //TMC2130
  2900. enable_endstops(endstops_enabled);
  2901. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2902. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2903. {
  2904. if (onlyZ)
  2905. {
  2906. clean_up_after_endstop_move(l_feedmultiply);
  2907. // Z only calibration.
  2908. // Load the machine correction matrix
  2909. world2machine_initialize();
  2910. // and correct the current_position to match the transformed coordinate system.
  2911. world2machine_update_current();
  2912. //FIXME
  2913. bool result = sample_mesh_and_store_reference();
  2914. if (result)
  2915. {
  2916. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2917. {
  2918. // Shipped, the nozzle height has been set already. The user can start printing now.
  2919. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2920. }
  2921. final_result = true;
  2922. // babystep_apply();
  2923. }
  2924. }
  2925. else
  2926. {
  2927. // Reset the baby step value and the baby step applied flag.
  2928. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2929. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2930. // Complete XYZ calibration.
  2931. uint8_t point_too_far_mask = 0;
  2932. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2933. clean_up_after_endstop_move(l_feedmultiply);
  2934. // Print head up.
  2935. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2936. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2937. st_synchronize();
  2938. //#ifndef NEW_XYZCAL
  2939. if (result >= 0)
  2940. {
  2941. #ifdef HEATBED_V2
  2942. sample_z();
  2943. #else //HEATBED_V2
  2944. point_too_far_mask = 0;
  2945. // Second half: The fine adjustment.
  2946. // Let the planner use the uncorrected coordinates.
  2947. mbl.reset();
  2948. world2machine_reset();
  2949. // Home in the XY plane.
  2950. int l_feedmultiply = setup_for_endstop_move();
  2951. home_xy();
  2952. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2953. clean_up_after_endstop_move(l_feedmultiply);
  2954. // Print head up.
  2955. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2956. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2957. st_synchronize();
  2958. // if (result >= 0) babystep_apply();
  2959. #endif //HEATBED_V2
  2960. }
  2961. //#endif //NEW_XYZCAL
  2962. lcd_update_enable(true);
  2963. lcd_update(2);
  2964. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2965. if (result >= 0)
  2966. {
  2967. #ifdef TEMP_MODEL
  2968. calibration_status_store(CALIBRATION_STATUS_TEMP_MODEL_CALIBRATION);
  2969. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_TM_NOT_CAL));
  2970. #else
  2971. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2972. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2973. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2974. #endif //TEMP_MODEL
  2975. final_result = true;
  2976. }
  2977. }
  2978. #ifdef TMC2130
  2979. tmc2130_home_exit();
  2980. #endif
  2981. }
  2982. else
  2983. {
  2984. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2985. final_result = false;
  2986. }
  2987. }
  2988. else
  2989. {
  2990. // Timeouted.
  2991. }
  2992. lcd_update_enable(true);
  2993. #ifdef TMC2130
  2994. FORCE_HIGH_POWER_END;
  2995. #endif // TMC2130
  2996. FORCE_BL_ON_END;
  2997. return final_result;
  2998. }
  2999. void gcode_M114()
  3000. {
  3001. SERIAL_PROTOCOLPGM("X:");
  3002. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3003. SERIAL_PROTOCOLPGM(" Y:");
  3004. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3005. SERIAL_PROTOCOLPGM(" Z:");
  3006. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3007. SERIAL_PROTOCOLPGM(" E:");
  3008. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3009. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  3010. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  3011. SERIAL_PROTOCOLPGM(" Y:");
  3012. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  3013. SERIAL_PROTOCOLPGM(" Z:");
  3014. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  3015. SERIAL_PROTOCOLPGM(" E:");
  3016. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3017. }
  3018. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3019. void gcode_M123()
  3020. {
  3021. printf_P(_N("E0:%d RPM PRN1:%d RPM E0@:%u PRN1@:%d\n"), 60*fan_speed[active_extruder], 60*fan_speed[1], newFanSpeed, fanSpeed);
  3022. }
  3023. #endif //FANCHECK and TACH_0 or TACH_1
  3024. static void mmu_M600_wait_and_beep() {
  3025. // Beep and wait for user to remove old filament and prepare new filament for load
  3026. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3027. int counterBeep = 0;
  3028. lcd_display_message_fullscreen_P(_i("Remove old filament and press the knob to start loading new filament.")); ////MSG_REMOVE_OLD_FILAMENT c=20 r=5
  3029. bool bFirst = true;
  3030. while (!lcd_clicked()) {
  3031. manage_heater();
  3032. manage_inactivity(true);
  3033. #if BEEPER > 0
  3034. if (counterBeep == 500) {
  3035. counterBeep = 0;
  3036. }
  3037. SET_OUTPUT(BEEPER);
  3038. if (counterBeep == 0) {
  3039. if ((eSoundMode == e_SOUND_MODE_BLIND) || (eSoundMode == e_SOUND_MODE_LOUD) || ((eSoundMode == e_SOUND_MODE_ONCE) && bFirst)) {
  3040. bFirst = false;
  3041. WRITE(BEEPER, HIGH);
  3042. }
  3043. }
  3044. if (counterBeep == 20) {
  3045. WRITE(BEEPER, LOW);
  3046. }
  3047. counterBeep++;
  3048. #endif // BEEPER > 0
  3049. delay_keep_alive(4);
  3050. }
  3051. WRITE(BEEPER, LOW);
  3052. }
  3053. /**
  3054. * @brief Handling of unload when using MMU with M600
  3055. * A fullscreen message showing "Unloading Filament x"
  3056. * should be shown on the LCD and LCD updates should be
  3057. * are disabled in the meantime.
  3058. */
  3059. static void mmu_M600_unload_filament() {
  3060. if (MMU2::mmu2.get_current_tool() == (uint8_t)MMU2::FILAMENT_UNKNOWN) return;
  3061. lcd_update_enable(false);
  3062. lcd_clear();
  3063. lcd_puts_at_P(0, 1, _T(MSG_UNLOADING_FILAMENT));
  3064. lcd_print(' ');
  3065. lcd_print(MMU2::mmu2.get_current_tool() + 1);
  3066. // unload just current filament for multimaterial printers (used also in M702)
  3067. MMU2::mmu2.unload();
  3068. lcd_update_enable(true);
  3069. }
  3070. /// @brief load filament for mmu v2
  3071. /// @par nozzle_temp nozzle temperature to load filament
  3072. static void mmu_M600_load_filament(bool automatic, float nozzle_temp) {
  3073. uint8_t slot;
  3074. if (automatic) {
  3075. slot = SpoolJoin::spooljoin.nextSlot();
  3076. } else {
  3077. // Only ask for the slot if automatic/SpoolJoin is off
  3078. slot = choose_menu_P(_T(MSG_SELECT_EXTRUDER), _T(MSG_EXTRUDER));
  3079. }
  3080. setTargetHotend(nozzle_temp, active_extruder);
  3081. MMU2::mmu2.load_filament_to_nozzle(slot);
  3082. load_filament_final_feed(); // @@TODO verify
  3083. st_synchronize();
  3084. }
  3085. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3086. st_synchronize();
  3087. float lastpos[4];
  3088. prusa_statistics(22);
  3089. //First backup current position and settings
  3090. int feedmultiplyBckp = feedmultiply;
  3091. float HotendTempBckp = degTargetHotend(active_extruder);
  3092. int fanSpeedBckp = fanSpeed;
  3093. memcpy(lastpos, current_position, sizeof(lastpos));
  3094. // Turn off the fan
  3095. fanSpeed = 0;
  3096. // Retract E
  3097. current_position[E_AXIS] += e_shift;
  3098. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3099. st_synchronize();
  3100. // Raise the Z axis
  3101. raise_z(z_shift);
  3102. // Move XY to side
  3103. current_position[X_AXIS] = x_position;
  3104. current_position[Y_AXIS] = y_position;
  3105. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3106. st_synchronize();
  3107. // Beep, manage nozzle heater and wait for user to start unload filament
  3108. if (!MMU2::mmu2.Enabled())
  3109. M600_wait_for_user(HotendTempBckp);
  3110. // Unload filament
  3111. if (MMU2::mmu2.Enabled())
  3112. mmu_M600_unload_filament();
  3113. else
  3114. unload_filament(FILAMENTCHANGE_FINALRETRACT);
  3115. st_synchronize(); // finish moves
  3116. {
  3117. FSensorBlockRunout fsBlockRunout;
  3118. if (!MMU2::mmu2.Enabled())
  3119. {
  3120. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3121. uint8_t choice =
  3122. lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"), false, LCD_LEFT_BUTTON_CHOICE); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3123. if (choice == LCD_MIDDLE_BUTTON_CHOICE) {
  3124. lcd_clear();
  3125. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3126. current_position[X_AXIS] -= 100;
  3127. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3128. st_synchronize();
  3129. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually.")); ////MSG_CHECK_IDLER c=20 r=5
  3130. }
  3131. M600_load_filament();
  3132. }
  3133. else // MMU is enabled
  3134. {
  3135. if (!automatic) {
  3136. if (saved_printing){
  3137. // if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3138. MMU2::mmu2.eject_filament(MMU2::mmu2.get_current_tool(), false);
  3139. }
  3140. mmu_M600_wait_and_beep();
  3141. if (saved_printing) {
  3142. lcd_clear();
  3143. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3144. //@@TODO mmu_command(MmuCmd::R0);
  3145. // manage_response(false, false);
  3146. }
  3147. }
  3148. mmu_M600_load_filament(automatic, HotendTempBckp);
  3149. }
  3150. if (!automatic)
  3151. M600_check_state(HotendTempBckp);
  3152. lcd_update_enable(true);
  3153. // Not let's go back to print
  3154. fanSpeed = fanSpeedBckp;
  3155. // Feed a little of filament to stabilize pressure
  3156. if (!automatic) {
  3157. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3158. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3159. }
  3160. // Move XY back
  3161. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3162. st_synchronize();
  3163. // Move Z back
  3164. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3165. st_synchronize();
  3166. // Set E position to original
  3167. plan_set_e_position(lastpos[E_AXIS]);
  3168. memcpy(current_position, lastpos, sizeof(lastpos));
  3169. set_destination_to_current();
  3170. // Recover feed rate
  3171. feedmultiply = feedmultiplyBckp;
  3172. char cmd[9];
  3173. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3174. enquecommand(cmd);
  3175. }
  3176. lcd_setstatuspgm(MSG_WELCOME);
  3177. custom_message_type = CustomMsg::Status;
  3178. }
  3179. void gcode_M701(float fastLoadLength, uint8_t mmuSlotIndex){
  3180. FSensorBlockRunout fsBlockRunout;
  3181. prusa_statistics(22);
  3182. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3183. MMU2::mmu2.load_filament_to_nozzle(mmuSlotIndex);
  3184. } else {
  3185. custom_message_type = CustomMsg::FilamentLoading;
  3186. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3187. current_position[E_AXIS] += fastLoadLength;
  3188. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3189. load_filament_final_feed(); // slow sequence
  3190. st_synchronize();
  3191. Sound_MakeCustom(50, 500, false);
  3192. if (!farm_mode && loading_flag) {
  3193. lcd_load_filament_color_check();
  3194. }
  3195. lcd_update_enable(true);
  3196. lcd_update(2);
  3197. lcd_setstatuspgm(MSG_WELCOME);
  3198. loading_flag = false;
  3199. custom_message_type = CustomMsg::Status;
  3200. }
  3201. eFilamentAction = FilamentAction::None;
  3202. }
  3203. // Common gcode shared by the gcodes. This saves some flash memory
  3204. static void gcodes_M704_M705_M706(uint16_t gcode)
  3205. {
  3206. uint8_t mmuSlotIndex = 0xffU;
  3207. if (MMU2::mmu2.Enabled() && code_seen('P'))
  3208. {
  3209. mmuSlotIndex = code_value_uint8();
  3210. if (mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3211. switch (gcode)
  3212. {
  3213. case 704:
  3214. MMU2::mmu2.load_filament(mmuSlotIndex);
  3215. break;
  3216. case 705:
  3217. MMU2::mmu2.eject_filament(mmuSlotIndex, false);
  3218. break;
  3219. case 706:
  3220. #ifdef MMU_HAS_CUTTER
  3221. if (eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED) != 0){
  3222. MMU2::mmu2.cut_filament(mmuSlotIndex);
  3223. }
  3224. #endif // MMU_HAS_CUTTER
  3225. break;
  3226. default:
  3227. break;
  3228. }
  3229. }
  3230. }
  3231. }
  3232. /**
  3233. * @brief Get serial number from 32U2 processor
  3234. *
  3235. * Typical format of S/N is:CZPX0917X003XC13518
  3236. *
  3237. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3238. * reply is stored in *SN.
  3239. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3240. * and returns a general failure flag.
  3241. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3242. * In that case the value that is stored in the EEPROM should be used instead.
  3243. *
  3244. * @return 0 on success
  3245. * @return 1 on general failure
  3246. */
  3247. #ifdef PRUSA_SN_SUPPORT
  3248. static uint8_t get_PRUSA_SN(char* SN)
  3249. {
  3250. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3251. uint8_t rxIndex;
  3252. bool SN_valid = false;
  3253. ShortTimer timeout;
  3254. selectedSerialPort = 0;
  3255. timeout.start();
  3256. while (!SN_valid)
  3257. {
  3258. rxIndex = 0;
  3259. _delay(50);
  3260. MYSERIAL.flush(); //clear RX buffer
  3261. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3262. while (rxIndex < 19)
  3263. {
  3264. if (timeout.expired(250u))
  3265. goto exit;
  3266. if (MYSERIAL.available() > 0)
  3267. {
  3268. SN[rxIndex] = MYSERIAL.read();
  3269. rxIndex++;
  3270. }
  3271. }
  3272. SN[rxIndex] = 0;
  3273. // printf_P(PSTR("SN:%s\n"), SN);
  3274. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3275. }
  3276. exit:
  3277. selectedSerialPort = selectedSerialPort_bak;
  3278. return !SN_valid;
  3279. }
  3280. #endif //PRUSA_SN_SUPPORT
  3281. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3282. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3283. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3284. //! it may even interfere with other functions of the printer! You have been warned!
  3285. //! The test idea is to measure the time necessary to charge the capacitor.
  3286. //! So the algorithm is as follows:
  3287. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3288. //! 2. Wait a few ms
  3289. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3290. //! Repeat 1.-3. several times
  3291. //! Good RAMBo's times are in the range of approx. 260-320 us
  3292. //! Bad RAMBo's times are approx. 260-1200 us
  3293. //! So basically we are interested in maximum time, the minima are mostly the same.
  3294. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3295. static void gcode_PRUSA_BadRAMBoFanTest(){
  3296. //printf_P(PSTR("Enter fan pin test\n"));
  3297. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3298. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3299. unsigned long tach1max = 0;
  3300. uint8_t tach1cntr = 0;
  3301. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3302. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3303. SET_OUTPUT(TACH_1);
  3304. WRITE(TACH_1, LOW);
  3305. _delay(20); // the delay may be lower
  3306. unsigned long tachMeasure = _micros();
  3307. cli();
  3308. SET_INPUT(TACH_1);
  3309. // just wait brutally in an endless cycle until we reach HIGH
  3310. // if this becomes a problem it may be improved to non-endless cycle
  3311. while( READ(TACH_1) == 0 ) ;
  3312. sei();
  3313. tachMeasure = _micros() - tachMeasure;
  3314. if( tach1max < tachMeasure )
  3315. tach1max = tachMeasure;
  3316. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3317. }
  3318. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3319. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3320. if( tach1max > 500 ){
  3321. // bad RAMBo
  3322. SERIAL_PROTOCOLLNPGM("BAD");
  3323. } else {
  3324. SERIAL_PROTOCOLLNPGM("OK");
  3325. }
  3326. // cleanup after the test function
  3327. SET_INPUT(TACH_1);
  3328. WRITE(TACH_1, HIGH);
  3329. #endif
  3330. }
  3331. // G92 - Set current position to coordinates given
  3332. static void gcode_G92()
  3333. {
  3334. bool codes[NUM_AXIS];
  3335. float values[NUM_AXIS];
  3336. // Check which axes need to be set
  3337. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3338. {
  3339. codes[i] = code_seen(axis_codes[i]);
  3340. if(codes[i])
  3341. values[i] = code_value();
  3342. }
  3343. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3344. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3345. {
  3346. // As a special optimization, when _just_ clearing the E position
  3347. // we schedule a flag asynchronously along with the next block to
  3348. // reset the starting E position instead of stopping the planner
  3349. current_position[E_AXIS] = 0;
  3350. plan_reset_next_e();
  3351. }
  3352. else
  3353. {
  3354. // In any other case we're forced to synchronize
  3355. st_synchronize();
  3356. for(uint8_t i = 0; i < 3; ++i)
  3357. {
  3358. if(codes[i])
  3359. current_position[i] = values[i] + cs.add_homing[i];
  3360. }
  3361. if(codes[E_AXIS])
  3362. current_position[E_AXIS] = values[E_AXIS];
  3363. // Set all at once
  3364. plan_set_position_curposXYZE();
  3365. }
  3366. }
  3367. #ifdef EXTENDED_CAPABILITIES_REPORT
  3368. static void cap_line(const char* name, bool ena = false) {
  3369. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3370. }
  3371. static void extended_capabilities_report()
  3372. {
  3373. // AUTOREPORT_TEMP (M155)
  3374. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3375. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3376. // AUTOREPORT_FANS (M123)
  3377. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3378. #endif //FANCHECK and TACH_0 or TACH_1
  3379. // AUTOREPORT_POSITION (M114)
  3380. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3381. // EXTENDED_M20 (support for L and T parameters)
  3382. cap_line(PSTR("EXTENDED_M20"), 1);
  3383. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3384. }
  3385. #endif //EXTENDED_CAPABILITIES_REPORT
  3386. #ifdef BACKLASH_X
  3387. extern uint8_t st_backlash_x;
  3388. #endif //BACKLASH_X
  3389. #ifdef BACKLASH_Y
  3390. extern uint8_t st_backlash_y;
  3391. #endif //BACKLASH_Y
  3392. //! \ingroup marlin_main
  3393. //! @brief Parse and process commands
  3394. //!
  3395. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3396. //!
  3397. //!
  3398. //! Implemented Codes
  3399. //! -------------------
  3400. //!
  3401. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3402. //!
  3403. //!@n PRUSA CODES
  3404. //!@n P F - Returns FW versions
  3405. //!@n P R - Returns revision of printer
  3406. //!
  3407. //!@n G0 -> G1
  3408. //!@n G1 - Coordinated Movement X Y Z E
  3409. //!@n G2 - CW ARC
  3410. //!@n G3 - CCW ARC
  3411. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3412. //!@n G10 - retract filament according to settings of M207
  3413. //!@n G11 - retract recover filament according to settings of M208
  3414. //!@n G28 - Home all Axes
  3415. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3416. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3417. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3418. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3419. //!@n G80 - Automatic mesh bed leveling
  3420. //!@n G81 - Print bed profile
  3421. //!@n G90 - Use Absolute Coordinates
  3422. //!@n G91 - Use Relative Coordinates
  3423. //!@n G92 - Set current position to coordinates given
  3424. //!
  3425. //!@n M Codes
  3426. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3427. //!@n M1 - Same as M0
  3428. //!@n M17 - Enable/Power all stepper motors
  3429. //!@n M18 - Disable all stepper motors; same as M84
  3430. //!@n M20 - List SD card
  3431. //!@n M21 - Init SD card
  3432. //!@n M22 - Release SD card
  3433. //!@n M23 - Select SD file (M23 filename.g)
  3434. //!@n M24 - Start/resume SD print
  3435. //!@n M25 - Pause SD print
  3436. //!@n M26 - Set SD position in bytes (M26 S12345)
  3437. //!@n M27 - Report SD print status
  3438. //!@n M28 - Start SD write (M28 filename.g)
  3439. //!@n M29 - Stop SD write
  3440. //!@n M30 - Delete file from SD (M30 filename.g)
  3441. //!@n M31 - Output time since last M109 or SD card start to serial
  3442. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3443. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3444. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3445. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3446. //!@n 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.
  3447. //!@n M73 - Show percent done and print time remaining
  3448. //!@n M80 - Turn on Power Supply
  3449. //!@n M81 - Turn off Power Supply
  3450. //!@n M82 - Set E codes absolute (default)
  3451. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3452. //!@n M84 - Disable steppers until next move,
  3453. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3454. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3455. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3456. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3457. //!@n M104 - Set extruder target temp
  3458. //!@n M105 - Read current temp
  3459. //!@n M106 - Fan on
  3460. //!@n M107 - Fan off
  3461. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3462. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3463. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3464. //!@n M112 - Emergency stop
  3465. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3466. //!@n M114 - Output current position to serial port
  3467. //!@n M115 - Capabilities string
  3468. //!@n M117 - display message
  3469. //!@n M119 - Output Endstop status to serial port
  3470. //!@n M123 - Tachometer value
  3471. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3472. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3473. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3474. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3475. //!@n M140 - Set bed target temp
  3476. //!@n 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.
  3477. //!@n M155 - Automatically send temperatures, fan speeds, position
  3478. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3479. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3480. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3481. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3482. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3483. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3484. //!@n M204 - Set default acceleration: S normal moves T filament only moves (M204 S3000 T7000) in mm/sec^2 also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  3485. //!@n 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
  3486. //!@n M206 - set additional homing offset
  3487. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3488. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3489. //!@n 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.
  3490. //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  3491. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3492. //!@n M220 S<factor in percent>- set speed factor override percentage
  3493. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3494. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3495. //!@n M240 - Trigger a camera to take a photograph
  3496. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3497. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3498. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3499. //!@n M301 - Set PID parameters P I and D
  3500. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3501. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3502. //!@n M304 - Set bed PID parameters P I and D
  3503. //!@n M310 - Temperature model settings
  3504. //!@n M400 - Finish all moves
  3505. //!@n M401 - Lower z-probe if present
  3506. //!@n M402 - Raise z-probe if present
  3507. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3508. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3509. //!@n M406 - Turn off Filament Sensor extrusion control
  3510. //!@n M407 - Displays measured filament diameter
  3511. //!@n M500 - stores parameters in EEPROM
  3512. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3513. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3514. //!@n M503 - print the current settings (from memory not from EEPROM)
  3515. //!@n M509 - force language selection on next restart
  3516. //!@n M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  3517. //!@n M552 - Set IP address
  3518. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3519. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3520. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3521. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3522. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3523. //!@n M907 - Set digital trimpot motor current using axis codes.
  3524. //!@n M908 - Control digital trimpot directly.
  3525. //!@n M350 - Set microstepping mode.
  3526. //!@n M351 - Toggle MS1 MS2 pins directly.
  3527. //!
  3528. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3529. //!@n M999 - Restart after being stopped by error
  3530. //! <br><br>
  3531. /** @defgroup marlin_main Marlin main */
  3532. /** \ingroup GCodes */
  3533. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3534. /**
  3535. They are shown in order of appearance in the code.
  3536. There are reasons why some G Codes aren't in numerical order.
  3537. */
  3538. void process_commands()
  3539. {
  3540. if (!buflen) return; //empty command
  3541. #ifdef CMDBUFFER_DEBUG
  3542. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3543. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3544. SERIAL_ECHOLNPGM("");
  3545. SERIAL_ECHOPGM("In cmdqueue: ");
  3546. SERIAL_ECHO(buflen);
  3547. SERIAL_ECHOLNPGM("");
  3548. #endif /* CMDBUFFER_DEBUG */
  3549. unsigned long codenum; //throw away variable
  3550. char *starpos = NULL;
  3551. #ifdef ENABLE_AUTO_BED_LEVELING
  3552. float x_tmp, y_tmp, z_tmp, real_z;
  3553. #endif
  3554. // PRUSA GCODES
  3555. KEEPALIVE_STATE(IN_HANDLER);
  3556. /*!
  3557. ---------------------------------------------------------------------------------
  3558. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3559. This causes the given message to be shown in the status line on an attached LCD.
  3560. It is processed early as to allow printing messages that contain G, M, N or T.
  3561. ---------------------------------------------------------------------------------
  3562. ### Special internal commands
  3563. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3564. They are processed early as the commands are complex (strings).
  3565. These are only available on the MK3(S) as these require TMC2130 drivers:
  3566. - CRASH DETECTED
  3567. - CRASH RECOVER
  3568. - CRASH_CANCEL
  3569. - TMC_SET_WAVE
  3570. - TMC_SET_STEP
  3571. - TMC_SET_CHOP
  3572. */
  3573. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3574. {
  3575. starpos = (strchr(strchr_pointer + 5, '*'));
  3576. if (starpos != NULL)
  3577. *(starpos) = '\0';
  3578. lcd_setstatus(strchr_pointer + 5);
  3579. custom_message_type = CustomMsg::M117;
  3580. }
  3581. /*!
  3582. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3583. #### Usage
  3584. M0 [P<ms<] [S<sec>] [string]
  3585. M1 [P<ms>] [S<sec>] [string]
  3586. #### Parameters
  3587. - `P<ms>` - Expire time, in milliseconds
  3588. - `S<sec>` - Expire time, in seconds
  3589. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3590. */
  3591. else if (code_seen_P(PSTR("M0")) || code_seen_P(PSTR("M1 "))) {// M0 and M1 - (Un)conditional stop - Wait for user button press on LCD
  3592. const char *src = strchr_pointer + 2;
  3593. codenum = 0;
  3594. bool hasP = false, hasS = false;
  3595. if (code_seen('P')) {
  3596. codenum = code_value_long(); // milliseconds to wait
  3597. hasP = codenum > 0;
  3598. }
  3599. if (code_seen('S')) {
  3600. codenum = code_value_long() * 1000; // seconds to wait
  3601. hasS = codenum > 0;
  3602. }
  3603. starpos = strchr(src, '*');
  3604. if (starpos != NULL) *(starpos) = '\0';
  3605. while (*src == ' ') ++src;
  3606. custom_message_type = CustomMsg::M0Wait;
  3607. if (!hasP && !hasS && *src != '\0') {
  3608. lcd_setstatus(src);
  3609. } else {
  3610. // farmers want to abuse a bug from the previous firmware releases
  3611. // - they need to see the filename on the status screen instead of "Wait for user..."
  3612. // So we won't update the message in farm mode...
  3613. if( ! farm_mode){
  3614. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3615. } else {
  3616. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3617. }
  3618. }
  3619. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3620. st_synchronize();
  3621. previous_millis_cmd.start();
  3622. if (codenum > 0 ) {
  3623. codenum += _millis(); // keep track of when we started waiting
  3624. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3625. while(_millis() < codenum && !lcd_clicked()) {
  3626. manage_heater();
  3627. manage_inactivity(true);
  3628. lcd_update(0);
  3629. }
  3630. KEEPALIVE_STATE(IN_HANDLER);
  3631. lcd_ignore_click(false);
  3632. } else {
  3633. marlin_wait_for_click();
  3634. }
  3635. if (IS_SD_PRINTING)
  3636. custom_message_type = CustomMsg::Status;
  3637. else
  3638. LCD_MESSAGERPGM(MSG_WELCOME);
  3639. }
  3640. #ifdef TMC2130
  3641. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3642. {
  3643. // ### CRASH_DETECTED - TMC2130
  3644. // ---------------------------------
  3645. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3646. {
  3647. uint8_t mask = 0;
  3648. if (code_seen('X')) mask |= X_AXIS_MASK;
  3649. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3650. crashdet_detected(mask);
  3651. }
  3652. // ### CRASH_RECOVER - TMC2130
  3653. // ----------------------------------
  3654. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3655. crashdet_recover();
  3656. // ### CRASH_CANCEL - TMC2130
  3657. // ----------------------------------
  3658. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3659. crashdet_cancel();
  3660. }
  3661. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3662. {
  3663. // ### TMC_SET_WAVE_
  3664. // --------------------
  3665. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3666. {
  3667. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3668. axis = (axis == 'E')?3:(axis - 'X');
  3669. if (axis < 4)
  3670. {
  3671. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3672. tmc2130_set_wave(axis, 247, fac);
  3673. }
  3674. }
  3675. // ### TMC_SET_STEP_
  3676. // ------------------
  3677. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3678. {
  3679. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3680. axis = (axis == 'E')?3:(axis - 'X');
  3681. if (axis < 4)
  3682. {
  3683. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3684. uint16_t res = tmc2130_get_res(axis);
  3685. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3686. }
  3687. }
  3688. // ### TMC_SET_CHOP_
  3689. // -------------------
  3690. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3691. {
  3692. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3693. axis = (axis == 'E')?3:(axis - 'X');
  3694. if (axis < 4)
  3695. {
  3696. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3697. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3698. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3699. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3700. char* str_end = 0;
  3701. if (CMDBUFFER_CURRENT_STRING[14])
  3702. {
  3703. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3704. if (str_end && *str_end)
  3705. {
  3706. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3707. if (str_end && *str_end)
  3708. {
  3709. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3710. if (str_end && *str_end)
  3711. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3712. }
  3713. }
  3714. }
  3715. tmc2130_chopper_config[axis].toff = chop0;
  3716. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3717. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3718. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3719. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3720. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3721. }
  3722. }
  3723. }
  3724. #ifdef BACKLASH_X
  3725. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3726. {
  3727. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3728. st_backlash_x = bl;
  3729. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3730. }
  3731. #endif //BACKLASH_X
  3732. #ifdef BACKLASH_Y
  3733. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3734. {
  3735. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3736. st_backlash_y = bl;
  3737. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3738. }
  3739. #endif //BACKLASH_Y
  3740. #endif //TMC2130
  3741. else if(code_seen_P(PSTR("PRUSA"))){
  3742. /*!
  3743. ---------------------------------------------------------------------------------
  3744. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3745. Set of internal PRUSA commands
  3746. #### Usage
  3747. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3748. #### Parameters
  3749. - `PRN` - Prints revision of the printer
  3750. - `FAN` - Prints fan details
  3751. - `thx`
  3752. - `uvlo`
  3753. - `MMURES` - Reset MMU
  3754. - `RESET` - (Careful!)
  3755. - `fv` - ?
  3756. - `M28`
  3757. - `SN`
  3758. - `Fir` - Prints firmware version
  3759. - `Rev`- Prints filament size, elelectronics, nozzle type
  3760. - `Lang` - Reset the language
  3761. - `Lz`
  3762. - `FR` - Full factory reset
  3763. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3764. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3765. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3766. */
  3767. if (farm_prusa_code_seen()) {}
  3768. else if(code_seen_P(PSTR("FANPINTST"))) {
  3769. gcode_PRUSA_BadRAMBoFanTest();
  3770. }
  3771. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3772. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3773. }
  3774. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3775. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3776. enquecommand_P(PSTR("M24"));
  3777. }
  3778. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3779. {
  3780. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  3781. }
  3782. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3783. #if defined(XFLASH) && defined(BOOTAPP)
  3784. boot_app_magic = BOOT_APP_MAGIC;
  3785. boot_app_flags = BOOT_APP_FLG_RUN;
  3786. #endif //defined(XFLASH) && defined(BOOTAPP)
  3787. softReset();
  3788. }
  3789. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3790. char SN[20];
  3791. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3792. if (SN[19])
  3793. puts_P(PSTR("SN invalid"));
  3794. else
  3795. puts(SN);
  3796. }
  3797. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3798. SERIAL_PROTOCOLLNPGM(FW_VERSION_FULL);
  3799. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3800. SERIAL_PROTOCOLLNPGM(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3801. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3802. lang_reset();
  3803. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3804. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3805. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3806. // Factory full reset
  3807. factory_reset(0);
  3808. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3809. // Change the MBL status without changing the logical Z position.
  3810. if(code_seen('V')) {
  3811. bool value = code_value_short();
  3812. st_synchronize();
  3813. if(value != mbl.active) {
  3814. mbl.active = value;
  3815. // Use plan_set_z_position to reset the physical values
  3816. plan_set_z_position(current_position[Z_AXIS]);
  3817. }
  3818. }
  3819. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3820. uint16_t nDiameter;
  3821. if(code_seen('D'))
  3822. {
  3823. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3824. nozzle_diameter_check(nDiameter);
  3825. }
  3826. else if(code_seen_P(PSTR("set")) && farm_mode)
  3827. {
  3828. strchr_pointer++; // skip 1st char (~ 's')
  3829. strchr_pointer++; // skip 2nd char (~ 'e')
  3830. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3831. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3832. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3833. }
  3834. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3835. }
  3836. }
  3837. else if(code_seen('G'))
  3838. {
  3839. gcode_in_progress = code_value_short();
  3840. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3841. switch (gcode_in_progress)
  3842. {
  3843. /*!
  3844. ---------------------------------------------------------------------------------
  3845. # G Codes
  3846. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3847. In Prusa Firmware G0 and G1 are the same.
  3848. #### Usage
  3849. G0 [ X | Y | Z | E | F | S ]
  3850. G1 [ X | Y | Z | E | F | S ]
  3851. #### Parameters
  3852. - `X` - The position to move to on the X axis
  3853. - `Y` - The position to move to on the Y axis
  3854. - `Z` - The position to move to on the Z axis
  3855. - `E` - The amount to extrude between the starting point and ending point
  3856. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3857. */
  3858. case 0: // G0 -> G1
  3859. case 1: // G1
  3860. {
  3861. uint16_t start_segment_idx = restore_interrupted_gcode();
  3862. get_coordinates(); // For X Y Z E F
  3863. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3864. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3865. }
  3866. #ifdef FWRETRACT
  3867. if(cs.autoretract_enabled) {
  3868. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3869. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3870. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3871. st_synchronize();
  3872. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3873. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3874. retract(!retracted[active_extruder]);
  3875. return;
  3876. }
  3877. }
  3878. }
  3879. #endif //FWRETRACT
  3880. prepare_move(start_segment_idx);
  3881. //ClearToSend();
  3882. }
  3883. break;
  3884. /*!
  3885. ### G2, G3 - Controlled Arc Move <a href="https://reprap.org/wiki/G-code#G2_.26_G3:_Controlled_Arc_Move">G2 & G3: Controlled Arc Move</a>
  3886. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3887. #### Usage
  3888. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3889. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3890. #### Parameters
  3891. - `X` - The position to move to on the X axis
  3892. - `Y` - The position to move to on the Y axis
  3893. - 'Z' - The position to move to on the Z axis
  3894. - `I` - The point in X space from the current X position to maintain a constant distance from
  3895. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3896. - `E` - The amount to extrude between the starting point and ending point
  3897. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3898. */
  3899. case 2:
  3900. case 3:
  3901. {
  3902. uint16_t start_segment_idx = restore_interrupted_gcode();
  3903. #ifdef SF_ARC_FIX
  3904. bool relative_mode_backup = relative_mode;
  3905. relative_mode = true;
  3906. #endif
  3907. get_coordinates(); // For X Y Z E F
  3908. #ifdef SF_ARC_FIX
  3909. relative_mode=relative_mode_backup;
  3910. #endif
  3911. offset[0] = code_seen('I') ? code_value() : 0.f;
  3912. offset[1] = code_seen('J') ? code_value() : 0.f;
  3913. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3914. } break;
  3915. /*!
  3916. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3917. Pause the machine for a period of time.
  3918. #### Usage
  3919. G4 [ P | S ]
  3920. #### Parameters
  3921. - `P` - Time to wait, in milliseconds
  3922. - `S` - Time to wait, in seconds
  3923. */
  3924. case 4:
  3925. codenum = 0;
  3926. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3927. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3928. if(codenum != 0)
  3929. {
  3930. if(custom_message_type != CustomMsg::M117)
  3931. {
  3932. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3933. }
  3934. }
  3935. st_synchronize();
  3936. codenum += _millis(); // keep track of when we started waiting
  3937. previous_millis_cmd.start();
  3938. while(_millis() < codenum) {
  3939. manage_heater();
  3940. manage_inactivity();
  3941. lcd_update(0);
  3942. }
  3943. break;
  3944. #ifdef FWRETRACT
  3945. /*!
  3946. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3947. Retracts filament according to settings of `M207`
  3948. */
  3949. case 10:
  3950. #if EXTRUDERS > 1
  3951. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3952. retract(true,retracted_swap[active_extruder]);
  3953. #else
  3954. retract(true);
  3955. #endif
  3956. break;
  3957. /*!
  3958. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3959. Unretracts/recovers filament according to settings of `M208`
  3960. */
  3961. case 11:
  3962. #if EXTRUDERS > 1
  3963. retract(false,retracted_swap[active_extruder]);
  3964. #else
  3965. retract(false);
  3966. #endif
  3967. break;
  3968. #endif //FWRETRACT
  3969. /*!
  3970. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  3971. Units are in millimeters. Prusa doesn't support inches.
  3972. */
  3973. case 21:
  3974. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  3975. /*!
  3976. ### G28 - Home all Axes one at a time <a href="https://reprap.org/wiki/G-code#G28:_Move_to_Origin_.28Home.29">G28: Move to Origin (Home)</a>
  3977. Using `G28` without any parameters will perfom homing of all axes AND mesh bed leveling, while `G28 W` will just home all axes (no mesh bed leveling).
  3978. #### Usage
  3979. G28 [ X | Y | Z | W | C ]
  3980. #### Parameters
  3981. - `X` - Flag to go back to the X axis origin
  3982. - `Y` - Flag to go back to the Y axis origin
  3983. - `Z` - Flag to go back to the Z axis origin
  3984. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  3985. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  3986. */
  3987. case 28:
  3988. {
  3989. long home_x_value = 0;
  3990. long home_y_value = 0;
  3991. long home_z_value = 0;
  3992. // Which axes should be homed?
  3993. bool home_x = code_seen(axis_codes[X_AXIS]);
  3994. if (home_x) home_x_value = code_value_long();
  3995. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3996. if (home_y) home_y_value = code_value_long();
  3997. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3998. if (home_z) home_z_value = code_value_long();
  3999. bool without_mbl = code_seen('W');
  4000. // calibrate?
  4001. #ifdef TMC2130
  4002. bool calib = code_seen('C');
  4003. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4004. #else
  4005. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4006. #endif //TMC2130
  4007. if ((home_x || home_y || without_mbl || home_z) == false) {
  4008. gcode_G80();
  4009. }
  4010. break;
  4011. }
  4012. #ifdef ENABLE_AUTO_BED_LEVELING
  4013. /*!
  4014. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4015. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4016. See `G81`
  4017. */
  4018. case 29:
  4019. {
  4020. #if Z_MIN_PIN == -1
  4021. #error "You must have a Z_MIN endstop in order to enable Auto Bed Leveling feature! Z_MIN_PIN must point to a valid hardware pin."
  4022. #endif
  4023. // Prevent user from running a G29 without first homing in X and Y
  4024. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4025. {
  4026. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4027. SERIAL_ECHO_START;
  4028. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4029. break; // abort G29, since we don't know where we are
  4030. }
  4031. st_synchronize();
  4032. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4033. //vector_3 corrected_position = plan_get_position_mm();
  4034. //corrected_position.debug("position before G29");
  4035. plan_bed_level_matrix.set_to_identity();
  4036. vector_3 uncorrected_position = plan_get_position();
  4037. //uncorrected_position.debug("position durring G29");
  4038. current_position[X_AXIS] = uncorrected_position.x;
  4039. current_position[Y_AXIS] = uncorrected_position.y;
  4040. current_position[Z_AXIS] = uncorrected_position.z;
  4041. plan_set_position_curposXYZE();
  4042. int l_feedmultiply = setup_for_endstop_move();
  4043. feedrate = homing_feedrate[Z_AXIS];
  4044. #ifdef AUTO_BED_LEVELING_GRID
  4045. // probe at the points of a lattice grid
  4046. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4047. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4048. // solve the plane equation ax + by + d = z
  4049. // A is the matrix with rows [x y 1] for all the probed points
  4050. // B is the vector of the Z positions
  4051. // 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
  4052. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4053. // "A" matrix of the linear system of equations
  4054. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4055. // "B" vector of Z points
  4056. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4057. int probePointCounter = 0;
  4058. bool zig = true;
  4059. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4060. {
  4061. int xProbe, xInc;
  4062. if (zig)
  4063. {
  4064. xProbe = LEFT_PROBE_BED_POSITION;
  4065. //xEnd = RIGHT_PROBE_BED_POSITION;
  4066. xInc = xGridSpacing;
  4067. zig = false;
  4068. } else // zag
  4069. {
  4070. xProbe = RIGHT_PROBE_BED_POSITION;
  4071. //xEnd = LEFT_PROBE_BED_POSITION;
  4072. xInc = -xGridSpacing;
  4073. zig = true;
  4074. }
  4075. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4076. {
  4077. float z_before;
  4078. if (probePointCounter == 0)
  4079. {
  4080. // raise before probing
  4081. z_before = Z_RAISE_BEFORE_PROBING;
  4082. } else
  4083. {
  4084. // raise extruder
  4085. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4086. }
  4087. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4088. eqnBVector[probePointCounter] = measured_z;
  4089. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4090. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4091. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4092. probePointCounter++;
  4093. xProbe += xInc;
  4094. }
  4095. }
  4096. clean_up_after_endstop_move(l_feedmultiply);
  4097. // solve lsq problem
  4098. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4099. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4100. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4101. SERIAL_PROTOCOLPGM(" b: ");
  4102. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4103. SERIAL_PROTOCOLPGM(" d: ");
  4104. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4105. set_bed_level_equation_lsq(plane_equation_coefficients);
  4106. free(plane_equation_coefficients);
  4107. #else // AUTO_BED_LEVELING_GRID not defined
  4108. // Probe at 3 arbitrary points
  4109. // probe 1
  4110. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4111. // probe 2
  4112. float z_at_pt_2 = probe_pt(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  4113. // probe 3
  4114. float z_at_pt_3 = probe_pt(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  4115. clean_up_after_endstop_move(l_feedmultiply);
  4116. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4117. #endif // AUTO_BED_LEVELING_GRID
  4118. st_synchronize();
  4119. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4120. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4121. // When the bed is uneven, this height must be corrected.
  4122. real_z = float(st_get_position(Z_AXIS))/cs.axis_steps_per_unit[Z_AXIS]; //get the real Z (since the auto bed leveling is already correcting the plane)
  4123. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4124. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4125. z_tmp = current_position[Z_AXIS];
  4126. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4127. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4128. plan_set_position_curposXYZE();
  4129. }
  4130. break;
  4131. #ifndef Z_PROBE_SLED
  4132. /*!
  4133. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4134. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4135. */
  4136. case 30:
  4137. {
  4138. st_synchronize();
  4139. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4140. int l_feedmultiply = setup_for_endstop_move();
  4141. feedrate = homing_feedrate[Z_AXIS];
  4142. run_z_probe();
  4143. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4144. SERIAL_PROTOCOLPGM(" X: ");
  4145. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4146. SERIAL_PROTOCOLPGM(" Y: ");
  4147. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4148. SERIAL_PROTOCOLPGM(" Z: ");
  4149. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4150. SERIAL_PROTOCOLPGM("\n");
  4151. clean_up_after_endstop_move(l_feedmultiply);
  4152. }
  4153. break;
  4154. #else
  4155. /*!
  4156. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4157. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4158. */
  4159. case 31:
  4160. dock_sled(true);
  4161. break;
  4162. /*!
  4163. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4164. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4165. */
  4166. case 32:
  4167. dock_sled(false);
  4168. break;
  4169. #endif // Z_PROBE_SLED
  4170. #endif // ENABLE_AUTO_BED_LEVELING
  4171. #ifdef MESH_BED_LEVELING
  4172. /*!
  4173. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4174. Sensor must be over the bed.
  4175. The maximum travel distance before an error is triggered is 10mm.
  4176. */
  4177. case 30:
  4178. {
  4179. st_synchronize();
  4180. homing_flag = true;
  4181. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4182. int l_feedmultiply = setup_for_endstop_move();
  4183. feedrate = homing_feedrate[Z_AXIS];
  4184. find_bed_induction_sensor_point_z(-10.f, 3);
  4185. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4186. clean_up_after_endstop_move(l_feedmultiply);
  4187. homing_flag = false;
  4188. }
  4189. break;
  4190. /*!
  4191. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4192. Show/print PINDA temperature interpolating.
  4193. */
  4194. case 75:
  4195. {
  4196. for (uint8_t i = 40; i <= 110; i++)
  4197. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4198. }
  4199. break;
  4200. /*!
  4201. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4202. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4203. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4204. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4205. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4206. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4207. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4208. #### Example
  4209. ```
  4210. G76
  4211. echo PINDA probe calibration start
  4212. echo start temperature: 35.0°
  4213. echo ...
  4214. echo PINDA temperature -- Z shift (mm): 0.---
  4215. ```
  4216. */
  4217. case 76:
  4218. {
  4219. #ifdef PINDA_THERMISTOR
  4220. if (!has_temperature_compensation())
  4221. {
  4222. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4223. break;
  4224. }
  4225. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4226. //we need to know accurate position of first calibration point
  4227. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4228. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4229. break;
  4230. }
  4231. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4232. {
  4233. // We don't know where we are! HOME!
  4234. // Push the commands to the front of the message queue in the reverse order!
  4235. // There shall be always enough space reserved for these commands.
  4236. repeatcommand_front(); // repeat G76 with all its parameters
  4237. enquecommand_front_P(G28W0);
  4238. break;
  4239. }
  4240. lcd_show_fullscreen_message_and_wait_P(_i("Stable ambient temperature 21-26C is needed a rigid stand is required."));////MSG_TEMP_CAL_WARNING c=20 r=4
  4241. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  4242. if (result == LCD_LEFT_BUTTON_CHOICE)
  4243. {
  4244. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4245. plan_buffer_line_curposXYZE(3000 / 60);
  4246. current_position[Z_AXIS] = 50;
  4247. current_position[Y_AXIS] = 180;
  4248. plan_buffer_line_curposXYZE(3000 / 60);
  4249. st_synchronize();
  4250. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4251. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4252. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4253. plan_buffer_line_curposXYZE(3000 / 60);
  4254. st_synchronize();
  4255. gcode_G28(false, false, true);
  4256. }
  4257. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4258. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4259. current_position[Z_AXIS] = 100;
  4260. plan_buffer_line_curposXYZE(3000 / 60);
  4261. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4262. lcd_temp_cal_show_result(false);
  4263. break;
  4264. }
  4265. }
  4266. st_synchronize();
  4267. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4268. lcd_update_enable(true);
  4269. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4270. float zero_z;
  4271. int z_shift = 0; //unit: steps
  4272. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4273. if (start_temp < 35) start_temp = 35;
  4274. if (start_temp < current_temperature_pinda) start_temp += 5;
  4275. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4276. // setTargetHotend(200, 0);
  4277. setTargetBed(70 + (start_temp - 30));
  4278. custom_message_type = CustomMsg::TempCal;
  4279. custom_message_state = 1;
  4280. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4281. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4282. plan_buffer_line_curposXYZE(3000 / 60);
  4283. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4284. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4285. plan_buffer_line_curposXYZE(3000 / 60);
  4286. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4287. plan_buffer_line_curposXYZE(3000 / 60);
  4288. st_synchronize();
  4289. while (current_temperature_pinda < start_temp)
  4290. {
  4291. delay_keep_alive(1000);
  4292. serialecho_temperatures();
  4293. }
  4294. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4295. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4296. plan_buffer_line_curposXYZE(3000 / 60);
  4297. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4298. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4299. plan_buffer_line_curposXYZE(3000 / 60);
  4300. st_synchronize();
  4301. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4302. if (find_z_result == false) {
  4303. lcd_temp_cal_show_result(find_z_result);
  4304. homing_flag = false;
  4305. break;
  4306. }
  4307. zero_z = current_position[Z_AXIS];
  4308. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4309. int i = -1; for (; i < 5; i++)
  4310. {
  4311. float temp = (40 + i * 5);
  4312. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4313. if (i >= 0) {
  4314. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4315. }
  4316. if (start_temp <= temp) break;
  4317. }
  4318. for (i++; i < 5; i++)
  4319. {
  4320. float temp = (40 + i * 5);
  4321. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4322. custom_message_state = i + 2;
  4323. setTargetBed(50 + 10 * (temp - 30) / 5);
  4324. // setTargetHotend(255, 0);
  4325. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4326. plan_buffer_line_curposXYZE(3000 / 60);
  4327. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4328. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4329. plan_buffer_line_curposXYZE(3000 / 60);
  4330. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4331. plan_buffer_line_curposXYZE(3000 / 60);
  4332. st_synchronize();
  4333. while (current_temperature_pinda < temp)
  4334. {
  4335. delay_keep_alive(1000);
  4336. serialecho_temperatures();
  4337. }
  4338. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4339. plan_buffer_line_curposXYZE(3000 / 60);
  4340. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4341. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4342. plan_buffer_line_curposXYZE(3000 / 60);
  4343. st_synchronize();
  4344. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4345. if (find_z_result == false) {
  4346. lcd_temp_cal_show_result(find_z_result);
  4347. break;
  4348. }
  4349. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4350. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4351. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4352. }
  4353. lcd_temp_cal_show_result(true);
  4354. homing_flag = false;
  4355. #else //PINDA_THERMISTOR
  4356. setTargetBed(PINDA_MIN_T);
  4357. float zero_z;
  4358. int z_shift = 0; //unit: steps
  4359. int t_c; // temperature
  4360. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4361. // We don't know where we are! HOME!
  4362. // Push the commands to the front of the message queue in the reverse order!
  4363. // There shall be always enough space reserved for these commands.
  4364. repeatcommand_front(); // repeat G76 with all its parameters
  4365. enquecommand_front_P(G28W0);
  4366. break;
  4367. }
  4368. puts_P(_N("PINDA probe calibration start"));
  4369. custom_message_type = CustomMsg::TempCal;
  4370. custom_message_state = 1;
  4371. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4372. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4373. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4374. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4375. plan_buffer_line_curposXYZE(3000 / 60);
  4376. st_synchronize();
  4377. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4378. delay_keep_alive(1000);
  4379. serialecho_temperatures();
  4380. }
  4381. //enquecommand_P(PSTR("M190 S50"));
  4382. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4383. delay_keep_alive(1000);
  4384. serialecho_temperatures();
  4385. }
  4386. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4387. current_position[Z_AXIS] = 5;
  4388. plan_buffer_line_curposXYZE(3000 / 60);
  4389. current_position[X_AXIS] = BED_X0;
  4390. current_position[Y_AXIS] = BED_Y0;
  4391. plan_buffer_line_curposXYZE(3000 / 60);
  4392. st_synchronize();
  4393. find_bed_induction_sensor_point_z(-1.f);
  4394. zero_z = current_position[Z_AXIS];
  4395. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4396. for (int i = 0; i<5; i++) {
  4397. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4398. custom_message_state = i + 2;
  4399. t_c = 60 + i * 10;
  4400. setTargetBed(t_c);
  4401. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4402. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4403. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4404. plan_buffer_line_curposXYZE(3000 / 60);
  4405. st_synchronize();
  4406. while (degBed() < t_c) {
  4407. delay_keep_alive(1000);
  4408. serialecho_temperatures();
  4409. }
  4410. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4411. delay_keep_alive(1000);
  4412. serialecho_temperatures();
  4413. }
  4414. current_position[Z_AXIS] = 5;
  4415. plan_buffer_line_curposXYZE(3000 / 60);
  4416. current_position[X_AXIS] = BED_X0;
  4417. current_position[Y_AXIS] = BED_Y0;
  4418. plan_buffer_line_curposXYZE(3000 / 60);
  4419. st_synchronize();
  4420. find_bed_induction_sensor_point_z(-1.f);
  4421. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4422. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4423. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4424. }
  4425. custom_message_type = CustomMsg::Status;
  4426. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4427. puts_P(_N("Temperature calibration done."));
  4428. disable_x();
  4429. disable_y();
  4430. disable_z();
  4431. disable_e0();
  4432. disable_e1();
  4433. disable_e2();
  4434. setTargetBed(0); //set bed target temperature back to 0
  4435. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4436. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4437. lcd_update_enable(true);
  4438. lcd_update(2);
  4439. #endif //PINDA_THERMISTOR
  4440. }
  4441. break;
  4442. /*!
  4443. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4444. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4445. #### Usage
  4446. G80 [ N | R | V | L | R | F | B ]
  4447. #### Parameters
  4448. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4449. - `R` - Probe retries. Default 3 max. 10
  4450. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4451. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4452. #### Additional Parameters
  4453. - `L` - Left Bed Level correct value in um.
  4454. - `R` - Right Bed Level correct value in um.
  4455. - `F` - Front Bed Level correct value in um.
  4456. - `B` - Back Bed Level correct value in um.
  4457. */
  4458. /*
  4459. * Probes a grid and produces a mesh to compensate for variable bed height
  4460. * The S0 report the points as below
  4461. * +----> X-axis
  4462. * |
  4463. * |
  4464. * v Y-axis
  4465. */
  4466. case 80: {
  4467. gcode_G80();
  4468. }
  4469. break;
  4470. /*!
  4471. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4472. Prints mesh bed leveling status and bed profile if activated.
  4473. */
  4474. case 81:
  4475. if (mbl.active) {
  4476. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4477. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4478. SERIAL_PROTOCOL(',');
  4479. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4480. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4481. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4482. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4483. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4484. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4485. SERIAL_PROTOCOLPGM(" ");
  4486. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4487. }
  4488. SERIAL_PROTOCOLLN();
  4489. }
  4490. }
  4491. else
  4492. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4493. break;
  4494. #if 0
  4495. /*!
  4496. ### G82: Single Z probe at current location - Not active <a href="https://reprap.org/wiki/G-code#G82:_Single_Z_probe_at_current_location">G82: Single Z probe at current location</a>
  4497. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4498. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4499. */
  4500. case 82:
  4501. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4502. int l_feedmultiply = setup_for_endstop_move();
  4503. find_bed_induction_sensor_point_z();
  4504. clean_up_after_endstop_move(l_feedmultiply);
  4505. SERIAL_PROTOCOLPGM("Bed found at: ");
  4506. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4507. SERIAL_PROTOCOLPGM("\n");
  4508. break;
  4509. /*!
  4510. ### G83: Babystep in Z and store to EEPROM - Not active <a href="https://reprap.org/wiki/G-code#G83:_Babystep_in_Z_and_store_to_EEPROM">G83: Babystep in Z and store to EEPROM</a>
  4511. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4512. */
  4513. case 83:
  4514. {
  4515. int babystepz = code_seen('S') ? code_value() : 0;
  4516. int BabyPosition = code_seen('P') ? code_value() : 0;
  4517. if (babystepz != 0) {
  4518. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4519. // Is the axis indexed starting with zero or one?
  4520. if (BabyPosition > 4) {
  4521. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4522. }else{
  4523. // Save it to the eeprom
  4524. babystepLoadZ = babystepz;
  4525. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4526. // adjust the Z
  4527. babystepsTodoZadd(babystepLoadZ);
  4528. }
  4529. }
  4530. }
  4531. break;
  4532. /*!
  4533. ### G84: UNDO Babystep Z (move Z axis back) - Not active <a href="https://reprap.org/wiki/G-code#G84:_UNDO_Babystep_Z_.28move_Z_axis_back.29">G84: UNDO Babystep Z (move Z axis back)</a>
  4534. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4535. */
  4536. case 84:
  4537. babystepsTodoZsubtract(babystepLoadZ);
  4538. // babystepLoadZ = 0;
  4539. break;
  4540. /*!
  4541. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4542. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4543. */
  4544. case 85:
  4545. lcd_pick_babystep();
  4546. break;
  4547. #endif
  4548. /*!
  4549. ### G86 - Disable babystep correction after home <a href="https://reprap.org/wiki/G-code#G86:_Disable_babystep_correction_after_home">G86: Disable babystep correction after home</a>
  4550. This G-code will be performed at the start of a calibration script.
  4551. (Prusa3D specific)
  4552. */
  4553. case 86:
  4554. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4555. break;
  4556. /*!
  4557. ### G87 - Enable babystep correction after home <a href="https://reprap.org/wiki/G-code#G87:_Enable_babystep_correction_after_home">G87: Enable babystep correction after home</a>
  4558. This G-code will be performed at the end of a calibration script.
  4559. (Prusa3D specific)
  4560. */
  4561. case 87:
  4562. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4563. break;
  4564. /*!
  4565. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4566. Currently has no effect.
  4567. */
  4568. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4569. case 88:
  4570. break;
  4571. #endif // ENABLE_MESH_BED_LEVELING
  4572. /*!
  4573. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4574. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4575. */
  4576. case 90: {
  4577. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4578. }
  4579. break;
  4580. /*!
  4581. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4582. All coordinates from now on are relative to the last position. E axis is left intact.
  4583. */
  4584. case 91: {
  4585. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4586. }
  4587. break;
  4588. /*!
  4589. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4590. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4591. If a parameter is omitted, that axis will not be affected.
  4592. If `X`, `Y`, or `Z` axis are specified, the move afterwards might stutter because of Mesh Bed Leveling. `E` axis is not affected if the target position is 0 (`G92 E0`).
  4593. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4594. #### Usage
  4595. G92 [ X | Y | Z | E ]
  4596. #### Parameters
  4597. - `X` - new X axis position
  4598. - `Y` - new Y axis position
  4599. - `Z` - new Z axis position
  4600. - `E` - new extruder position
  4601. */
  4602. case 92: {
  4603. gcode_G92();
  4604. }
  4605. break;
  4606. #ifdef PRUSA_FARM
  4607. /*!
  4608. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4609. Enable Prusa-specific Farm functions and g-code.
  4610. See Internal Prusa commands.
  4611. */
  4612. case 98:
  4613. farm_gcode_g98();
  4614. break;
  4615. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4616. Disables Prusa-specific Farm functions and g-code.
  4617. */
  4618. case 99:
  4619. farm_gcode_g99();
  4620. break;
  4621. #endif //PRUSA_FARM
  4622. default:
  4623. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4624. }
  4625. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4626. gcode_in_progress = 0;
  4627. } // end if(code_seen('G'))
  4628. /*!
  4629. ### End of G-Codes
  4630. */
  4631. /*!
  4632. ---------------------------------------------------------------------------------
  4633. # M Commands
  4634. */
  4635. else if(code_seen('M'))
  4636. {
  4637. int index;
  4638. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4639. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4640. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4641. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4642. } else
  4643. {
  4644. mcode_in_progress = code_value_short();
  4645. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4646. switch(mcode_in_progress)
  4647. {
  4648. /*!
  4649. ### M17 - Enable all axes <a href="https://reprap.org/wiki/G-code#M17:_Enable.2FPower_all_stepper_motors">M17: Enable/Power all stepper motors</a>
  4650. */
  4651. case 17:
  4652. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4653. enable_x();
  4654. enable_y();
  4655. enable_z();
  4656. enable_e0();
  4657. enable_e1();
  4658. enable_e2();
  4659. break;
  4660. #ifdef SDSUPPORT
  4661. /*!
  4662. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4663. #### Usage
  4664. M20 [ L | T ]
  4665. #### Parameters
  4666. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4667. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4668. */
  4669. case 20:
  4670. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4671. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4672. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4673. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4674. break;
  4675. /*!
  4676. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4677. */
  4678. case 21:
  4679. card.initsd();
  4680. break;
  4681. /*!
  4682. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4683. */
  4684. case 22:
  4685. card.release();
  4686. break;
  4687. /*!
  4688. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4689. #### Usage
  4690. M23 [filename]
  4691. */
  4692. case 23:
  4693. starpos = (strchr(strchr_pointer + 4,'*'));
  4694. if(starpos!=NULL)
  4695. *(starpos)='\0';
  4696. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4697. break;
  4698. /*!
  4699. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4700. */
  4701. case 24:
  4702. if (isPrintPaused)
  4703. lcd_resume_print();
  4704. else
  4705. {
  4706. if (!card.get_sdpos())
  4707. {
  4708. // A new print has started from scratch, reset stats
  4709. failstats_reset_print();
  4710. sdpos_atomic = 0;
  4711. #ifndef LA_NOCOMPAT
  4712. la10c_reset();
  4713. #endif
  4714. }
  4715. card.startFileprint();
  4716. starttime=_millis();
  4717. if (MMU2::mmu2.Enabled())
  4718. {
  4719. if (MMU2::mmu2.FindaDetectsFilament() && !fsensor.getFilamentPresent())
  4720. { // Filament only half way into the PTFE. Unload the filament.
  4721. MMU2::mmu2.unload();
  4722. // Tx and Tc gcodes take care of loading the filament to the nozzle.
  4723. }
  4724. }
  4725. }
  4726. break;
  4727. /*!
  4728. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4729. Set position in SD card file to index in bytes.
  4730. This command is expected to be called after M23 and before M24.
  4731. Otherwise effect of this command is undefined.
  4732. #### Usage
  4733. M26 [ S ]
  4734. #### Parameters
  4735. - `S` - Index in bytes
  4736. */
  4737. case 26:
  4738. if(card.cardOK && code_seen('S')) {
  4739. long index = code_value_long();
  4740. card.setIndex(index);
  4741. // We don't disable interrupt during update of sdpos_atomic
  4742. // as we expect, that SD card print is not active in this moment
  4743. sdpos_atomic = index;
  4744. }
  4745. break;
  4746. /*!
  4747. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4748. #### Usage
  4749. M27 [ P ]
  4750. #### Parameters
  4751. - `P` - Show full SFN path instead of LFN only.
  4752. */
  4753. case 27:
  4754. card.getStatus(code_seen('P'));
  4755. break;
  4756. /*!
  4757. ### M28 - Start SD write <a href="https://reprap.org/wiki/G-code#M28:_Begin_write_to_SD_card">M28: Begin write to SD card</a>
  4758. */
  4759. case 28:
  4760. starpos = (strchr(strchr_pointer + 4,'*'));
  4761. if(starpos != NULL){
  4762. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4763. strchr_pointer = strchr(npos,' ') + 1;
  4764. *(starpos) = '\0';
  4765. }
  4766. card.openFileWrite(strchr_pointer+4);
  4767. break;
  4768. /*! ### M29 - Stop SD write <a href="https://reprap.org/wiki/G-code#M29:_Stop_writing_to_SD_card">M29: Stop writing to SD card</a>
  4769. Stops writing to the SD file signaling the end of the uploaded file. It is processed very early and it's not written to the card.
  4770. */
  4771. case 29:
  4772. //processed in write to file routine above
  4773. //card,saving = false;
  4774. break;
  4775. /*!
  4776. ### M30 - Delete file <a href="https://reprap.org/wiki/G-code#M30:_Delete_a_file_on_the_SD_card">M30: Delete a file on the SD card</a>
  4777. #### Usage
  4778. M30 [filename]
  4779. */
  4780. case 30:
  4781. if (card.cardOK){
  4782. card.closefile();
  4783. starpos = (strchr(strchr_pointer + 4,'*'));
  4784. if(starpos != NULL){
  4785. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4786. strchr_pointer = strchr(npos,' ') + 1;
  4787. *(starpos) = '\0';
  4788. }
  4789. card.removeFile(strchr_pointer + 4);
  4790. }
  4791. break;
  4792. /*!
  4793. ### M32 - Select file and start SD print <a href="https://reprap.org/wiki/G-code#M32:_Select_file_and_start_SD_print">M32: Select file and start SD print</a>
  4794. @todo What are the parameters P and S for in M32?
  4795. */
  4796. case 32:
  4797. {
  4798. if(card.sdprinting) {
  4799. st_synchronize();
  4800. }
  4801. starpos = (strchr(strchr_pointer + 4,'*'));
  4802. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4803. if(namestartpos==NULL)
  4804. {
  4805. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4806. }
  4807. else
  4808. namestartpos++; //to skip the '!'
  4809. if(starpos!=NULL)
  4810. *(starpos)='\0';
  4811. bool call_procedure=(code_seen('P'));
  4812. if(strchr_pointer>namestartpos)
  4813. call_procedure=false; //false alert, 'P' found within filename
  4814. if( card.cardOK )
  4815. {
  4816. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4817. if(code_seen('S'))
  4818. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4819. card.setIndex(code_value_long());
  4820. card.startFileprint();
  4821. if(!call_procedure)
  4822. {
  4823. if(!card.get_sdpos())
  4824. {
  4825. // A new print has started from scratch, reset stats
  4826. failstats_reset_print();
  4827. sdpos_atomic = 0;
  4828. #ifndef LA_NOCOMPAT
  4829. la10c_reset();
  4830. #endif
  4831. }
  4832. starttime=_millis(); // procedure calls count as normal print time.
  4833. }
  4834. }
  4835. } break;
  4836. /*!
  4837. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4838. #### Usage
  4839. M928 [filename]
  4840. */
  4841. case 928:
  4842. starpos = (strchr(strchr_pointer + 5,'*'));
  4843. if(starpos != NULL){
  4844. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4845. strchr_pointer = strchr(npos,' ') + 1;
  4846. *(starpos) = '\0';
  4847. }
  4848. card.openLogFile(strchr_pointer+5);
  4849. break;
  4850. #endif //SDSUPPORT
  4851. /*!
  4852. ### M31 - Report current print time <a href="https://reprap.org/wiki/G-code#M31:_Output_time_since_last_M109_or_SD_card_start_to_serial">M31: Output time since last M109 or SD card start to serial</a>
  4853. */
  4854. case 31: //M31 take time since the start of the SD print or an M109 command
  4855. {
  4856. stoptime=_millis();
  4857. char time[30];
  4858. unsigned long t=(stoptime-starttime)/1000;
  4859. int sec,min;
  4860. min=t/60;
  4861. sec=t%60;
  4862. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4863. SERIAL_ECHO_START;
  4864. SERIAL_ECHOLN(time);
  4865. lcd_setstatus(time);
  4866. autotempShutdown();
  4867. }
  4868. break;
  4869. /*!
  4870. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4871. #### Usage
  4872. M42 [ P | S ]
  4873. #### Parameters
  4874. - `P` - Pin number.
  4875. - `S` - Pin value. If the pin is analog, values are from 0 to 255. If the pin is digital, values are from 0 to 1.
  4876. */
  4877. case 42:
  4878. if (code_seen('S'))
  4879. {
  4880. uint8_t pin_status = code_value_uint8();
  4881. int8_t pin_number = LED_PIN;
  4882. if (code_seen('P'))
  4883. pin_number = code_value_uint8();
  4884. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4885. {
  4886. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4887. {
  4888. pin_number = -1;
  4889. break;
  4890. }
  4891. }
  4892. #if defined(FAN_PIN) && FAN_PIN > -1
  4893. if (pin_number == FAN_PIN)
  4894. fanSpeed = pin_status;
  4895. #endif
  4896. if (pin_number > -1)
  4897. {
  4898. pinMode(pin_number, OUTPUT);
  4899. digitalWrite(pin_number, pin_status);
  4900. analogWrite(pin_number, pin_status);
  4901. }
  4902. }
  4903. break;
  4904. /*!
  4905. ### M44 - Reset the bed skew and offset calibration <a href="https://reprap.org/wiki/G-code#M44:_Reset_the_bed_skew_and_offset_calibration">M44: Reset the bed skew and offset calibration</a>
  4906. */
  4907. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4908. // Reset the baby step value and the baby step applied flag.
  4909. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4910. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4911. // Reset the skew and offset in both RAM and EEPROM.
  4912. reset_bed_offset_and_skew();
  4913. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4914. // the planner will not perform any adjustments in the XY plane.
  4915. // Wait for the motors to stop and update the current position with the absolute values.
  4916. world2machine_revert_to_uncorrected();
  4917. break;
  4918. /*!
  4919. ### M45 - Bed skew and offset with manual Z up <a href="https://reprap.org/wiki/G-code#M45:_Bed_skew_and_offset_with_manual_Z_up">M45: Bed skew and offset with manual Z up</a>
  4920. #### Usage
  4921. M45 [ V ]
  4922. #### Parameters
  4923. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4924. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4925. */
  4926. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4927. {
  4928. int8_t verbosity_level = 0;
  4929. bool only_Z = code_seen('Z');
  4930. #ifdef SUPPORT_VERBOSITY
  4931. if (code_seen('V'))
  4932. {
  4933. // Just 'V' without a number counts as V1.
  4934. char c = strchr_pointer[1];
  4935. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4936. }
  4937. #endif //SUPPORT_VERBOSITY
  4938. gcode_M45(only_Z, verbosity_level);
  4939. }
  4940. break;
  4941. /*!
  4942. ### M46 - Show the assigned IP address <a href="https://reprap.org/wiki/G-code#M46:_Show_the_assigned_IP_address">M46: Show the assigned IP address.</a>
  4943. */
  4944. case 46:
  4945. {
  4946. // M46: Prusa3D: Show the assigned IP address.
  4947. if (card.ToshibaFlashAir_isEnabled()) {
  4948. uint8_t ip[4];
  4949. if (card.ToshibaFlashAir_GetIP(ip)) {
  4950. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  4951. SERIAL_PROTOCOL(uint8_t(ip[0]));
  4952. SERIAL_PROTOCOL('.');
  4953. SERIAL_PROTOCOL(uint8_t(ip[1]));
  4954. SERIAL_PROTOCOL('.');
  4955. SERIAL_PROTOCOL(uint8_t(ip[2]));
  4956. SERIAL_PROTOCOL('.');
  4957. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  4958. } else {
  4959. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  4960. }
  4961. } else {
  4962. SERIAL_PROTOCOLLNPGM("n/a");
  4963. }
  4964. break;
  4965. }
  4966. /*!
  4967. ### M47 - Show end stops dialog on the display <a href="https://reprap.org/wiki/G-code#M47:_Show_end_stops_dialog_on_the_display">M47: Show end stops dialog on the display</a>
  4968. */
  4969. case 47:
  4970. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4971. lcd_diag_show_end_stops();
  4972. KEEPALIVE_STATE(IN_HANDLER);
  4973. break;
  4974. #if 0
  4975. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4976. {
  4977. // Disable the default update procedure of the display. We will do a modal dialog.
  4978. lcd_update_enable(false);
  4979. // Let the planner use the uncorrected coordinates.
  4980. mbl.reset();
  4981. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4982. // the planner will not perform any adjustments in the XY plane.
  4983. // Wait for the motors to stop and update the current position with the absolute values.
  4984. world2machine_revert_to_uncorrected();
  4985. // Move the print head close to the bed.
  4986. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4987. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  4988. st_synchronize();
  4989. // Home in the XY plane.
  4990. set_destination_to_current();
  4991. int l_feedmultiply = setup_for_endstop_move();
  4992. home_xy();
  4993. int8_t verbosity_level = 0;
  4994. if (code_seen('V')) {
  4995. // Just 'V' without a number counts as V1.
  4996. char c = strchr_pointer[1];
  4997. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4998. }
  4999. bool success = scan_bed_induction_points(verbosity_level);
  5000. clean_up_after_endstop_move(l_feedmultiply);
  5001. // Print head up.
  5002. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5003. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  5004. st_synchronize();
  5005. lcd_update_enable(true);
  5006. break;
  5007. }
  5008. #endif
  5009. #ifdef ENABLE_AUTO_BED_LEVELING
  5010. #ifdef Z_PROBE_REPEATABILITY_TEST
  5011. /*!
  5012. ### M48 - Z-Probe repeatability measurement function <a href="https://reprap.org/wiki/G-code#M48:_Measure_Z-Probe_repeatability">M48: Measure Z-Probe repeatability</a>
  5013. This function assumes the bed has been homed. Specifically, that a G28 command as been issued prior to invoking the M48 Z-Probe repeatability measurement function. Any information generated by a prior G29 Bed leveling command will be lost and needs to be regenerated.
  5014. The number of samples will default to 10 if not specified. You can use upper or lower case letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital N for its communication protocol and will get horribly confused if you send it a capital N.
  5015. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5016. #### Usage
  5017. M48 [ n | X | Y | V | L ]
  5018. #### Parameters
  5019. - `n` - Number of samples. Valid values 4-50
  5020. - `X` - X position for samples
  5021. - `Y` - Y position for samples
  5022. - `V` - Verbose level. Valid values 1-4
  5023. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5024. */
  5025. case 48: // M48 Z-Probe repeatability
  5026. {
  5027. #if Z_MIN_PIN == -1
  5028. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5029. #endif
  5030. double sum=0.0;
  5031. double mean=0.0;
  5032. double sigma=0.0;
  5033. double sample_set[50];
  5034. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5035. double X_current, Y_current, Z_current;
  5036. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5037. if (code_seen('V') || code_seen('v')) {
  5038. verbose_level = code_value();
  5039. if (verbose_level<0 || verbose_level>4 ) {
  5040. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5041. goto Sigma_Exit;
  5042. }
  5043. }
  5044. if (verbose_level > 0) {
  5045. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5046. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5047. }
  5048. if (code_seen('n')) {
  5049. n_samples = code_value();
  5050. if (n_samples<4 || n_samples>50 ) {
  5051. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5052. goto Sigma_Exit;
  5053. }
  5054. }
  5055. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5056. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5057. Z_current = st_get_position_mm(Z_AXIS);
  5058. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5059. ext_position = st_get_position_mm(E_AXIS);
  5060. if (code_seen('X') || code_seen('x') ) {
  5061. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5062. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5063. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5064. goto Sigma_Exit;
  5065. }
  5066. }
  5067. if (code_seen('Y') || code_seen('y') ) {
  5068. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5069. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5070. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5071. goto Sigma_Exit;
  5072. }
  5073. }
  5074. if (code_seen('L') || code_seen('l') ) {
  5075. n_legs = code_value();
  5076. if ( n_legs==1 )
  5077. n_legs = 2;
  5078. if ( n_legs<0 || n_legs>15 ) {
  5079. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5080. goto Sigma_Exit;
  5081. }
  5082. }
  5083. //
  5084. // Do all the preliminary setup work. First raise the probe.
  5085. //
  5086. st_synchronize();
  5087. plan_bed_level_matrix.set_to_identity();
  5088. plan_buffer_line( X_current, Y_current, Z_start_location,
  5089. ext_position,
  5090. homing_feedrate[Z_AXIS]/60,
  5091. active_extruder);
  5092. st_synchronize();
  5093. //
  5094. // Now get everything to the specified probe point So we can safely do a probe to
  5095. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5096. // use that as a starting point for each probe.
  5097. //
  5098. if (verbose_level > 2)
  5099. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5100. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5101. ext_position,
  5102. homing_feedrate[X_AXIS]/60,
  5103. active_extruder);
  5104. st_synchronize();
  5105. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5106. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5107. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5108. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5109. //
  5110. // OK, do the inital probe to get us close to the bed.
  5111. // Then retrace the right amount and use that in subsequent probes
  5112. //
  5113. int l_feedmultiply = setup_for_endstop_move();
  5114. run_z_probe();
  5115. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5116. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5117. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5118. ext_position,
  5119. homing_feedrate[X_AXIS]/60,
  5120. active_extruder);
  5121. st_synchronize();
  5122. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5123. for( n=0; n<n_samples; n++) {
  5124. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5125. if ( n_legs) {
  5126. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5127. int rotational_direction, l;
  5128. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5129. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5130. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5131. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5132. //SERIAL_ECHOPAIR(" theta: ",theta);
  5133. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5134. //SERIAL_PROTOCOLLNPGM("");
  5135. for( l=0; l<n_legs-1; l++) {
  5136. if (rotational_direction==1)
  5137. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5138. else
  5139. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5140. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5141. if ( radius<0.0 )
  5142. radius = -radius;
  5143. X_current = X_probe_location + cos(theta) * radius;
  5144. Y_current = Y_probe_location + sin(theta) * radius;
  5145. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5146. X_current = X_MIN_POS;
  5147. if ( X_current>X_MAX_POS)
  5148. X_current = X_MAX_POS;
  5149. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5150. Y_current = Y_MIN_POS;
  5151. if ( Y_current>Y_MAX_POS)
  5152. Y_current = Y_MAX_POS;
  5153. if (verbose_level>3 ) {
  5154. SERIAL_ECHOPAIR("x: ", X_current);
  5155. SERIAL_ECHOPAIR("y: ", Y_current);
  5156. SERIAL_PROTOCOLLNPGM("");
  5157. }
  5158. do_blocking_move_to( X_current, Y_current, Z_current );
  5159. }
  5160. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5161. }
  5162. int l_feedmultiply = setup_for_endstop_move();
  5163. run_z_probe();
  5164. sample_set[n] = current_position[Z_AXIS];
  5165. //
  5166. // Get the current mean for the data points we have so far
  5167. //
  5168. sum=0.0;
  5169. for( j=0; j<=n; j++) {
  5170. sum = sum + sample_set[j];
  5171. }
  5172. mean = sum / (double (n+1));
  5173. //
  5174. // Now, use that mean to calculate the standard deviation for the
  5175. // data points we have so far
  5176. //
  5177. sum=0.0;
  5178. for( j=0; j<=n; j++) {
  5179. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5180. }
  5181. sigma = sqrt( sum / (double (n+1)) );
  5182. if (verbose_level > 1) {
  5183. SERIAL_PROTOCOL(n+1);
  5184. SERIAL_PROTOCOL(" of ");
  5185. SERIAL_PROTOCOL(n_samples);
  5186. SERIAL_PROTOCOLPGM(" z: ");
  5187. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5188. }
  5189. if (verbose_level > 2) {
  5190. SERIAL_PROTOCOL(" mean: ");
  5191. SERIAL_PROTOCOL_F(mean,6);
  5192. SERIAL_PROTOCOL(" sigma: ");
  5193. SERIAL_PROTOCOL_F(sigma,6);
  5194. }
  5195. if (verbose_level > 0)
  5196. SERIAL_PROTOCOLPGM("\n");
  5197. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5198. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5199. st_synchronize();
  5200. }
  5201. _delay(1000);
  5202. clean_up_after_endstop_move(l_feedmultiply);
  5203. // enable_endstops(true);
  5204. if (verbose_level > 0) {
  5205. SERIAL_PROTOCOLPGM("Mean: ");
  5206. SERIAL_PROTOCOL_F(mean, 6);
  5207. SERIAL_PROTOCOLPGM("\n");
  5208. }
  5209. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5210. SERIAL_PROTOCOL_F(sigma, 6);
  5211. SERIAL_PROTOCOLPGM("\n\n");
  5212. Sigma_Exit:
  5213. break;
  5214. }
  5215. #endif // Z_PROBE_REPEATABILITY_TEST
  5216. #endif // ENABLE_AUTO_BED_LEVELING
  5217. /*!
  5218. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5219. #### Usage
  5220. M73 [ P | R | Q | S | C | D ]
  5221. #### Parameters
  5222. - `P` - Percent in normal mode
  5223. - `R` - Time remaining in normal mode
  5224. - `Q` - Percent in silent mode
  5225. - `S` - Time in silent mode
  5226. - `C` - Time to change/pause/user interaction in normal mode
  5227. - `D` - Time to change/pause/user interaction in silent mode
  5228. */
  5229. case 73: //M73 show percent done, time remaining and time to change/pause
  5230. {
  5231. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5232. if(code_seen('R')) print_time_remaining_normal = code_value();
  5233. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5234. if(code_seen('S')) print_time_remaining_silent = code_value();
  5235. if(code_seen('C')){
  5236. float print_time_to_change_normal_f = code_value_float();
  5237. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5238. }
  5239. if(code_seen('D')){
  5240. float print_time_to_change_silent_f = code_value_float();
  5241. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5242. }
  5243. {
  5244. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5245. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5246. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5247. }
  5248. break;
  5249. }
  5250. /*!
  5251. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5252. #### Usage
  5253. M104 [ S ]
  5254. #### Parameters
  5255. - `S` - Target temperature
  5256. */
  5257. case 104: // M104
  5258. {
  5259. uint8_t extruder;
  5260. if(setTargetedHotend(104,extruder)){
  5261. break;
  5262. }
  5263. if (code_seen('S'))
  5264. {
  5265. setTargetHotendSafe(code_value(), extruder);
  5266. }
  5267. break;
  5268. }
  5269. /*!
  5270. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5271. It is processed much earlier as to bypass the cmdqueue.
  5272. */
  5273. case 112:
  5274. kill(MSG_M112_KILL, 3);
  5275. break;
  5276. /*!
  5277. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5278. #### Usage
  5279. M140 [ S ]
  5280. #### Parameters
  5281. - `S` - Target temperature
  5282. */
  5283. case 140:
  5284. if (code_seen('S')) setTargetBed(code_value());
  5285. break;
  5286. /*!
  5287. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5288. Prints temperatures:
  5289. - `T:` - Hotend (actual / target)
  5290. - `B:` - Bed (actual / target)
  5291. - `Tx:` - x Tool (actual / target)
  5292. - `@:` - Hotend power
  5293. - `B@:` - Bed power
  5294. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5295. - `A:` - Ambient actual (only MK3/s)
  5296. _Example:_
  5297. ok T:20.2 /0.0 B:19.1 /0.0 T0:20.2 /0.0 @:0 B@:0 P:19.8 A:26.4
  5298. */
  5299. case 105:
  5300. {
  5301. uint8_t extruder;
  5302. if(setTargetedHotend(105, extruder)){
  5303. break;
  5304. }
  5305. SERIAL_PROTOCOLPGM("ok ");
  5306. gcode_M105(extruder);
  5307. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5308. cmdbuffer_front_already_processed = true;
  5309. break;
  5310. }
  5311. #if defined(AUTO_REPORT)
  5312. /*!
  5313. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5314. #### Usage
  5315. M155 [ S ] [ C ]
  5316. #### Parameters
  5317. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5318. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5319. bit 0 = Auto-report temperatures
  5320. bit 1 = Auto-report fans
  5321. bit 2 = Auto-report position
  5322. bit 3 = free
  5323. bit 4 = free
  5324. bit 5 = free
  5325. bit 6 = free
  5326. bit 7 = free
  5327. */
  5328. case 155:
  5329. {
  5330. if (code_seen('S')){
  5331. autoReportFeatures.SetPeriod( code_value_uint8() );
  5332. }
  5333. if (code_seen('C')){
  5334. autoReportFeatures.SetMask(code_value_uint8());
  5335. } else{
  5336. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5337. }
  5338. }
  5339. break;
  5340. #endif //AUTO_REPORT
  5341. /*!
  5342. ### M109 - Wait for extruder temperature <a href="https://reprap.org/wiki/G-code#M109:_Set_Extruder_Temperature_and_Wait">M109: Set Extruder Temperature and Wait</a>
  5343. #### Usage
  5344. M104 [ B | R | S ]
  5345. #### Parameters (not mandatory)
  5346. - `S` - Set extruder temperature
  5347. - `R` - Set extruder temperature
  5348. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5349. Parameters S and R are treated identically.
  5350. Command always waits for both cool down and heat up.
  5351. If no parameters are supplied waits for previously set extruder temperature.
  5352. */
  5353. case 109:
  5354. {
  5355. uint8_t extruder;
  5356. if(setTargetedHotend(109, extruder)){
  5357. break;
  5358. }
  5359. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5360. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5361. prusa_statistics(1);
  5362. #ifdef AUTOTEMP
  5363. autotemp_enabled=false;
  5364. #endif
  5365. if (code_seen('S')) {
  5366. setTargetHotendSafe(code_value(), extruder);
  5367. } else if (code_seen('R')) {
  5368. setTargetHotendSafe(code_value(), extruder);
  5369. }
  5370. #ifdef AUTOTEMP
  5371. if (code_seen('S')) autotemp_min=code_value();
  5372. if (code_seen('B')) autotemp_max=code_value();
  5373. if (code_seen('F'))
  5374. {
  5375. autotemp_factor=code_value();
  5376. autotemp_enabled=true;
  5377. }
  5378. #endif
  5379. codenum = _millis();
  5380. /* See if we are heating up or cooling down */
  5381. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5382. cancel_heatup = false;
  5383. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5384. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5385. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5386. prusa_statistics(2);
  5387. //starttime=_millis();
  5388. previous_millis_cmd.start();
  5389. }
  5390. break;
  5391. /*!
  5392. ### M190 - Wait for bed temperature <a href="https://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp">M190: Wait for bed temperature to reach target temp</a>
  5393. #### Usage
  5394. M190 [ R | S ]
  5395. #### Parameters (not mandatory)
  5396. - `S` - Set extruder temperature and wait for heating
  5397. - `R` - Set extruder temperature and wait for heating or cooling
  5398. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5399. */
  5400. case 190:
  5401. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5402. {
  5403. bool CooldownNoWait = false;
  5404. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5405. heating_status = HeatingStatus::BED_HEATING;
  5406. prusa_statistics(1);
  5407. if (code_seen('S'))
  5408. {
  5409. setTargetBed(code_value());
  5410. CooldownNoWait = true;
  5411. }
  5412. else if (code_seen('R'))
  5413. {
  5414. setTargetBed(code_value());
  5415. }
  5416. codenum = _millis();
  5417. cancel_heatup = false;
  5418. target_direction = isHeatingBed(); // true if heating, false if cooling
  5419. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5420. {
  5421. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5422. {
  5423. if (!farm_mode) {
  5424. float tt = degHotend(active_extruder);
  5425. SERIAL_PROTOCOLPGM("T:");
  5426. SERIAL_PROTOCOL(tt);
  5427. SERIAL_PROTOCOLPGM(" E:");
  5428. SERIAL_PROTOCOL((int)active_extruder);
  5429. SERIAL_PROTOCOLPGM(" B:");
  5430. SERIAL_PROTOCOL_F(degBed(), 1);
  5431. SERIAL_PROTOCOLLN();
  5432. }
  5433. codenum = _millis();
  5434. }
  5435. manage_heater();
  5436. manage_inactivity();
  5437. lcd_update(0);
  5438. }
  5439. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5440. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5441. previous_millis_cmd.start();
  5442. }
  5443. #endif
  5444. break;
  5445. #if defined(FAN_PIN) && FAN_PIN > -1
  5446. /*!
  5447. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5448. #### Usage
  5449. M106 [ S ]
  5450. #### Parameters
  5451. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5452. */
  5453. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5454. if (code_seen('S')){
  5455. fanSpeed = code_value_uint8();
  5456. }
  5457. else {
  5458. fanSpeed = 255;
  5459. }
  5460. break;
  5461. /*!
  5462. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5463. */
  5464. case 107:
  5465. fanSpeed = 0;
  5466. break;
  5467. #endif //FAN_PIN
  5468. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5469. /*!
  5470. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5471. Only works if the firmware is compiled with PS_ON_PIN defined.
  5472. */
  5473. case 80:
  5474. SET_OUTPUT(PS_ON_PIN); //GND
  5475. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5476. // If you have a switch on suicide pin, this is useful
  5477. // if you want to start another print with suicide feature after
  5478. // a print without suicide...
  5479. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5480. SET_OUTPUT(SUICIDE_PIN);
  5481. WRITE(SUICIDE_PIN, HIGH);
  5482. #endif
  5483. powersupply = true;
  5484. LCD_MESSAGERPGM(MSG_WELCOME);
  5485. lcd_update(0);
  5486. break;
  5487. /*!
  5488. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5489. Only works if the firmware is compiled with PS_ON_PIN defined.
  5490. */
  5491. case 81:
  5492. disable_heater();
  5493. st_synchronize();
  5494. disable_e0();
  5495. disable_e1();
  5496. disable_e2();
  5497. finishAndDisableSteppers();
  5498. fanSpeed = 0;
  5499. _delay(1000); // Wait a little before to switch off
  5500. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5501. st_synchronize();
  5502. suicide();
  5503. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5504. SET_OUTPUT(PS_ON_PIN);
  5505. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5506. #endif
  5507. powersupply = false;
  5508. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5509. lcd_update(0);
  5510. break;
  5511. #endif
  5512. /*!
  5513. ### M82 - Set E axis to absolute mode <a href="https://reprap.org/wiki/G-code#M82:_Set_extruder_to_absolute_mode">M82: Set extruder to absolute mode</a>
  5514. Makes the extruder interpret extrusion as absolute positions.
  5515. */
  5516. case 82:
  5517. axis_relative_modes &= ~E_AXIS_MASK;
  5518. break;
  5519. /*!
  5520. ### M83 - Set E axis to relative mode <a href="https://reprap.org/wiki/G-code#M83:_Set_extruder_to_relative_mode">M83: Set extruder to relative mode</a>
  5521. Makes the extruder interpret extrusion values as relative positions.
  5522. */
  5523. case 83:
  5524. axis_relative_modes |= E_AXIS_MASK;
  5525. break;
  5526. /*!
  5527. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5528. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5529. This command can be used without any additional parameters. In that case all steppers are disabled.
  5530. The file completeness check uses this parameter to detect an incomplete file. It has to be present at the end of a file with no parameters.
  5531. M84 [ S | X | Y | Z | E ]
  5532. - `S` - Seconds
  5533. - `X` - X axis
  5534. - `Y` - Y axis
  5535. - `Z` - Z axis
  5536. - `E` - Extruder
  5537. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5538. Equal to M84 (compatibility)
  5539. */
  5540. case 18: //compatibility
  5541. case 84: // M84
  5542. if(code_seen('S')){
  5543. stepper_inactive_time = code_value() * 1000;
  5544. }
  5545. else
  5546. {
  5547. 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])));
  5548. if(all_axis)
  5549. {
  5550. st_synchronize();
  5551. disable_e0();
  5552. disable_e1();
  5553. disable_e2();
  5554. finishAndDisableSteppers();
  5555. }
  5556. else
  5557. {
  5558. st_synchronize();
  5559. if (code_seen('X')) disable_x();
  5560. if (code_seen('Y')) disable_y();
  5561. if (code_seen('Z')) disable_z();
  5562. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5563. if (code_seen('E')) {
  5564. disable_e0();
  5565. disable_e1();
  5566. disable_e2();
  5567. }
  5568. #endif
  5569. }
  5570. }
  5571. break;
  5572. /*!
  5573. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5574. #### Usage
  5575. M85 [ S ]
  5576. #### Parameters
  5577. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5578. */
  5579. case 85: // M85
  5580. if(code_seen('S')) {
  5581. max_inactive_time = code_value() * 1000;
  5582. }
  5583. break;
  5584. #ifdef SAFETYTIMER
  5585. /*!
  5586. ### M86 - Set safety timer expiration time <a href="https://reprap.org/wiki/G-code#M86:_Set_Safety_Timer_expiration_time">M86: Set Safety Timer expiration time</a>
  5587. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5588. #### Usage
  5589. M86 [ S ]
  5590. #### Parameters
  5591. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5592. */
  5593. case 86:
  5594. if (code_seen('S')) {
  5595. safetytimer_inactive_time = code_value() * 1000;
  5596. safetyTimer.start();
  5597. }
  5598. break;
  5599. #endif
  5600. /*!
  5601. ### M92 Set Axis steps-per-unit <a href="https://reprap.org/wiki/G-code#M92:_Set_axis_steps_per_unit">M92: Set axis_steps_per_unit</a>
  5602. Allows programming of steps per unit (usually mm) for motor drives. These values are reset to firmware defaults on power on, unless saved to EEPROM if available (M500 in Marlin)
  5603. #### Usage
  5604. M92 [ X | Y | Z | E ]
  5605. #### Parameters
  5606. - `X` - Steps per unit for the X drive
  5607. - `Y` - Steps per unit for the Y drive
  5608. - `Z` - Steps per unit for the Z drive
  5609. - `E` - Steps per unit for the extruder drive
  5610. */
  5611. case 92:
  5612. for(int8_t i=0; i < NUM_AXIS; i++)
  5613. {
  5614. if(code_seen(axis_codes[i]))
  5615. {
  5616. if(i == E_AXIS) { // E
  5617. float value = code_value();
  5618. if(value < 20.0) {
  5619. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5620. cs.max_jerk[E_AXIS] *= factor;
  5621. max_feedrate[i] *= factor;
  5622. axis_steps_per_sqr_second[i] *= factor;
  5623. }
  5624. cs.axis_steps_per_unit[i] = value;
  5625. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5626. fsensor.init();
  5627. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5628. }
  5629. else {
  5630. cs.axis_steps_per_unit[i] = code_value();
  5631. }
  5632. }
  5633. }
  5634. reset_acceleration_rates();
  5635. break;
  5636. /*!
  5637. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5638. Sets the line number in G-code
  5639. #### Usage
  5640. M110 [ N ]
  5641. #### Parameters
  5642. - `N` - Line number
  5643. */
  5644. case 110:
  5645. if (code_seen('N'))
  5646. gcode_LastN = code_value_long();
  5647. break;
  5648. /*!
  5649. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5650. During some lengthy processes, such as G29, Marlin may appear to the host to have “gone away.” The “host keepalive” feature will send messages to the host when Marlin is busy or waiting for user response so the host won’t try to reconnect (or disconnect).
  5651. #### Usage
  5652. M113 [ S ]
  5653. #### Parameters
  5654. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5655. */
  5656. case 113:
  5657. if (code_seen('S')) {
  5658. host_keepalive_interval = code_value_uint8();
  5659. // NOMORE(host_keepalive_interval, 60);
  5660. }
  5661. else {
  5662. SERIAL_ECHO_START;
  5663. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5664. SERIAL_PROTOCOLLN();
  5665. }
  5666. break;
  5667. /*!
  5668. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5669. Print the firmware info and capabilities
  5670. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5671. `M115 U` Checks the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware, it will pause the print for 30s and ask the user to upgrade the firmware.
  5672. _Examples:_
  5673. `M115` results:
  5674. `FIRMWARE_NAME:Prusa-Firmware 3.8.1 based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:1.0 MACHINE_TYPE:Prusa i3 MK3S EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000`
  5675. `M115 V` results:
  5676. `3.8.1`
  5677. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5678. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5679. #### Usage
  5680. M115 [ V | U ]
  5681. #### Parameters
  5682. - V - Report current installed firmware version
  5683. - U - Firmware version provided by G-code to be compared to current one.
  5684. */
  5685. case 115: // M115
  5686. if (code_seen('V')) {
  5687. // Report the Prusa version number.
  5688. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5689. } else if (code_seen('U')) {
  5690. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5691. // pause the print for 30s and ask the user to upgrade the firmware.
  5692. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5693. } else {
  5694. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5695. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5696. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5697. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5698. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5699. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5700. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5701. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5702. SERIAL_ECHOPGM(" UUID:");
  5703. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5704. #ifdef EXTENDED_CAPABILITIES_REPORT
  5705. extended_capabilities_report();
  5706. #endif //EXTENDED_CAPABILITIES_REPORT
  5707. }
  5708. break;
  5709. /*!
  5710. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5711. */
  5712. case 114:
  5713. gcode_M114();
  5714. break;
  5715. /*
  5716. M117 moved up to get the high priority
  5717. case 117: // M117 display message
  5718. starpos = (strchr(strchr_pointer + 5,'*'));
  5719. if(starpos!=NULL)
  5720. *(starpos)='\0';
  5721. lcd_setstatus(strchr_pointer + 5);
  5722. break;*/
  5723. #ifdef M120_M121_ENABLED
  5724. /*!
  5725. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5726. */
  5727. case 120:
  5728. enable_endstops(true) ;
  5729. break;
  5730. /*!
  5731. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5732. */
  5733. case 121:
  5734. enable_endstops(false) ;
  5735. break;
  5736. #endif //M120_M121_ENABLED
  5737. /*!
  5738. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5739. Returns the current state of the configured X, Y, Z endstops. Takes into account any 'inverted endstop' settings, so one can confirm that the machine is interpreting the endstops correctly.
  5740. */
  5741. case 119:
  5742. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5743. SERIAL_PROTOCOLLN();
  5744. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5745. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5746. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5747. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5748. }else{
  5749. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5750. }
  5751. SERIAL_PROTOCOLLN();
  5752. #endif
  5753. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5754. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5755. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5756. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5757. }else{
  5758. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5759. }
  5760. SERIAL_PROTOCOLLN();
  5761. #endif
  5762. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5763. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5764. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5765. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5766. }else{
  5767. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5768. }
  5769. SERIAL_PROTOCOLLN();
  5770. #endif
  5771. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5772. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5773. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5774. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5775. }else{
  5776. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5777. }
  5778. SERIAL_PROTOCOLLN();
  5779. #endif
  5780. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5781. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5782. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5783. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5784. }else{
  5785. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5786. }
  5787. SERIAL_PROTOCOLLN();
  5788. #endif
  5789. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5790. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5791. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5792. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5793. }else{
  5794. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5795. }
  5796. SERIAL_PROTOCOLLN();
  5797. #endif
  5798. break;
  5799. //!@todo update for all axes, use for loop
  5800. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5801. /*!
  5802. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5803. This command is used to report fan speeds and fan pwm values.
  5804. #### Usage
  5805. M123
  5806. - E0: - Hotend fan speed in RPM
  5807. - PRN1: - Part cooling fans speed in RPM
  5808. - E0@: - Hotend fan PWM value
  5809. - PRN1@: -Part cooling fan PWM value
  5810. _Example:_
  5811. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5812. */
  5813. case 123:
  5814. gcode_M123();
  5815. break;
  5816. #endif //FANCHECK and TACH_0 and TACH_1
  5817. #ifdef BLINKM
  5818. /*!
  5819. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5820. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5821. #### Usage
  5822. M150 [ R | U | B ]
  5823. #### Parameters
  5824. - `R` - Red color value
  5825. - `U` - Green color value. It is NOT `G`!
  5826. - `B` - Blue color value
  5827. */
  5828. case 150:
  5829. {
  5830. byte red;
  5831. byte grn;
  5832. byte blu;
  5833. if(code_seen('R')) red = code_value();
  5834. if(code_seen('U')) grn = code_value();
  5835. if(code_seen('B')) blu = code_value();
  5836. SendColors(red,grn,blu);
  5837. }
  5838. break;
  5839. #endif //BLINKM
  5840. /*!
  5841. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5842. #### Usage
  5843. M200 [ D | T ]
  5844. #### Parameters
  5845. - `D` - Diameter in mm
  5846. - `T` - Number of extruder (MMUs)
  5847. */
  5848. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5849. {
  5850. uint8_t extruder = active_extruder;
  5851. if(code_seen('T')) {
  5852. extruder = code_value_uint8();
  5853. if(extruder >= EXTRUDERS) {
  5854. SERIAL_ECHO_START;
  5855. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5856. break;
  5857. }
  5858. }
  5859. if(code_seen('D')) {
  5860. float diameter = code_value();
  5861. if (diameter == 0.0) {
  5862. // setting any extruder filament size disables volumetric on the assumption that
  5863. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5864. // for all extruders
  5865. cs.volumetric_enabled = false;
  5866. } else {
  5867. cs.filament_size[extruder] = code_value();
  5868. // make sure all extruders have some sane value for the filament size
  5869. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5870. #if EXTRUDERS > 1
  5871. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5872. #if EXTRUDERS > 2
  5873. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5874. #endif
  5875. #endif
  5876. cs.volumetric_enabled = true;
  5877. }
  5878. } else {
  5879. //reserved for setting filament diameter via UFID or filament measuring device
  5880. break;
  5881. }
  5882. calculate_extruder_multipliers();
  5883. }
  5884. break;
  5885. /*!
  5886. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5887. For each axis individually.
  5888. ##### Usage
  5889. M201 [ X | Y | Z | E ]
  5890. ##### Parameters
  5891. - `X` - Acceleration for X axis in units/s^2
  5892. - `Y` - Acceleration for Y axis in units/s^2
  5893. - `Z` - Acceleration for Z axis in units/s^2
  5894. - `E` - Acceleration for the active or specified extruder in units/s^2
  5895. */
  5896. case 201:
  5897. for (int8_t i = 0; i < NUM_AXIS; i++)
  5898. {
  5899. if (code_seen(axis_codes[i]))
  5900. {
  5901. unsigned long val = code_value();
  5902. #ifdef TMC2130
  5903. unsigned long val_silent = val;
  5904. if ((i == X_AXIS) || (i == Y_AXIS))
  5905. {
  5906. if (val > NORMAL_MAX_ACCEL_XY)
  5907. val = NORMAL_MAX_ACCEL_XY;
  5908. if (val_silent > SILENT_MAX_ACCEL_XY)
  5909. val_silent = SILENT_MAX_ACCEL_XY;
  5910. }
  5911. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5912. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5913. #else //TMC2130
  5914. max_acceleration_units_per_sq_second[i] = val;
  5915. #endif //TMC2130
  5916. }
  5917. }
  5918. // 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)
  5919. reset_acceleration_rates();
  5920. break;
  5921. #if 0 // Not used for Sprinter/grbl gen6
  5922. case 202: // M202
  5923. for(int8_t i=0; i < NUM_AXIS; i++) {
  5924. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5925. }
  5926. break;
  5927. #endif
  5928. /*!
  5929. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5930. For each axis individually.
  5931. ##### Usage
  5932. M203 [ X | Y | Z | E ]
  5933. ##### Parameters
  5934. - `X` - Maximum feedrate for X axis
  5935. - `Y` - Maximum feedrate for Y axis
  5936. - `Z` - Maximum feedrate for Z axis
  5937. - `E` - Maximum feedrate for extruder drives
  5938. */
  5939. case 203: // M203 max feedrate mm/sec
  5940. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5941. {
  5942. if (code_seen(axis_codes[i]))
  5943. {
  5944. float val = code_value();
  5945. #ifdef TMC2130
  5946. float val_silent = val;
  5947. if ((i == X_AXIS) || (i == Y_AXIS))
  5948. {
  5949. if (val > NORMAL_MAX_FEEDRATE_XY)
  5950. val = NORMAL_MAX_FEEDRATE_XY;
  5951. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5952. val_silent = SILENT_MAX_FEEDRATE_XY;
  5953. }
  5954. cs.max_feedrate_normal[i] = val;
  5955. cs.max_feedrate_silent[i] = val_silent;
  5956. #else //TMC2130
  5957. max_feedrate[i] = val;
  5958. #endif //TMC2130
  5959. }
  5960. }
  5961. break;
  5962. /*!
  5963. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  5964. #### Old format:
  5965. ##### Usage
  5966. M204 [ S | T ]
  5967. ##### Parameters
  5968. - `S` - normal moves
  5969. - `T` - filmanent only moves
  5970. #### New format:
  5971. ##### Usage
  5972. M204 [ P | R | T ]
  5973. ##### Parameters
  5974. - `P` - printing moves
  5975. - `R` - filmanent only moves
  5976. - `T` - travel moves (as of now T is ignored)
  5977. */
  5978. case 204:
  5979. {
  5980. if(code_seen('S')) {
  5981. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5982. // and it is also generated by Slic3r to control acceleration per extrusion type
  5983. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5984. cs.acceleration = cs.travel_acceleration = code_value();
  5985. // Interpret the T value as retract acceleration in the old Marlin format.
  5986. if(code_seen('T'))
  5987. cs.retract_acceleration = code_value();
  5988. } else {
  5989. // New acceleration format, compatible with the upstream Marlin.
  5990. if(code_seen('P'))
  5991. cs.acceleration = code_value();
  5992. if(code_seen('R'))
  5993. cs.retract_acceleration = code_value();
  5994. if(code_seen('T'))
  5995. cs.travel_acceleration = code_value();
  5996. }
  5997. }
  5998. break;
  5999. /*!
  6000. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6001. Set some advanced settings related to movement.
  6002. #### Usage
  6003. M205 [ S | T | B | X | Y | Z | E ]
  6004. #### Parameters
  6005. - `S` - Minimum feedrate for print moves (unit/s)
  6006. - `T` - Minimum feedrate for travel moves (units/s)
  6007. - `B` - Minimum segment time (us)
  6008. - `X` - Maximum X jerk (units/s)
  6009. - `Y` - Maximum Y jerk (units/s)
  6010. - `Z` - Maximum Z jerk (units/s)
  6011. - `E` - Maximum E jerk (units/s)
  6012. */
  6013. case 205:
  6014. {
  6015. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6016. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6017. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6018. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6019. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6020. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6021. if(code_seen('E'))
  6022. {
  6023. float e = code_value();
  6024. #ifndef LA_NOCOMPAT
  6025. e = la10c_jerk(e);
  6026. #endif
  6027. cs.max_jerk[E_AXIS] = e;
  6028. }
  6029. }
  6030. break;
  6031. /*!
  6032. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6033. #### Usage
  6034. M206 [ X | Y | Z ]
  6035. #### Parameters
  6036. - `X` - X axis offset
  6037. - `Y` - Y axis offset
  6038. - `Z` - Z axis offset
  6039. */
  6040. case 206:
  6041. for(uint8_t i=0; i < 3; i++)
  6042. {
  6043. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6044. }
  6045. break;
  6046. #ifdef FWRETRACT
  6047. /*!
  6048. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6049. #### Usage
  6050. M207 [ S | F | Z ]
  6051. #### Parameters
  6052. - `S` - positive length to retract, in mm
  6053. - `F` - retraction feedrate, in mm/min
  6054. - `Z` - additional zlift/hop
  6055. */
  6056. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6057. {
  6058. if(code_seen('S'))
  6059. {
  6060. cs.retract_length = code_value() ;
  6061. }
  6062. if(code_seen('F'))
  6063. {
  6064. cs.retract_feedrate = code_value()/60 ;
  6065. }
  6066. if(code_seen('Z'))
  6067. {
  6068. cs.retract_zlift = code_value() ;
  6069. }
  6070. }break;
  6071. /*!
  6072. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6073. #### Usage
  6074. M208 [ S | F ]
  6075. #### Parameters
  6076. - `S` - positive length surplus to the M207 Snnn, in mm
  6077. - `F` - feedrate, in mm/sec
  6078. */
  6079. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6080. {
  6081. if(code_seen('S'))
  6082. {
  6083. cs.retract_recover_length = code_value() ;
  6084. }
  6085. if(code_seen('F'))
  6086. {
  6087. cs.retract_recover_feedrate = code_value()/60 ;
  6088. }
  6089. }break;
  6090. /*!
  6091. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6092. This boolean value S 1=true or 0=false enables automatic retract detect if the slicer did not support G10/G11: every normal extrude-only move will be classified as retract depending on the direction.
  6093. #### Usage
  6094. M209 [ S ]
  6095. #### Parameters
  6096. - `S` - 1=true or 0=false
  6097. */
  6098. 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.
  6099. {
  6100. if(code_seen('S'))
  6101. {
  6102. switch(code_value_uint8())
  6103. {
  6104. case 0:
  6105. {
  6106. cs.autoretract_enabled=false;
  6107. retracted[0]=false;
  6108. #if EXTRUDERS > 1
  6109. retracted[1]=false;
  6110. #endif
  6111. #if EXTRUDERS > 2
  6112. retracted[2]=false;
  6113. #endif
  6114. }break;
  6115. case 1:
  6116. {
  6117. cs.autoretract_enabled=true;
  6118. retracted[0]=false;
  6119. #if EXTRUDERS > 1
  6120. retracted[1]=false;
  6121. #endif
  6122. #if EXTRUDERS > 2
  6123. retracted[2]=false;
  6124. #endif
  6125. }break;
  6126. default:
  6127. SERIAL_ECHO_START;
  6128. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6129. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6130. SERIAL_ECHOLNPGM("\"(1)");
  6131. }
  6132. }
  6133. }break;
  6134. #endif // FWRETRACT
  6135. /*!
  6136. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6137. #### Usage
  6138. M214 [P] [S] [N] [R] [F]
  6139. #### Parameters
  6140. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6141. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6142. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6143. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6144. except when the results in segment lengths greater than or less than the minimum
  6145. and maximum segment length. Set to 0 to disable.
  6146. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6147. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6148. */
  6149. case 214: //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  6150. {
  6151. // Extract all possible parameters if they appear
  6152. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6153. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6154. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6155. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6156. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6157. // Ensure mm_per_arc_segment is greater than 0, and that min_mm_per_arc_segment is sero or greater than or equal to mm_per_arc_segment
  6158. if (p <=0 || s < 0 || p < s)
  6159. {
  6160. // Should we display some error here?
  6161. break;
  6162. }
  6163. cs.mm_per_arc_segment = p;
  6164. cs.min_mm_per_arc_segment = s;
  6165. cs.n_arc_correction = n;
  6166. cs.min_arc_segments = r;
  6167. cs.arc_segments_per_sec = f;
  6168. }break;
  6169. #if EXTRUDERS > 1
  6170. /*!
  6171. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6172. In Prusa Firmware this G-code is only active if `EXTRUDERS` is higher then 1 in the source code. On Original i3 Prusa MK2/s MK2.5/s MK3/s it is not active.
  6173. #### Usage
  6174. M218 [ X | Y ]
  6175. #### Parameters
  6176. - `X` - X offset
  6177. - `Y` - Y offset
  6178. */
  6179. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6180. {
  6181. uint8_t extruder;
  6182. if(setTargetedHotend(218, extruder)){
  6183. break;
  6184. }
  6185. if(code_seen('X'))
  6186. {
  6187. extruder_offset[X_AXIS][extruder] = code_value();
  6188. }
  6189. if(code_seen('Y'))
  6190. {
  6191. extruder_offset[Y_AXIS][extruder] = code_value();
  6192. }
  6193. SERIAL_ECHO_START;
  6194. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6195. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6196. {
  6197. SERIAL_ECHO(" ");
  6198. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6199. SERIAL_ECHO(",");
  6200. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6201. }
  6202. SERIAL_ECHOLN("");
  6203. }break;
  6204. #endif
  6205. /*!
  6206. ### M220 Set feedrate percentage <a href="https://reprap.org/wiki/G-code#M220:_Set_speed_factor_override_percentage">M220: Set speed factor override percentage</a>
  6207. #### Usage
  6208. M220 [ B | S | R ]
  6209. #### Parameters
  6210. - `B` - Backup current speed factor
  6211. - `S` - Speed factor override percentage (0..100 or higher)
  6212. - `R` - Restore previous speed factor
  6213. */
  6214. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6215. {
  6216. bool codesWereSeen = false;
  6217. if (code_seen('B')) //backup current speed factor
  6218. {
  6219. saved_feedmultiply_mm = feedmultiply;
  6220. codesWereSeen = true;
  6221. }
  6222. if (code_seen('S'))
  6223. {
  6224. feedmultiply = code_value_short();
  6225. codesWereSeen = true;
  6226. }
  6227. if (code_seen('R')) //restore previous feedmultiply
  6228. {
  6229. feedmultiply = saved_feedmultiply_mm;
  6230. codesWereSeen = true;
  6231. }
  6232. if (!codesWereSeen)
  6233. {
  6234. printf_P(PSTR("%i%%\n"), feedmultiply);
  6235. }
  6236. }
  6237. break;
  6238. /*!
  6239. ### M221 - Set extrude factor override percentage <a href="https://reprap.org/wiki/G-code#M221:_Set_extrude_factor_override_percentage">M221: Set extrude factor override percentage</a>
  6240. #### Usage
  6241. M221 [ S | T ]
  6242. #### Parameters
  6243. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6244. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6245. */
  6246. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6247. {
  6248. if (code_seen('S'))
  6249. {
  6250. int tmp_code = code_value_short();
  6251. if (code_seen('T'))
  6252. {
  6253. uint8_t extruder;
  6254. if (setTargetedHotend(221, extruder))
  6255. break;
  6256. extruder_multiply[extruder] = tmp_code;
  6257. }
  6258. else
  6259. {
  6260. extrudemultiply = tmp_code ;
  6261. }
  6262. }
  6263. else
  6264. {
  6265. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6266. }
  6267. calculate_extruder_multipliers();
  6268. }
  6269. break;
  6270. /*!
  6271. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6272. Wait until the specified pin reaches the state required
  6273. #### Usage
  6274. M226 [ P | S ]
  6275. #### Parameters
  6276. - `P` - pin number
  6277. - `S` - pin state
  6278. */
  6279. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6280. {
  6281. if(code_seen('P')){
  6282. int pin_number = code_value_short(); // pin number
  6283. int pin_state = -1; // required pin state - default is inverted
  6284. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6285. if(pin_state >= -1 && pin_state <= 1){
  6286. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6287. {
  6288. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6289. {
  6290. pin_number = -1;
  6291. break;
  6292. }
  6293. }
  6294. if (pin_number > -1)
  6295. {
  6296. int target = LOW;
  6297. st_synchronize();
  6298. pinMode(pin_number, INPUT);
  6299. switch(pin_state){
  6300. case 1:
  6301. target = HIGH;
  6302. break;
  6303. case 0:
  6304. target = LOW;
  6305. break;
  6306. case -1:
  6307. target = !digitalRead(pin_number);
  6308. break;
  6309. }
  6310. while(digitalRead(pin_number) != target){
  6311. manage_heater();
  6312. manage_inactivity();
  6313. lcd_update(0);
  6314. }
  6315. }
  6316. }
  6317. }
  6318. }
  6319. break;
  6320. #if NUM_SERVOS > 0
  6321. /*!
  6322. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6323. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6324. #### Usage
  6325. M280 [ P | S ]
  6326. #### Parameters
  6327. - `P` - Servo index (id)
  6328. - `S` - Target position
  6329. */
  6330. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6331. {
  6332. int servo_index = -1;
  6333. int servo_position = 0;
  6334. if (code_seen('P'))
  6335. servo_index = code_value();
  6336. if (code_seen('S')) {
  6337. servo_position = code_value();
  6338. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6339. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6340. servos[servo_index].attach(0);
  6341. #endif
  6342. servos[servo_index].write(servo_position);
  6343. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6344. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6345. servos[servo_index].detach();
  6346. #endif
  6347. }
  6348. else {
  6349. SERIAL_ECHO_START;
  6350. SERIAL_ECHO("Servo ");
  6351. SERIAL_ECHO(servo_index);
  6352. SERIAL_ECHOLN(" out of range");
  6353. }
  6354. }
  6355. else if (servo_index >= 0) {
  6356. SERIAL_PROTOCOL(MSG_OK);
  6357. SERIAL_PROTOCOL(" Servo ");
  6358. SERIAL_PROTOCOL(servo_index);
  6359. SERIAL_PROTOCOL(": ");
  6360. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6361. }
  6362. }
  6363. break;
  6364. #endif // NUM_SERVOS > 0
  6365. #if (LARGE_FLASH == true && BEEPER > 0 )
  6366. /*!
  6367. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6368. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6369. #### Usage
  6370. M300 [ S | P ]
  6371. #### Parameters
  6372. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6373. - `P` - duration in milliseconds
  6374. */
  6375. case 300: // M300
  6376. {
  6377. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6378. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6379. #if BEEPER > 0
  6380. if (beepP > 0)
  6381. Sound_MakeCustom(beepP,beepS,false);
  6382. #endif
  6383. }
  6384. break;
  6385. #endif // M300
  6386. #ifdef PIDTEMP
  6387. /*!
  6388. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6389. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6390. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6391. #### Usage
  6392. M301 [ P | I | D ]
  6393. #### Parameters
  6394. - `P` - proportional (Kp)
  6395. - `I` - integral (Ki)
  6396. - `D` - derivative (Kd)
  6397. */
  6398. case 301:
  6399. {
  6400. if(code_seen('P')) cs.Kp = code_value();
  6401. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6402. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6403. updatePID();
  6404. SERIAL_PROTOCOLRPGM(MSG_OK);
  6405. SERIAL_PROTOCOLPGM(" p:");
  6406. SERIAL_PROTOCOL(cs.Kp);
  6407. SERIAL_PROTOCOLPGM(" i:");
  6408. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6409. SERIAL_PROTOCOLPGM(" d:");
  6410. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6411. SERIAL_PROTOCOLLN();
  6412. }
  6413. break;
  6414. #endif //PIDTEMP
  6415. #ifdef PIDTEMPBED
  6416. /*!
  6417. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6418. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6419. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6420. #### Usage
  6421. M304 [ P | I | D ]
  6422. #### Parameters
  6423. - `P` - proportional (Kp)
  6424. - `I` - integral (Ki)
  6425. - `D` - derivative (Kd)
  6426. */
  6427. case 304:
  6428. {
  6429. if(code_seen('P')) cs.bedKp = code_value();
  6430. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6431. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6432. updatePID();
  6433. SERIAL_PROTOCOLRPGM(MSG_OK);
  6434. SERIAL_PROTOCOLPGM(" p:");
  6435. SERIAL_PROTOCOL(cs.bedKp);
  6436. SERIAL_PROTOCOLPGM(" i:");
  6437. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6438. SERIAL_PROTOCOLPGM(" d:");
  6439. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6440. }
  6441. break;
  6442. #endif //PIDTEMP
  6443. /*!
  6444. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6445. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6446. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6447. */
  6448. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6449. {
  6450. #ifdef CHDK
  6451. SET_OUTPUT(CHDK);
  6452. WRITE(CHDK, HIGH);
  6453. chdkHigh = _millis();
  6454. chdkActive = true;
  6455. #else
  6456. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6457. const uint8_t NUM_PULSES=16;
  6458. const float PULSE_LENGTH=0.01524;
  6459. for(int i=0; i < NUM_PULSES; i++) {
  6460. WRITE(PHOTOGRAPH_PIN, HIGH);
  6461. _delay_ms(PULSE_LENGTH);
  6462. WRITE(PHOTOGRAPH_PIN, LOW);
  6463. _delay_ms(PULSE_LENGTH);
  6464. }
  6465. _delay(7.33);
  6466. for(int i=0; i < NUM_PULSES; i++) {
  6467. WRITE(PHOTOGRAPH_PIN, HIGH);
  6468. _delay_ms(PULSE_LENGTH);
  6469. WRITE(PHOTOGRAPH_PIN, LOW);
  6470. _delay_ms(PULSE_LENGTH);
  6471. }
  6472. #endif
  6473. #endif //chdk end if
  6474. }
  6475. break;
  6476. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6477. /*!
  6478. ### M302 - Allow cold extrude, or set minimum extrude temperature <a href="https://reprap.org/wiki/G-code#M302:_Allow_cold_extrudes">M302: Allow cold extrudes</a>
  6479. This tells the printer to allow movement of the extruder motor above a certain temperature, or if disabled, to allow extruder movement when the hotend is below a safe printing temperature.
  6480. #### Usage
  6481. M302 [ S ]
  6482. #### Parameters
  6483. - `S` - Cold extrude minimum temperature
  6484. */
  6485. case 302:
  6486. {
  6487. int temp = 0;
  6488. if (code_seen('S')) temp=code_value_short();
  6489. set_extrude_min_temp(temp);
  6490. }
  6491. break;
  6492. #endif
  6493. /*!
  6494. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6495. PID Tuning refers to a control algorithm used in some repraps to tune heating behavior for hot ends and heated beds. This command generates Proportional (Kp), Integral (Ki), and Derivative (Kd) values for the hotend or bed. Send the appropriate code and wait for the output to update the firmware values.
  6496. #### Usage
  6497. M303 [ E | S | C ]
  6498. #### Parameters
  6499. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6500. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6501. - `C` - Cycles, default `5`
  6502. */
  6503. case 303:
  6504. {
  6505. float temp = 150.0;
  6506. int e = 0;
  6507. int c = 5;
  6508. if (code_seen('E')) e = code_value_short();
  6509. if (e < 0)
  6510. temp = 70;
  6511. if (code_seen('S')) temp = code_value();
  6512. if (code_seen('C')) c = code_value_short();
  6513. PID_autotune(temp, e, c);
  6514. }
  6515. break;
  6516. #ifdef TEMP_MODEL
  6517. /*!
  6518. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6519. #### Usage
  6520. M310 ; report values
  6521. M310 [ A ] [ F ] ; autotune
  6522. M310 [ S ] ; set 0=disable 1=enable
  6523. M310 [ I ] [ R ] ; set resistance at index
  6524. M310 [ P | C ] ; set power, capacitance
  6525. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6526. M310 [ T ] ; set ambient temperature correction
  6527. #### Parameters
  6528. - `I` - resistance index position (0-15)
  6529. - `R` - resistance value at index (K/W; requires `I`)
  6530. - `P` - power (W)
  6531. - `C` - capacitance (J/K)
  6532. - `S` - set 0=disable 1=enable
  6533. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6534. - `E` - error threshold (K/s; default in variant)
  6535. - `W` - warning threshold (K/s; default in variant)
  6536. - `T` - ambient temperature correction (K; default in variant)
  6537. - `A` - autotune C+R values
  6538. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6539. */
  6540. case 310:
  6541. {
  6542. // parse all parameters
  6543. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6544. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6545. if(code_seen('C')) C = code_value();
  6546. if(code_seen('P')) P = code_value();
  6547. if(code_seen('I')) I = code_value_short();
  6548. if(code_seen('R')) R = code_value();
  6549. if(code_seen('S')) S = code_value_short();
  6550. if(code_seen('B')) B = code_value_short();
  6551. if(code_seen('E')) E = code_value();
  6552. if(code_seen('W')) W = code_value();
  6553. if(code_seen('T')) T = code_value();
  6554. if(code_seen('A')) A = code_value_short();
  6555. if(code_seen('F')) F = code_value_short();
  6556. // report values if nothing has been requested
  6557. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6558. temp_model_report_settings();
  6559. break;
  6560. }
  6561. // update all parameters
  6562. if(B >= 0) temp_model_set_warn_beep(B);
  6563. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6564. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6565. // enable the model last, if requested
  6566. if(S >= 0) temp_model_set_enabled(S);
  6567. // run autotune
  6568. if(A >= 0) temp_model_autotune(A, F > 0);
  6569. }
  6570. break;
  6571. #endif
  6572. /*!
  6573. ### M400 - Wait for all moves to finish <a href="https://reprap.org/wiki/G-code#M400:_Wait_for_current_moves_to_finish">M400: Wait for current moves to finish</a>
  6574. Finishes all current moves and and thus clears the buffer.
  6575. Equivalent to `G4` with no parameters.
  6576. */
  6577. case 400:
  6578. {
  6579. st_synchronize();
  6580. }
  6581. break;
  6582. /*!
  6583. ### M403 - Set filament type (material) for particular extruder and notify the MMU <a href="https://reprap.org/wiki/G-code#M403:_Set_filament_type_.28material.29_for_particular_extruder_and_notify_the_MMU.">M403 - Set filament type (material) for particular extruder and notify the MMU</a>
  6584. Currently three different materials are needed (default, flex and PVA).
  6585. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6586. #### Usage
  6587. M403 [ E | F ]
  6588. #### Parameters
  6589. - `E` - Extruder number. 0-indexed.
  6590. - `F` - Filament type
  6591. */
  6592. case 403:
  6593. {
  6594. // currently three different materials are needed (default, flex and PVA)
  6595. // add storing this information for different load/unload profiles etc. in the future
  6596. if (MMU2::mmu2.Enabled())
  6597. {
  6598. uint8_t extruder = 255;
  6599. uint8_t filament = FILAMENT_UNDEFINED;
  6600. if(code_seen('E')) extruder = code_value_uint8();
  6601. if(code_seen('F')) filament = code_value_uint8();
  6602. MMU2::mmu2.set_filament_type(extruder, filament);
  6603. }
  6604. }
  6605. break;
  6606. /*!
  6607. ### M500 - Store settings in EEPROM <a href="https://reprap.org/wiki/G-code#M500:_Store_parameters_in_non-volatile_storage">M500: Store parameters in non-volatile storage</a>
  6608. Save current parameters to EEPROM.
  6609. */
  6610. case 500:
  6611. {
  6612. Config_StoreSettings();
  6613. }
  6614. break;
  6615. /*!
  6616. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6617. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6618. */
  6619. case 501:
  6620. {
  6621. Config_RetrieveSettings();
  6622. }
  6623. break;
  6624. /*!
  6625. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6626. This command resets all tunable parameters to their default values, as set in the firmware's configuration files. This doesn't reset any parameters stored in the EEPROM, so it must be followed by M500 to write the default settings.
  6627. */
  6628. case 502:
  6629. {
  6630. Config_ResetDefault();
  6631. }
  6632. break;
  6633. /*!
  6634. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6635. This command asks the firmware to reply with the current print settings as set in memory. Settings will differ from EEPROM contents if changed since the last load / save. The reply output includes the G-Code commands to produce each setting. For example, Steps-Per-Unit values are displayed as an M92 command.
  6636. */
  6637. case 503:
  6638. {
  6639. Config_PrintSettings();
  6640. }
  6641. break;
  6642. /*!
  6643. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6644. Resets the language to English.
  6645. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6646. */
  6647. case 509:
  6648. {
  6649. lang_reset();
  6650. SERIAL_ECHO_START;
  6651. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6652. }
  6653. break;
  6654. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6655. /*!
  6656. ### M540 - Abort print on endstop hit (enable/disable) <a href="https://reprap.org/wiki/G-code#M540_in_Marlin:_Enable.2FDisable_.22Stop_SD_Print_on_Endstop_Hit.22">M540 in Marlin: Enable/Disable "Stop SD Print on Endstop Hit"</a>
  6657. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. You must define `ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED`.
  6658. #### Usage
  6659. M540 [ S ]
  6660. #### Parameters
  6661. - `S` - disabled=0, enabled=1
  6662. */
  6663. case 540:
  6664. {
  6665. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6666. }
  6667. break;
  6668. #endif
  6669. #ifdef ENABLE_AUTO_BED_LEVELING
  6670. /*!
  6671. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6672. Sets the Z-probe Z offset. This offset is used to determine the actual Z position of the nozzle when using a probe to home Z with G28. This value may also be used by G81 (Prusa) / G29 (Marlin) to apply correction to the Z position.
  6673. This value represents the distance from nozzle to the bed surface at the point where the probe is triggered. This value will be negative for typical switch probes, inductive probes, and setups where the nozzle makes a circuit with a raised metal contact. This setting will be greater than zero on machines where the nozzle itself is used as the probe, pressing down on the bed to press a switch. (This is a common setup on delta machines.)
  6674. #### Usage
  6675. M851 [ Z ]
  6676. #### Parameters
  6677. - `Z` - Z offset probe to nozzle.
  6678. */
  6679. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6680. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6681. {
  6682. float value;
  6683. if (code_seen('Z'))
  6684. {
  6685. value = code_value();
  6686. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6687. {
  6688. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6689. SERIAL_ECHO_START;
  6690. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6691. SERIAL_PROTOCOLLN();
  6692. }
  6693. else
  6694. {
  6695. SERIAL_ECHO_START;
  6696. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6697. SERIAL_ECHORPGM(MSG_Z_MIN);
  6698. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6699. SERIAL_ECHORPGM(MSG_Z_MAX);
  6700. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6701. SERIAL_PROTOCOLLN();
  6702. }
  6703. }
  6704. else
  6705. {
  6706. SERIAL_ECHO_START;
  6707. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6708. SERIAL_ECHO(-cs.zprobe_zoffset);
  6709. SERIAL_PROTOCOLLN();
  6710. }
  6711. break;
  6712. }
  6713. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6714. #endif // ENABLE_AUTO_BED_LEVELING
  6715. /*!
  6716. ### M552 - Set IP address <a href="https://reprap.org/wiki/G-code#M552:_Set_IP_address.2C_enable.2Fdisable_network_interface">M552: Set IP address, enable/disable network interface"</a>
  6717. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6718. If P is not specified nothing happens.
  6719. If the structure of the IP address is invalid, 0.0.0.0 is assumed and nothing is shown on the screen in the Support menu.
  6720. #### Usage
  6721. M552 [ P<IP_address> ]
  6722. #### Parameters
  6723. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6724. */
  6725. case 552:
  6726. {
  6727. if (code_seen('P'))
  6728. {
  6729. uint8_t valCnt = 0;
  6730. IP_address = 0;
  6731. do
  6732. {
  6733. *strchr_pointer = '*';
  6734. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6735. valCnt++;
  6736. } while ((valCnt < 4) && code_seen('.'));
  6737. if (valCnt != 4)
  6738. IP_address = 0;
  6739. }
  6740. } break;
  6741. #ifdef FILAMENTCHANGEENABLE
  6742. /*!
  6743. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6744. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6745. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6746. #### Usage
  6747. M600 [ X | Y | Z | E | L | AUTO ]
  6748. - `X` - X position, default 211
  6749. - `Y` - Y position, default 0
  6750. - `Z` - relative lift Z, default MIN_Z_FOR_SWAP.
  6751. - `E` - initial retract, default -2
  6752. - `L` - later retract distance for removal, default -80
  6753. - `AUTO` - Automatically (only with MMU)
  6754. */
  6755. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6756. {
  6757. st_synchronize();
  6758. float x_position = current_position[X_AXIS];
  6759. float y_position = current_position[Y_AXIS];
  6760. float z_shift = MIN_Z_FOR_SWAP;
  6761. float e_shift_init = 0;
  6762. float e_shift_late = 0;
  6763. bool automatic = false;
  6764. //Retract extruder
  6765. if(code_seen('E'))
  6766. {
  6767. e_shift_init = code_value();
  6768. }
  6769. else
  6770. {
  6771. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6772. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6773. #endif
  6774. }
  6775. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6776. if (code_seen('L'))
  6777. {
  6778. e_shift_late = code_value();
  6779. }
  6780. else
  6781. {
  6782. #ifdef FILAMENTCHANGE_FINALRETRACT
  6783. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6784. #endif
  6785. }
  6786. // Z lift. For safety only allow positive values
  6787. if (code_seen('Z')) z_shift = fabs(code_value());
  6788. //Move XY to side
  6789. if(code_seen('X'))
  6790. {
  6791. x_position = code_value();
  6792. }
  6793. else
  6794. {
  6795. #ifdef FILAMENTCHANGE_XPOS
  6796. x_position = FILAMENTCHANGE_XPOS;
  6797. #endif
  6798. }
  6799. if(code_seen('Y'))
  6800. {
  6801. y_position = code_value();
  6802. }
  6803. else
  6804. {
  6805. #ifdef FILAMENTCHANGE_YPOS
  6806. y_position = FILAMENTCHANGE_YPOS ;
  6807. #endif
  6808. }
  6809. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6810. automatic = true;
  6811. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6812. }
  6813. break;
  6814. #endif //FILAMENTCHANGEENABLE
  6815. /*!
  6816. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6817. */
  6818. /*!
  6819. ### M125 - Pause print (TODO: not implemented)
  6820. */
  6821. /*!
  6822. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6823. */
  6824. case 25:
  6825. case 601:
  6826. {
  6827. if (!isPrintPaused) {
  6828. st_synchronize();
  6829. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6830. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6831. lcd_pause_print();
  6832. }
  6833. }
  6834. break;
  6835. /*!
  6836. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6837. */
  6838. case 602:
  6839. {
  6840. if (isPrintPaused) lcd_resume_print();
  6841. }
  6842. break;
  6843. /*!
  6844. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6845. */
  6846. case 603: {
  6847. print_stop();
  6848. }
  6849. break;
  6850. #ifdef PINDA_THERMISTOR
  6851. /*!
  6852. ### M860 - Wait for extruder temperature (PINDA) <a href="https://reprap.org/wiki/G-code#M860_Wait_for_Probe_Temperature">M860 Wait for Probe Temperature</a>
  6853. Wait for PINDA thermistor to reach target temperature
  6854. #### Usage
  6855. M860 [ S ]
  6856. #### Parameters
  6857. - `S` - Target temperature
  6858. */
  6859. case 860:
  6860. {
  6861. int set_target_pinda = 0;
  6862. if (code_seen('S')) {
  6863. set_target_pinda = code_value_short();
  6864. }
  6865. else {
  6866. break;
  6867. }
  6868. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6869. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6870. SERIAL_PROTOCOLLN(set_target_pinda);
  6871. codenum = _millis();
  6872. cancel_heatup = false;
  6873. bool is_pinda_cooling = false;
  6874. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6875. is_pinda_cooling = true;
  6876. }
  6877. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6878. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6879. {
  6880. SERIAL_PROTOCOLPGM("P:");
  6881. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6882. SERIAL_PROTOCOL('/');
  6883. SERIAL_PROTOCOLLN(set_target_pinda);
  6884. codenum = _millis();
  6885. }
  6886. manage_heater();
  6887. manage_inactivity();
  6888. lcd_update(0);
  6889. }
  6890. LCD_MESSAGERPGM(MSG_OK);
  6891. break;
  6892. }
  6893. /*!
  6894. ### M861 - Set/Get PINDA temperature compensation offsets <a href="https://reprap.org/wiki/G-code#M861_Set_Probe_Thermal_Compensation">M861 Set Probe Thermal Compensation</a>
  6895. Set compensation ustep value `S` for compensation table index `I`.
  6896. #### Usage
  6897. M861 [ ? | ! | Z | S | I ]
  6898. #### Parameters
  6899. - `?` - Print current EEPROM offset values
  6900. - `!` - Set factory default values
  6901. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6902. - `S` - Microsteps
  6903. - `I` - Table index
  6904. */
  6905. case 861: {
  6906. const char * const _header = PSTR("index, temp, ustep, um");
  6907. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6908. int16_t usteps = 0;
  6909. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6910. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6911. SERIAL_PROTOCOLLNRPGM(_header);
  6912. for (uint8_t i = 0; i < 6; i++)
  6913. {
  6914. if(i > 0) {
  6915. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6916. }
  6917. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6918. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6919. SERIAL_PROTOCOLPGM(", ");
  6920. SERIAL_PROTOCOL(35 + (i * 5));
  6921. SERIAL_PROTOCOLPGM(", ");
  6922. SERIAL_PROTOCOL(usteps);
  6923. SERIAL_PROTOCOLPGM(", ");
  6924. SERIAL_PROTOCOLLN(mm * 1000);
  6925. }
  6926. }
  6927. else if (code_seen('!')) { // ! - Set factory default values
  6928. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6929. int16_t z_shift = 8; //40C - 20um - 8usteps
  6930. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6931. z_shift = 24; //45C - 60um - 24usteps
  6932. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6933. z_shift = 48; //50C - 120um - 48usteps
  6934. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6935. z_shift = 80; //55C - 200um - 80usteps
  6936. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6937. z_shift = 120; //60C - 300um - 120usteps
  6938. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6939. SERIAL_PROTOCOLLNPGM("factory restored");
  6940. }
  6941. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6942. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6943. int16_t z_shift = 0;
  6944. for (uint8_t i = 0; i < 5; i++) {
  6945. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  6946. }
  6947. SERIAL_PROTOCOLLNPGM("zerorized");
  6948. }
  6949. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6950. int16_t usteps = code_value_short();
  6951. if (code_seen('I')) {
  6952. uint8_t index = code_value_uint8();
  6953. if (index < 5) {
  6954. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  6955. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6956. SERIAL_PROTOCOLLNRPGM(_header);
  6957. for (uint8_t i = 0; i < 6; i++)
  6958. {
  6959. usteps = 0;
  6960. if (i > 0) {
  6961. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6962. }
  6963. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6964. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6965. SERIAL_PROTOCOLPGM(", ");
  6966. SERIAL_PROTOCOL(35 + (i * 5));
  6967. SERIAL_PROTOCOLPGM(", ");
  6968. SERIAL_PROTOCOL(usteps);
  6969. SERIAL_PROTOCOLPGM(", ");
  6970. SERIAL_PROTOCOLLN(mm * 1000);
  6971. }
  6972. }
  6973. }
  6974. }
  6975. else {
  6976. SERIAL_PROTOCOLLNPGM("no valid command");
  6977. }
  6978. } break;
  6979. #endif //PINDA_THERMISTOR
  6980. /*!
  6981. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  6982. Checks the parameters of the printer and gcode and performs compatibility check
  6983. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  6984. - M862.2 { P<model_code> | Q }
  6985. - M862.3 { P"<model_name>" | Q }
  6986. - M862.4 { P<fw_version> | Q }
  6987. - M862.5 { P<gcode_level> | Q }
  6988. When run with P<> argument, the check is performed against the input value.
  6989. When run with Q argument, the current value is shown.
  6990. M862.3 accepts text identifiers of printer types too.
  6991. The syntax of M862.3 is (note the quotes around the type):
  6992. M862.3 P "MK3S"
  6993. Accepted printer type identifiers and their numeric counterparts:
  6994. - MK1 (100)
  6995. - MK2 (200)
  6996. - MK2MM (201)
  6997. - MK2S (202)
  6998. - MK2SMM (203)
  6999. - MK2.5 (250)
  7000. - MK2.5MMU2 (20250)
  7001. - MK2.5S (252)
  7002. - MK2.5SMMU2S (20252)
  7003. - MK3 (300)
  7004. - MK3MMU2 (20300)
  7005. - MK3S (302)
  7006. - MK3SMMU2S (20302)
  7007. */
  7008. case 862: // M862: print checking
  7009. float nDummy;
  7010. uint8_t nCommand;
  7011. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7012. switch((ClPrintChecking)nCommand)
  7013. {
  7014. case ClPrintChecking::_Nozzle: // ~ .1
  7015. uint16_t nDiameter;
  7016. if(code_seen('P'))
  7017. {
  7018. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7019. nozzle_diameter_check(nDiameter);
  7020. }
  7021. else if(code_seen('Q'))
  7022. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7023. break;
  7024. case ClPrintChecking::_Model: { // ~ .2
  7025. uint16_t type = nPrinterType(MMU2::mmu2.Enabled());
  7026. if(code_seen('P'))
  7027. {
  7028. uint16_t nPrinterModel;
  7029. nPrinterModel=(uint16_t)code_value_long();
  7030. // based on current state of MMU (active/stopped/connecting) perform a runtime update of the printer type
  7031. printer_model_check(nPrinterModel, type);
  7032. }
  7033. else if(code_seen('Q'))
  7034. SERIAL_PROTOCOLLN(type);
  7035. } break;
  7036. case ClPrintChecking::_Smodel: { // ~ .3
  7037. const char *type = sPrinterType(MMU2::mmu2.Enabled());
  7038. if(code_seen('P'))
  7039. {
  7040. printer_smodel_check(strchr_pointer, type);
  7041. }
  7042. else if(code_seen('Q'))
  7043. SERIAL_PROTOCOLLNRPGM(type);
  7044. } break;
  7045. case ClPrintChecking::_Version: // ~ .4
  7046. if(code_seen('P'))
  7047. fw_version_check(++strchr_pointer);
  7048. else if(code_seen('Q'))
  7049. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7050. break;
  7051. case ClPrintChecking::_Gcode: // ~ .5
  7052. if(code_seen('P'))
  7053. {
  7054. uint16_t nGcodeLevel;
  7055. nGcodeLevel=(uint16_t)code_value_long();
  7056. gcode_level_check(nGcodeLevel);
  7057. }
  7058. else if(code_seen('Q'))
  7059. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7060. break;
  7061. }
  7062. break;
  7063. #ifdef LIN_ADVANCE
  7064. /*!
  7065. ### M900 - Set Linear advance options <a href="https://reprap.org/wiki/G-code#M900_Set_Linear_Advance_Scaling_Factors">M900 Set Linear Advance Scaling Factors</a>
  7066. Sets the advance extrusion factors for Linear Advance. If any of the R, W, H, or D parameters are set to zero the ratio will be computed dynamically during printing.
  7067. #### Usage
  7068. M900 [ K | R | W | H | D]
  7069. #### Parameters
  7070. - `K` - Advance K factor
  7071. - `R` - Set ratio directly (overrides WH/D)
  7072. - `W` - Width
  7073. - `H` - Height
  7074. - `D` - Diameter Set ratio from WH/D
  7075. */
  7076. case 900:
  7077. gcode_M900();
  7078. break;
  7079. #endif
  7080. /*!
  7081. ### M907 - Set digital trimpot motor current in mA using axis codes <a href="https://reprap.org/wiki/G-code#M907:_Set_digital_trimpot_motor">M907: Set digital trimpot motor</a>
  7082. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7083. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7084. #### Usage
  7085. M907 [ X | Y | Z | E | B | S ]
  7086. #### Parameters
  7087. - `X` - X motor driver
  7088. - `Y` - Y motor driver
  7089. - `Z` - Z motor driver
  7090. - `E` - Extruder motor driver
  7091. - `B` - Second Extruder motor driver
  7092. - `S` - All motors
  7093. */
  7094. case 907:
  7095. {
  7096. #ifdef TMC2130
  7097. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7098. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7099. if(code_seen(axis_codes[i])){
  7100. if( i == E_AXIS && FarmOrUserECool() ){
  7101. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7102. SERIAL_ECHOLNPGM(", M907 E ignored");
  7103. continue;
  7104. }
  7105. long cur_mA = code_value_long();
  7106. uint8_t val = tmc2130_cur2val(cur_mA);
  7107. tmc2130_set_current_h(i, val);
  7108. tmc2130_set_current_r(i, val);
  7109. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7110. }
  7111. }
  7112. #else //TMC2130
  7113. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7114. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7115. if(code_seen('B')) st_current_set(4,code_value());
  7116. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7117. #endif
  7118. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7119. if(code_seen('X')) st_current_set(0, code_value());
  7120. #endif
  7121. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7122. if(code_seen('Z')) st_current_set(1, code_value());
  7123. #endif
  7124. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7125. if(code_seen('E')) st_current_set(2, code_value());
  7126. #endif
  7127. #endif //TMC2130
  7128. }
  7129. break;
  7130. /*!
  7131. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7132. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7133. #### Usage
  7134. M908 [ P | S ]
  7135. #### Parameters
  7136. - `P` - channel
  7137. - `S` - current
  7138. */
  7139. case 908:
  7140. {
  7141. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7142. uint8_t channel,current;
  7143. if(code_seen('P')) channel=code_value();
  7144. if(code_seen('S')) current=code_value();
  7145. digitalPotWrite(channel, current);
  7146. #endif
  7147. }
  7148. break;
  7149. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7150. /*!
  7151. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7152. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7153. */
  7154. case 910:
  7155. {
  7156. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7157. }
  7158. break;
  7159. /*!
  7160. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7161. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7162. #### Usage
  7163. M911 [ X | Y | Z | E ]
  7164. #### Parameters
  7165. - `X` - X stepper driver holding current value
  7166. - `Y` - Y stepper driver holding current value
  7167. - `Z` - Z stepper driver holding current value
  7168. - `E` - Extruder stepper driver holding current value
  7169. */
  7170. case 911:
  7171. {
  7172. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7173. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7174. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7175. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7176. }
  7177. break;
  7178. /*!
  7179. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7180. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7181. #### Usage
  7182. M912 [ X | Y | Z | E ]
  7183. #### Parameters
  7184. - `X` - X stepper driver running current value
  7185. - `Y` - Y stepper driver running current value
  7186. - `Z` - Z stepper driver running current value
  7187. - `E` - Extruder stepper driver running current value
  7188. */
  7189. case 912:
  7190. {
  7191. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7192. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7193. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7194. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7195. }
  7196. break;
  7197. /*!
  7198. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7199. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7200. Shows TMC2130 currents.
  7201. */
  7202. case 913:
  7203. {
  7204. tmc2130_print_currents();
  7205. }
  7206. break;
  7207. /*!
  7208. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7209. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7210. */
  7211. case 914:
  7212. {
  7213. tmc2130_mode = TMC2130_MODE_NORMAL;
  7214. update_mode_profile();
  7215. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7216. }
  7217. break;
  7218. /*!
  7219. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7220. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7221. */
  7222. case 915:
  7223. {
  7224. tmc2130_mode = TMC2130_MODE_SILENT;
  7225. update_mode_profile();
  7226. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7227. }
  7228. break;
  7229. /*!
  7230. ### M916 - Set TMC2130 Stallguard sensitivity threshold <a href="https://reprap.org/wiki/G-code#M916:_Set_TMC2130_Stallguard_sensitivity_threshold">M916: Set TMC2130 Stallguard sensitivity threshold</a>
  7231. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7232. #### Usage
  7233. M916 [ X | Y | Z | E ]
  7234. #### Parameters
  7235. - `X` - X stepper driver stallguard sensitivity threshold value
  7236. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7237. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7238. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7239. */
  7240. case 916:
  7241. {
  7242. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7243. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7244. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7245. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7246. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7247. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7248. }
  7249. break;
  7250. /*!
  7251. ### M917 - Set TMC2130 PWM amplitude offset (pwm_ampl) <a href="https://reprap.org/wiki/G-code#M917:_Set_TMC2130_PWM_amplitude_offset_.28pwm_ampl.29">M917: Set TMC2130 PWM amplitude offset (pwm_ampl)</a>
  7252. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7253. #### Usage
  7254. M917 [ X | Y | Z | E ]
  7255. #### Parameters
  7256. - `X` - X stepper driver PWM amplitude offset value
  7257. - `Y` - Y stepper driver PWM amplitude offset value
  7258. - `Z` - Z stepper driver PWM amplitude offset value
  7259. - `E` - Extruder stepper driver PWM amplitude offset value
  7260. */
  7261. case 917:
  7262. {
  7263. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7264. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7265. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7266. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7267. }
  7268. break;
  7269. /*!
  7270. ### M918 - Set TMC2130 PWM amplitude gradient (pwm_grad) <a href="https://reprap.org/wiki/G-code#M918:_Set_TMC2130_PWM_amplitude_gradient_.28pwm_grad.29">M918: Set TMC2130 PWM amplitude gradient (pwm_grad)</a>
  7271. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7272. #### Usage
  7273. M918 [ X | Y | Z | E ]
  7274. #### Parameters
  7275. - `X` - X stepper driver PWM amplitude gradient value
  7276. - `Y` - Y stepper driver PWM amplitude gradient value
  7277. - `Z` - Z stepper driver PWM amplitude gradient value
  7278. - `E` - Extruder stepper driver PWM amplitude gradient value
  7279. */
  7280. case 918:
  7281. {
  7282. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7283. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7284. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7285. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7286. }
  7287. break;
  7288. #endif //TMC2130_SERVICE_CODES_M910_M918
  7289. /*!
  7290. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7291. Printers with TMC2130 drivers have `X`, `Y`, `Z` and `E` as options. The steps-per-unit value is updated accordingly. Not all resolutions are valid!
  7292. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7293. #### Usage
  7294. M350 [ X | Y | Z | E | B | S ]
  7295. #### Parameters
  7296. - `X` - X new resolution
  7297. - `Y` - Y new resolution
  7298. - `Z` - Z new resolution
  7299. - `E` - E new resolution
  7300. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7301. - `B` - Second extruder new resolution
  7302. - `S` - All axes new resolution
  7303. */
  7304. case 350:
  7305. {
  7306. #ifdef TMC2130
  7307. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7308. {
  7309. if(code_seen(axis_codes[i]))
  7310. {
  7311. uint16_t res_new = code_value();
  7312. #ifdef ALLOW_ALL_MRES
  7313. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7314. #else
  7315. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7316. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7317. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7318. #endif
  7319. if (res_valid)
  7320. {
  7321. st_synchronize();
  7322. uint16_t res = tmc2130_get_res(i);
  7323. tmc2130_set_res(i, res_new);
  7324. cs.axis_ustep_resolution[i] = res_new;
  7325. if (res_new > res)
  7326. {
  7327. uint16_t fac = (res_new / res);
  7328. cs.axis_steps_per_unit[i] *= fac;
  7329. position[i] *= fac;
  7330. }
  7331. else
  7332. {
  7333. uint16_t fac = (res / res_new);
  7334. cs.axis_steps_per_unit[i] /= fac;
  7335. position[i] /= fac;
  7336. }
  7337. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7338. if (i == E_AXIS)
  7339. fsensor.init();
  7340. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7341. }
  7342. }
  7343. }
  7344. reset_acceleration_rates();
  7345. #else //TMC2130
  7346. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7347. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7348. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7349. if(code_seen('B')) microstep_mode(4,code_value());
  7350. microstep_readings();
  7351. #endif
  7352. #endif //TMC2130
  7353. }
  7354. break;
  7355. /*!
  7356. ### M351 - Toggle Microstep Pins <a href="https://reprap.org/wiki/G-code#M351:_Toggle_MS1_MS2_pins_directly">M351: Toggle MS1 MS2 pins directly</a>
  7357. Toggle MS1 MS2 pins directly.
  7358. #### Usage
  7359. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7360. #### Parameters
  7361. - `X` - Update X axis
  7362. - `Y` - Update Y axis
  7363. - `Z` - Update Z axis
  7364. - `E` - Update E axis
  7365. - `S` - which MSx pin to toggle
  7366. - `B` - new pin value
  7367. */
  7368. case 351:
  7369. {
  7370. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7371. if(code_seen('S')) switch((int)code_value())
  7372. {
  7373. case 1:
  7374. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7375. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7376. break;
  7377. case 2:
  7378. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7379. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7380. break;
  7381. }
  7382. microstep_readings();
  7383. #endif
  7384. }
  7385. break;
  7386. /*!
  7387. ### M701 - Load filament to extruder <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7388. Load filament into the active extruder.
  7389. #### Usage
  7390. M701 [ P | T | L | Z ]
  7391. #### Parameters
  7392. - `P` - n index of MMU slot (zero based, so 0-4 like T0 and T4)
  7393. - `T` - Alias of `P`. Used for compatibility with Marlin
  7394. - `L` - Extrude distance for insertion (positive value)(manual reload)
  7395. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_LOAD
  7396. */
  7397. case 701:
  7398. {
  7399. uint8_t mmuSlotIndex = 0xffU;
  7400. float fastLoadLength = FILAMENTCHANGE_FIRSTFEED; // Only used without MMU
  7401. float z_target = MIN_Z_FOR_LOAD;
  7402. if( MMU2::mmu2.Enabled() )
  7403. {
  7404. if( code_seen('P') || code_seen('T') ) {
  7405. mmuSlotIndex = code_value_uint8();
  7406. }
  7407. }
  7408. if (code_seen('L')) fastLoadLength = code_value();
  7409. // Z lift. For safety only allow positive values
  7410. if (code_seen('Z')) z_target = fabs(code_value());
  7411. // Raise the Z axis
  7412. float delta = raise_z(z_target);
  7413. // Load filament
  7414. gcode_M701(fastLoadLength, mmuSlotIndex);
  7415. // Restore Z axis
  7416. raise_z(-delta);
  7417. }
  7418. break;
  7419. /*!
  7420. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7421. #### Usage
  7422. M702 [ U | Z ]
  7423. #### Parameters
  7424. - `U` - Retract distance for removal (manual reload). Default value is 0.
  7425. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_UNLOAD.
  7426. */
  7427. case 702:
  7428. {
  7429. float z_target = MIN_Z_FOR_UNLOAD;
  7430. float unloadLength = FILAMENTCHANGE_FINALRETRACT;
  7431. if (code_seen('U')) unloadLength = code_value();
  7432. // For safety only allow positive values
  7433. if (code_seen('Z')) z_target = fabs(code_value());
  7434. // Raise the Z axis
  7435. float delta = raise_z(z_target);
  7436. // Unload filament
  7437. if (MMU2::mmu2.Enabled()) MMU2::mmu2.unload();
  7438. else unload_filament(unloadLength);
  7439. // Restore Z axis
  7440. raise_z(-delta);
  7441. }
  7442. break;
  7443. /*!
  7444. ### M704 - Load to MMU <a href="https://reprap.org/wiki/G-code#M704:_Load_to_MMU">M704: Load to MMU</a>
  7445. #### Usage
  7446. M704 [ P ]
  7447. #### Parameters
  7448. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7449. */
  7450. case 704:
  7451. {
  7452. gcodes_M704_M705_M706(704);
  7453. }
  7454. break;
  7455. /*!
  7456. ### M705 - Eject filament <a href="https://reprap.org/wiki/G-code#M705:_Eject_filament">M705: Eject filament</a>
  7457. #### Usage
  7458. M705 [ P ]
  7459. #### Parameters
  7460. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7461. */
  7462. case 705:
  7463. {
  7464. gcodes_M704_M705_M706(705);
  7465. }
  7466. break;
  7467. /*!
  7468. ### M706 - Cut filament <a href="https://reprap.org/wiki/G-code#M706:_Cut_filament">M706: Cut filament</a>
  7469. #### Usage
  7470. M706 [ P ]
  7471. #### Parameters
  7472. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7473. */
  7474. case 706:
  7475. {
  7476. gcodes_M704_M705_M706(706);
  7477. }
  7478. break;
  7479. /*!
  7480. ### M707 - Read from MMU register <a href="https://reprap.org/wiki/G-code#M707:_Read_from_MMU_register">M707: Read from MMU register</a>
  7481. #### Usage
  7482. M707 [ A ]
  7483. #### Parameters
  7484. - `A` - Address of register in hexidecimal.
  7485. #### Example
  7486. M707 A0x1b - Read a 8bit integer from register 0x1b and prints the result onto the serial line.
  7487. Does nothing if the A parameter is not present or if MMU is not enabled.
  7488. */
  7489. case 707: {
  7490. if ( MMU2::mmu2.Enabled() ) {
  7491. if( code_seen('A') ) {
  7492. MMU2::mmu2.ReadRegister(uint8_t(strtol(strchr_pointer+1, NULL, 16)));
  7493. }
  7494. }
  7495. } break;
  7496. /*!
  7497. ### M708 - Write to MMU register <a href="https://reprap.org/wiki/G-code#M708:_Write_to_MMU_register">M707: Write to MMU register</a>
  7498. #### Usage
  7499. M708 [ A | X ]
  7500. #### Parameters
  7501. - `A` - Address of register in hexidecimal.
  7502. - `X` - Data to write (16-bit integer). Default value 0.
  7503. #### Example
  7504. M708 A0x1b X05 - Write to register 0x1b the value 05.
  7505. Does nothing if A parameter is missing or if MMU is not enabled.
  7506. */
  7507. case 708: {
  7508. if ( MMU2::mmu2.Enabled() ){
  7509. uint8_t addr = 0;
  7510. if( code_seen('A') ) {
  7511. addr = uint8_t(strtol(strchr_pointer+1, NULL, 16));
  7512. }
  7513. uint16_t data = 0;
  7514. if( code_seen('X') ) {
  7515. data = code_value_short();
  7516. }
  7517. if(addr){
  7518. MMU2::mmu2.WriteRegister(addr, data);
  7519. }
  7520. }
  7521. } break;
  7522. /*!
  7523. ### M709 - MMU reset <a href="https://reprap.org/wiki/G-code#M709:_MMU_reset">M709: MMU reset</a>
  7524. The MK3S cannot not power off the MMU, for that reason the functionality is not supported.
  7525. #### Usage
  7526. M709 [ X ]
  7527. #### Parameters
  7528. - `X` - Reset MMU (0:soft reset | 1:hardware reset)
  7529. #### Example
  7530. M709 X0 - issue an X0 command via communication into the MMU (soft reset)
  7531. M709 X1 - toggle the MMU's reset pin (hardware reset)
  7532. */
  7533. case 709:
  7534. {
  7535. if (MMU2::mmu2.Enabled() && code_seen('X'))
  7536. {
  7537. switch (code_value_uint8())
  7538. {
  7539. case 0:
  7540. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  7541. break;
  7542. case 1:
  7543. MMU2::mmu2.Reset(MMU2::MMU2::ResetPin);
  7544. break;
  7545. default:
  7546. break;
  7547. }
  7548. }
  7549. }
  7550. break;
  7551. /*!
  7552. #### End of M-Commands
  7553. */
  7554. default:
  7555. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7556. }
  7557. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7558. mcode_in_progress = 0;
  7559. }
  7560. }
  7561. // end if(code_seen('M')) (end of M codes)
  7562. /*!
  7563. -----------------------------------------------------------------------------------------
  7564. # T Codes
  7565. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7566. #### For MMU_V2:
  7567. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7568. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7569. @n Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load.
  7570. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7571. */
  7572. else if(code_seen('T')){
  7573. TCodes(strchr_pointer, code_value_uint8());
  7574. } // end if(code_seen('T')) (end of T codes)
  7575. /*!
  7576. #### End of T-Codes
  7577. */
  7578. /**
  7579. *---------------------------------------------------------------------------------
  7580. *# D codes
  7581. */
  7582. else if (code_seen('D')) // D codes (debug)
  7583. {
  7584. switch(code_value_short())
  7585. {
  7586. /*!
  7587. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7588. */
  7589. case -1:
  7590. dcode__1(); break;
  7591. #ifdef DEBUG_DCODES
  7592. /*!
  7593. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7594. #### Usage
  7595. D0 [ B ]
  7596. #### Parameters
  7597. - `B` - Bootloader
  7598. */
  7599. case 0:
  7600. dcode_0(); break;
  7601. /*!
  7602. *
  7603. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7604. D1
  7605. *
  7606. */
  7607. case 1:
  7608. dcode_1(); break;
  7609. #endif
  7610. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7611. /*!
  7612. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7613. This command can be used without any additional parameters. It will read the entire RAM.
  7614. #### Usage
  7615. D2 [ A | C | X ]
  7616. #### Parameters
  7617. - `A` - Address (x0000-x1fff)
  7618. - `C` - Count (1-8192)
  7619. - `X` - Data
  7620. #### Notes
  7621. - The hex address needs to be lowercase without the 0 before the x
  7622. - Count is decimal
  7623. - The hex data needs to be lowercase
  7624. */
  7625. case 2:
  7626. dcode_2(); break;
  7627. #endif //DEBUG_DCODES
  7628. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7629. /*!
  7630. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7631. This command can be used without any additional parameters. It will read the entire eeprom.
  7632. #### Usage
  7633. D3 [ A | C | X ]
  7634. #### Parameters
  7635. - `A` - Address (x0000-x0fff)
  7636. - `C` - Count (1-4096)
  7637. - `X` - Data (hex)
  7638. #### Notes
  7639. - The hex address needs to be lowercase without the 0 before the x
  7640. - Count is decimal
  7641. - The hex data needs to be lowercase
  7642. */
  7643. case 3:
  7644. dcode_3(); break;
  7645. #endif //DEBUG_DCODE3
  7646. #ifdef DEBUG_DCODES
  7647. /*!
  7648. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7649. To read the digital value of a pin you need only to define the pin number.
  7650. #### Usage
  7651. D4 [ P | F | V ]
  7652. #### Parameters
  7653. - `P` - Pin (0-255)
  7654. - `F` - Function in/out (0/1)
  7655. - `V` - Value (0/1)
  7656. */
  7657. case 4:
  7658. dcode_4(); break;
  7659. #endif //DEBUG_DCODES
  7660. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7661. /*!
  7662. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7663. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7664. #### Usage
  7665. D5 [ A | C | X | E ]
  7666. #### Parameters
  7667. - `A` - Address (x00000-x3ffff)
  7668. - `C` - Count (1-8192)
  7669. - `X` - Data (hex)
  7670. - `E` - Erase
  7671. #### Notes
  7672. - The hex address needs to be lowercase without the 0 before the x
  7673. - Count is decimal
  7674. - The hex data needs to be lowercase
  7675. */
  7676. case 5:
  7677. dcode_5(); break;
  7678. #endif //DEBUG_DCODE5
  7679. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7680. /*!
  7681. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7682. Reserved
  7683. */
  7684. case 6:
  7685. dcode_6(); break;
  7686. #endif
  7687. #ifdef DEBUG_DCODES
  7688. /*!
  7689. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7690. Reserved
  7691. */
  7692. case 7:
  7693. dcode_7(); break;
  7694. /*!
  7695. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7696. #### Usage
  7697. D8 [ ? | ! | P | Z ]
  7698. #### Parameters
  7699. - `?` - Read PINDA temperature shift values
  7700. - `!` - Reset PINDA temperature shift values to default
  7701. - `P` - Pinda temperature [C]
  7702. - `Z` - Z Offset [mm]
  7703. */
  7704. case 8:
  7705. dcode_8(); break;
  7706. /*!
  7707. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7708. #### Usage
  7709. D9 [ I | V ]
  7710. #### Parameters
  7711. - `I` - ADC channel index
  7712. - `0` - Heater 0 temperature
  7713. - `1` - Heater 1 temperature
  7714. - `2` - Bed temperature
  7715. - `3` - PINDA temperature
  7716. - `4` - PWR voltage
  7717. - `5` - Ambient temperature
  7718. - `6` - BED voltage
  7719. - `V` Value to be written as simulated
  7720. */
  7721. case 9:
  7722. dcode_9(); break;
  7723. /*!
  7724. ### D10 - Set XYZ calibration = OK <a href="https://reprap.org/wiki/G-code#D10:_Set_XYZ_calibration_.3D_OK">D10: Set XYZ calibration = OK</a>
  7725. */
  7726. case 10:
  7727. dcode_10(); break;
  7728. /*!
  7729. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7730. Writes the current time in the log file.
  7731. */
  7732. #endif //DEBUG_DCODES
  7733. #ifdef XFLASH_DUMP
  7734. /*!
  7735. ### D20 - Generate an offline crash dump <a href="https://reprap.org/wiki/G-code#D20:_Generate_an_offline_crash_dump">D20: Generate an offline crash dump</a>
  7736. Generate a crash dump for later retrival.
  7737. #### Usage
  7738. D20 [E]
  7739. ### Parameters
  7740. - `E` - Perform an emergency crash dump (resets the printer).
  7741. ### Notes
  7742. - A crash dump can be later recovered with D21, or cleared with D22.
  7743. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7744. is completed.
  7745. */
  7746. case 20: {
  7747. dcode_20();
  7748. break;
  7749. };
  7750. /*!
  7751. ### D21 - Print crash dump to serial <a href="https://reprap.org/wiki/G-code#D21:_Print_crash_dump_to_serial">D21: Print crash dump to serial</a>
  7752. Output the complete crash dump (if present) to the serial.
  7753. #### Usage
  7754. D21
  7755. ### Notes
  7756. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7757. */
  7758. case 21: {
  7759. dcode_21();
  7760. break;
  7761. };
  7762. /*!
  7763. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7764. Clear an existing internal crash dump.
  7765. #### Usage
  7766. D22
  7767. */
  7768. case 22: {
  7769. dcode_22();
  7770. break;
  7771. };
  7772. #endif //XFLASH_DUMP
  7773. #ifdef EMERGENCY_SERIAL_DUMP
  7774. /*!
  7775. ### D23 - Request emergency dump on serial <a href="https://reprap.org/wiki/G-code#D23:_Request_emergency_dump_on_serial">D23: Request emergency dump on serial</a>
  7776. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7777. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7778. #### Usage
  7779. D23 [E] [R]
  7780. #### Parameters
  7781. - `E` - Perform an emergency crash dump (resets the printer).
  7782. - `R` - Disable online dumps.
  7783. */
  7784. case 23: {
  7785. dcode_23();
  7786. break;
  7787. };
  7788. #endif
  7789. #ifdef TEMP_MODEL_DEBUG
  7790. /*!
  7791. ## D70 - Enable low-level temperature model logging for offline simulation
  7792. #### Usage
  7793. D70 [ S ]
  7794. #### Parameters
  7795. - `S` - Enable 0-1 (default 0)
  7796. */
  7797. case 70: {
  7798. if(code_seen('S'))
  7799. temp_model_log_enable(code_value_short());
  7800. break;
  7801. }
  7802. #endif
  7803. #ifdef HEATBED_ANALYSIS
  7804. /*!
  7805. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7806. This command will log data to SD card file "mesh.txt".
  7807. #### Usage
  7808. D80 [ E | F | G | H | I | J ]
  7809. #### Parameters
  7810. - `E` - Dimension X (default 40)
  7811. - `F` - Dimention Y (default 40)
  7812. - `G` - Points X (default 40)
  7813. - `H` - Points Y (default 40)
  7814. - `I` - Offset X (default 74)
  7815. - `J` - Offset Y (default 34)
  7816. */
  7817. case 80:
  7818. dcode_80(); break;
  7819. /*!
  7820. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7821. This command will log data to SD card file "wldsd.txt".
  7822. #### Usage
  7823. D81 [ E | F | G | H | I | J ]
  7824. #### Parameters
  7825. - `E` - Dimension X (default 40)
  7826. - `F` - Dimention Y (default 40)
  7827. - `G` - Points X (default 40)
  7828. - `H` - Points Y (default 40)
  7829. - `I` - Offset X (default 74)
  7830. - `J` - Offset Y (default 34)
  7831. */
  7832. case 81:
  7833. dcode_81(); break;
  7834. #endif //HEATBED_ANALYSIS
  7835. #ifdef DEBUG_DCODES
  7836. /*!
  7837. ### D106 - Print measured fan speed for different pwm values <a href="https://reprap.org/wiki/G-code#D106:_Print_measured_fan_speed_for_different_pwm_values">D106: Print measured fan speed for different pwm values</a>
  7838. */
  7839. case 106:
  7840. dcode_106(); break;
  7841. #ifdef TMC2130
  7842. /*!
  7843. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7844. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7845. #### Usage
  7846. D2130 [ Axis | Command | Subcommand | Value ]
  7847. #### Parameters
  7848. - Axis
  7849. - `X` - X stepper driver
  7850. - `Y` - Y stepper driver
  7851. - `Z` - Z stepper driver
  7852. - `E` - Extruder stepper driver
  7853. - Commands
  7854. - `0` - Current off
  7855. - `1` - Current on
  7856. - `+` - Single step
  7857. - `-` - Single step oposite direction
  7858. - `NNN` - Value sereval steps
  7859. - `?` - Read register
  7860. - Subcommands for read register
  7861. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7862. - `step` - Step
  7863. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7864. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7865. - `wave` - Microstep linearity compensation curve
  7866. - `!` - Set register
  7867. - Subcommands for set register
  7868. - `mres` - Micro step resolution
  7869. - `step` - Step
  7870. - `wave` - Microstep linearity compensation curve
  7871. - Values for set register
  7872. - `0, 180 --> 250` - Off
  7873. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7874. - `@` - Home calibrate axis
  7875. Examples:
  7876. D2130E?wave
  7877. Print extruder microstep linearity compensation curve
  7878. D2130E!wave0
  7879. Disable extruder linearity compensation curve, (sine curve is used)
  7880. D2130E!wave220
  7881. (sin(x))^1.1 extruder microstep compensation curve used
  7882. Notes:
  7883. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7884. *
  7885. */
  7886. case 2130:
  7887. dcode_2130(); break;
  7888. #endif //TMC2130
  7889. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7890. /*!
  7891. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7892. #### Usage
  7893. D9125 [ ? | ! | R | X | Y | L ]
  7894. #### Parameters
  7895. - `?` - Print values
  7896. - `!` - Print values
  7897. - `R` - Resolution. Not active in code
  7898. - `X` - X values
  7899. - `Y` - Y values
  7900. - `L` - Activate filament sensor log
  7901. */
  7902. case 9125:
  7903. dcode_9125(); break;
  7904. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7905. #endif //DEBUG_DCODES
  7906. default:
  7907. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7908. }
  7909. }
  7910. else
  7911. {
  7912. SERIAL_ECHO_START;
  7913. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7914. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7915. SERIAL_ECHOLNPGM("\"(2)");
  7916. }
  7917. KEEPALIVE_STATE(NOT_BUSY);
  7918. ClearToSend();
  7919. }
  7920. /*!
  7921. #### End of D-Codes
  7922. */
  7923. /** @defgroup GCodes G-Code List
  7924. */
  7925. // ---------------------------------------------------
  7926. void FlushSerialRequestResend()
  7927. {
  7928. //char cmdbuffer[bufindr][100]="Resend:";
  7929. MYSERIAL.flush();
  7930. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7931. }
  7932. // Confirm the execution of a command, if sent from a serial line.
  7933. // Execution of a command from a SD card will not be confirmed.
  7934. void ClearToSend()
  7935. {
  7936. previous_millis_cmd.start();
  7937. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7938. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7939. }
  7940. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7941. void update_currents() {
  7942. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7943. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7944. float tmp_motor[3];
  7945. //SERIAL_ECHOLNPGM("Currents updated: ");
  7946. if (destination[Z_AXIS] < Z_SILENT) {
  7947. //SERIAL_ECHOLNPGM("LOW");
  7948. for (uint8_t i = 0; i < 3; i++) {
  7949. st_current_set(i, current_low[i]);
  7950. /*MYSERIAL.print(int(i));
  7951. SERIAL_ECHOPGM(": ");
  7952. MYSERIAL.println(current_low[i]);*/
  7953. }
  7954. }
  7955. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7956. //SERIAL_ECHOLNPGM("HIGH");
  7957. for (uint8_t i = 0; i < 3; i++) {
  7958. st_current_set(i, current_high[i]);
  7959. /*MYSERIAL.print(int(i));
  7960. SERIAL_ECHOPGM(": ");
  7961. MYSERIAL.println(current_high[i]);*/
  7962. }
  7963. }
  7964. else {
  7965. for (uint8_t i = 0; i < 3; i++) {
  7966. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7967. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7968. st_current_set(i, tmp_motor[i]);
  7969. /*MYSERIAL.print(int(i));
  7970. SERIAL_ECHOPGM(": ");
  7971. MYSERIAL.println(tmp_motor[i]);*/
  7972. }
  7973. }
  7974. }
  7975. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7976. void get_coordinates() {
  7977. bool seen[4]={false,false,false,false};
  7978. for(int8_t i=0; i < NUM_AXIS; i++) {
  7979. if(code_seen(axis_codes[i]))
  7980. {
  7981. bool relative = axis_relative_modes & (1 << i);
  7982. destination[i] = code_value();
  7983. if (i == E_AXIS) {
  7984. float emult = extruder_multiplier[active_extruder];
  7985. if (emult != 1.) {
  7986. if (! relative) {
  7987. destination[i] -= current_position[i];
  7988. relative = true;
  7989. }
  7990. destination[i] *= emult;
  7991. }
  7992. }
  7993. if (relative)
  7994. destination[i] += current_position[i];
  7995. seen[i]=true;
  7996. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7997. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7998. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7999. }
  8000. else destination[i] = current_position[i]; //Are these else lines really needed?
  8001. }
  8002. if(code_seen('F')) {
  8003. next_feedrate = code_value();
  8004. if(next_feedrate > 0.0) feedrate = next_feedrate;
  8005. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  8006. {
  8007. // float e_max_speed =
  8008. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  8009. }
  8010. }
  8011. }
  8012. void clamp_to_software_endstops(float target[3])
  8013. {
  8014. #ifdef DEBUG_DISABLE_SWLIMITS
  8015. return;
  8016. #endif //DEBUG_DISABLE_SWLIMITS
  8017. world2machine_clamp(target[0], target[1]);
  8018. // Clamp the Z coordinate.
  8019. if (min_software_endstops) {
  8020. float negative_z_offset = 0;
  8021. #ifdef ENABLE_AUTO_BED_LEVELING
  8022. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8023. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8024. #endif
  8025. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8026. }
  8027. if (max_software_endstops) {
  8028. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8029. }
  8030. }
  8031. uint16_t restore_interrupted_gcode() {
  8032. // When recovering from a previous print move, restore the originally
  8033. // calculated start position on the first USB/SD command. This accounts
  8034. // properly for relative moves
  8035. if (
  8036. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  8037. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  8038. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  8039. )
  8040. ) {
  8041. memcpy(current_position, saved_start_position, sizeof(current_position));
  8042. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  8043. return saved_segment_idx;
  8044. }
  8045. else
  8046. return 1; //begin with the first segment
  8047. }
  8048. #ifdef MESH_BED_LEVELING
  8049. void mesh_plan_buffer_line(const float &x, const float &y, const float &z, const float &e, const float &feed_rate, const uint8_t extruder, uint16_t start_segment_idx = 0) {
  8050. float dx = x - current_position[X_AXIS];
  8051. float dy = y - current_position[Y_AXIS];
  8052. uint16_t n_segments = 0;
  8053. if (mbl.active) {
  8054. float len = fabs(dx) + fabs(dy);
  8055. if (len > 0)
  8056. // Split to 3cm segments or shorter.
  8057. n_segments = uint16_t(ceil(len / 30.f));
  8058. }
  8059. if (n_segments > 1 && start_segment_idx) {
  8060. float dz = z - current_position[Z_AXIS];
  8061. float de = e - current_position[E_AXIS];
  8062. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  8063. float t = float(i) / float(n_segments);
  8064. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8065. current_position[Y_AXIS] + t * dy,
  8066. current_position[Z_AXIS] + t * dz,
  8067. current_position[E_AXIS] + t * de,
  8068. feed_rate, extruder, current_position, i);
  8069. if (planner_aborted)
  8070. return;
  8071. }
  8072. }
  8073. // The rest of the path.
  8074. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  8075. }
  8076. #endif // MESH_BED_LEVELING
  8077. void prepare_move(uint16_t start_segment_idx)
  8078. {
  8079. clamp_to_software_endstops(destination);
  8080. previous_millis_cmd.start();
  8081. // Do not use feedmultiply for E or Z only moves
  8082. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8083. plan_buffer_line_destinationXYZE(feedrate/60);
  8084. }
  8085. else {
  8086. #ifdef MESH_BED_LEVELING
  8087. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder, start_segment_idx);
  8088. #else
  8089. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8090. #endif
  8091. }
  8092. set_current_to_destination();
  8093. }
  8094. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8095. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8096. // Trace the arc
  8097. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8098. // As far as the parser is concerned, the position is now == target. In reality the
  8099. // motion control system might still be processing the action and the real tool position
  8100. // in any intermediate location.
  8101. set_current_to_destination();
  8102. previous_millis_cmd.start();
  8103. }
  8104. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8105. #if defined(FAN_PIN)
  8106. #if CONTROLLERFAN_PIN == FAN_PIN
  8107. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8108. #endif
  8109. #endif
  8110. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8111. unsigned long lastMotorCheck = 0;
  8112. void controllerFan()
  8113. {
  8114. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8115. {
  8116. lastMotorCheck = _millis();
  8117. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8118. #if EXTRUDERS > 2
  8119. || !READ(E2_ENABLE_PIN)
  8120. #endif
  8121. #if EXTRUDER > 1
  8122. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8123. || !READ(X2_ENABLE_PIN)
  8124. #endif
  8125. || !READ(E1_ENABLE_PIN)
  8126. #endif
  8127. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8128. {
  8129. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8130. }
  8131. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8132. {
  8133. digitalWrite(CONTROLLERFAN_PIN, 0);
  8134. analogWrite(CONTROLLERFAN_PIN, 0);
  8135. }
  8136. else
  8137. {
  8138. // allows digital or PWM fan output to be used (see M42 handling)
  8139. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8140. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8141. }
  8142. }
  8143. }
  8144. #endif
  8145. #ifdef SAFETYTIMER
  8146. /**
  8147. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8148. *
  8149. * Full screen blocking notification message is shown after heater turning off.
  8150. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8151. * damage print.
  8152. *
  8153. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8154. */
  8155. static void handleSafetyTimer()
  8156. {
  8157. #if (EXTRUDERS > 1)
  8158. #error Implemented only for one extruder.
  8159. #endif //(EXTRUDERS > 1)
  8160. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8161. {
  8162. safetyTimer.stop();
  8163. }
  8164. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8165. {
  8166. safetyTimer.start();
  8167. }
  8168. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8169. {
  8170. setTargetBed(0);
  8171. setAllTargetHotends(0);
  8172. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8173. }
  8174. }
  8175. #endif //SAFETYTIMER
  8176. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8177. {
  8178. #ifdef FILAMENT_SENSOR
  8179. if (fsensor.update()) {
  8180. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8181. }
  8182. #endif
  8183. #ifdef SAFETYTIMER
  8184. handleSafetyTimer();
  8185. #endif //SAFETYTIMER
  8186. #if defined(KILL_PIN) && KILL_PIN > -1
  8187. static int killCount = 0; // make the inactivity button a bit less responsive
  8188. const int KILL_DELAY = 10000;
  8189. #endif
  8190. if(buflen < (BUFSIZE-1)){
  8191. get_command();
  8192. }
  8193. if(previous_millis_cmd.expired(max_inactive_time))
  8194. if(max_inactive_time)
  8195. kill(_n("Inactivity Shutdown"), 4);
  8196. if(stepper_inactive_time) {
  8197. if(previous_millis_cmd.expired(stepper_inactive_time))
  8198. {
  8199. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8200. disable_x();
  8201. disable_y();
  8202. disable_z();
  8203. disable_e0();
  8204. disable_e1();
  8205. disable_e2();
  8206. }
  8207. }
  8208. }
  8209. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8210. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8211. {
  8212. chdkActive = false;
  8213. WRITE(CHDK, LOW);
  8214. }
  8215. #endif
  8216. #if defined(KILL_PIN) && KILL_PIN > -1
  8217. // Check if the kill button was pressed and wait just in case it was an accidental
  8218. // key kill key press
  8219. // -------------------------------------------------------------------------------
  8220. if( 0 == READ(KILL_PIN) )
  8221. {
  8222. killCount++;
  8223. }
  8224. else if (killCount > 0)
  8225. {
  8226. killCount--;
  8227. }
  8228. // Exceeded threshold and we can confirm that it was not accidental
  8229. // KILL the machine
  8230. // ----------------------------------------------------------------
  8231. if ( killCount >= KILL_DELAY)
  8232. {
  8233. kill(NULL, 5);
  8234. }
  8235. #endif
  8236. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8237. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8238. #endif
  8239. #ifdef EXTRUDER_RUNOUT_PREVENT
  8240. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8241. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8242. {
  8243. bool oldstatus=READ(E0_ENABLE_PIN);
  8244. enable_e0();
  8245. float oldepos=current_position[E_AXIS];
  8246. float oldedes=destination[E_AXIS];
  8247. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8248. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8249. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8250. current_position[E_AXIS]=oldepos;
  8251. destination[E_AXIS]=oldedes;
  8252. plan_set_e_position(oldepos);
  8253. previous_millis_cmd.start();
  8254. st_synchronize();
  8255. WRITE(E0_ENABLE_PIN,oldstatus);
  8256. }
  8257. #endif
  8258. check_axes_activity();
  8259. MMU2::mmu2.mmu_loop();
  8260. // handle longpress
  8261. if(lcd_longpress_trigger)
  8262. {
  8263. // long press is not possible in modal mode, wait until ready
  8264. if (lcd_longpress_func && lcd_update_enabled)
  8265. {
  8266. lcd_longpress_func();
  8267. lcd_longpress_trigger = 0;
  8268. }
  8269. }
  8270. #if defined(AUTO_REPORT)
  8271. host_autoreport();
  8272. #endif //AUTO_REPORT
  8273. host_keepalive();
  8274. }
  8275. void kill(const char *full_screen_message, unsigned char id)
  8276. {
  8277. printf_P(_N("KILL: %d\n"), id);
  8278. //return;
  8279. cli(); // Stop interrupts
  8280. disable_heater();
  8281. disable_x();
  8282. // SERIAL_ECHOLNPGM("kill - disable Y");
  8283. disable_y();
  8284. poweroff_z();
  8285. disable_e0();
  8286. disable_e1();
  8287. disable_e2();
  8288. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8289. pinMode(PS_ON_PIN,INPUT);
  8290. #endif
  8291. SERIAL_ERROR_START;
  8292. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8293. if (full_screen_message != NULL) {
  8294. SERIAL_ERRORLNRPGM(full_screen_message);
  8295. lcd_display_message_fullscreen_P(full_screen_message);
  8296. } else {
  8297. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8298. }
  8299. // FMC small patch to update the LCD before ending
  8300. sei(); // enable interrupts
  8301. for ( int i=5; i--; lcd_update(0))
  8302. {
  8303. _delay(200);
  8304. }
  8305. cli(); // disable interrupts
  8306. suicide();
  8307. while(1)
  8308. {
  8309. #ifdef WATCHDOG
  8310. wdt_reset();
  8311. #endif //WATCHDOG
  8312. /* Intentionally left empty */
  8313. } // Wait for reset
  8314. }
  8315. void UnconditionalStop()
  8316. {
  8317. CRITICAL_SECTION_START;
  8318. // Disable all heaters and unroll the temperature wait loop stack
  8319. disable_heater();
  8320. cancel_heatup = true;
  8321. heating_status = HeatingStatus::NO_HEATING;
  8322. // Clear any saved printing state
  8323. cancel_saved_printing();
  8324. // Abort the planner
  8325. planner_abort_hard();
  8326. // Reset the queue
  8327. cmdqueue_reset();
  8328. cmdqueue_serial_disabled = false;
  8329. // Reset the sd status
  8330. card.sdprinting = false;
  8331. card.closefile();
  8332. st_reset_timer();
  8333. CRITICAL_SECTION_END;
  8334. }
  8335. // Emergency stop used by overtemp functions which allows recovery
  8336. // WARNING: This function is called *continuously* during a thermal failure.
  8337. //
  8338. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8339. // "allow_recovery". If recovery is allowed, this forces a printer-initiated instantanenous pause
  8340. // (just like an LCD pause) that bypasses the host pausing functionality. In this state the printer
  8341. // is kept in busy state and *must* be recovered from the LCD.
  8342. void ThermalStop(bool allow_recovery)
  8343. {
  8344. if(Stopped == false) {
  8345. Stopped = true;
  8346. if(allow_recovery && (IS_SD_PRINTING || usb_timer.running())) {
  8347. if (!isPrintPaused) {
  8348. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8349. // we cannot make a distinction for the host here, the pause must be instantaneous
  8350. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8351. // disable heaters and save the original temperatures to saved_*, which will get
  8352. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8353. // original values after the pause handler is called.
  8354. float bed_temp = saved_bed_temperature;
  8355. float ext_temp = saved_extruder_temperature;
  8356. int fan_speed = saved_fan_speed;
  8357. lcd_pause_print();
  8358. saved_bed_temperature = bed_temp;
  8359. saved_extruder_temperature = ext_temp;
  8360. saved_fan_speed = fan_speed;
  8361. }
  8362. } else {
  8363. // We got a hard thermal error and/or there is no print going on. Just stop.
  8364. print_stop();
  8365. }
  8366. // Report the status on the serial, switch to a busy state
  8367. SERIAL_ERROR_START;
  8368. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8369. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8370. // higher-priority alert status message)
  8371. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8372. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8373. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8374. WRITE(BEEPER, HIGH);
  8375. // Always return to the status screen to ensure the NEW error is immediately shown.
  8376. lcd_return_to_status();
  8377. if(!allow_recovery) {
  8378. // prevent menu access for all fatal errors
  8379. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8380. }
  8381. }
  8382. }
  8383. bool IsStopped() { return Stopped; };
  8384. void finishAndDisableSteppers()
  8385. {
  8386. st_synchronize();
  8387. disable_x();
  8388. disable_y();
  8389. disable_z();
  8390. disable_e0();
  8391. disable_e1();
  8392. disable_e2();
  8393. #ifndef LA_NOCOMPAT
  8394. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8395. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8396. // state for the next print.
  8397. la10c_reset();
  8398. #endif
  8399. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8400. print_time_remaining_init();
  8401. }
  8402. #ifdef FAST_PWM_FAN
  8403. void setPwmFrequency(uint8_t pin, int val)
  8404. {
  8405. val &= 0x07;
  8406. switch(digitalPinToTimer(pin))
  8407. {
  8408. #if defined(TCCR0A)
  8409. case TIMER0A:
  8410. case TIMER0B:
  8411. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8412. // TCCR0B |= val;
  8413. break;
  8414. #endif
  8415. #if defined(TCCR1A)
  8416. case TIMER1A:
  8417. case TIMER1B:
  8418. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8419. // TCCR1B |= val;
  8420. break;
  8421. #endif
  8422. #if defined(TCCR2)
  8423. case TIMER2:
  8424. case TIMER2:
  8425. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8426. TCCR2 |= val;
  8427. break;
  8428. #endif
  8429. #if defined(TCCR2A)
  8430. case TIMER2A:
  8431. case TIMER2B:
  8432. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8433. TCCR2B |= val;
  8434. break;
  8435. #endif
  8436. #if defined(TCCR3A)
  8437. case TIMER3A:
  8438. case TIMER3B:
  8439. case TIMER3C:
  8440. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8441. TCCR3B |= val;
  8442. break;
  8443. #endif
  8444. #if defined(TCCR4A)
  8445. case TIMER4A:
  8446. case TIMER4B:
  8447. case TIMER4C:
  8448. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8449. TCCR4B |= val;
  8450. break;
  8451. #endif
  8452. #if defined(TCCR5A)
  8453. case TIMER5A:
  8454. case TIMER5B:
  8455. case TIMER5C:
  8456. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8457. TCCR5B |= val;
  8458. break;
  8459. #endif
  8460. }
  8461. }
  8462. #endif //FAST_PWM_FAN
  8463. //! @brief Get and validate extruder number
  8464. //!
  8465. //! If it is not specified, active_extruder is returned in parameter extruder.
  8466. //! @param [in] code M code number
  8467. //! @param [out] extruder
  8468. //! @return error
  8469. //! @retval true Invalid extruder specified in T code
  8470. //! @retval false Valid extruder specified in T code, or not specifiead
  8471. bool setTargetedHotend(int code, uint8_t &extruder)
  8472. {
  8473. extruder = active_extruder;
  8474. if(code_seen('T')) {
  8475. extruder = code_value_uint8();
  8476. if(extruder >= EXTRUDERS) {
  8477. SERIAL_ECHO_START;
  8478. serialprintPGM(PSTR("M"));
  8479. SERIAL_ECHO(code);
  8480. SERIAL_ECHOPGM(" Invalid extruder ");
  8481. SERIAL_PROTOCOLLN((int)extruder);
  8482. return true;
  8483. }
  8484. }
  8485. return false;
  8486. }
  8487. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) { //_total_filament_used unit: mm/100; print time in s
  8488. uint32_t _previous_filament = eeprom_init_default_dword((uint32_t *)EEPROM_FILAMENTUSED, 0); //_previous_filament unit: cm
  8489. uint32_t _previous_time = eeprom_init_default_dword((uint32_t *)EEPROM_TOTALTIME, 0); //_previous_time unit: min
  8490. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time / 60)); // EEPROM_TOTALTIME unit: min
  8491. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8492. total_filament_used = 0;
  8493. if (MMU2::mmu2.Enabled()) {
  8494. eeprom_add_dword((uint32_t *)EEPROM_TOTAL_TOOLCHANGE_COUNT, MMU2::mmu2.ToolChangeCounter());
  8495. // @@TODO why were EEPROM_MMU_FAIL_TOT and EEPROM_MMU_LOAD_FAIL_TOT behaving differently - i.e. updated with every change?
  8496. MMU2::mmu2.ClearToolChangeCounter();
  8497. MMU2::mmu2.ClearTMCFailures(); // not stored into EEPROM
  8498. }
  8499. }
  8500. float calculate_extruder_multiplier(float diameter) {
  8501. float out = 1.f;
  8502. if (cs.volumetric_enabled && diameter > 0.f) {
  8503. float area = M_PI * diameter * diameter * 0.25;
  8504. out = 1.f / area;
  8505. }
  8506. if (extrudemultiply != 100)
  8507. out *= float(extrudemultiply) * 0.01f;
  8508. return out;
  8509. }
  8510. void calculate_extruder_multipliers() {
  8511. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8512. #if EXTRUDERS > 1
  8513. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8514. #if EXTRUDERS > 2
  8515. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8516. #endif
  8517. #endif
  8518. }
  8519. void delay_keep_alive(unsigned int ms)
  8520. {
  8521. for (;;) {
  8522. manage_heater();
  8523. // Manage inactivity, but don't disable steppers on timeout.
  8524. manage_inactivity(true);
  8525. lcd_update(0);
  8526. if (ms == 0)
  8527. break;
  8528. else if (ms >= 50) {
  8529. _delay(50);
  8530. ms -= 50;
  8531. } else {
  8532. _delay(ms);
  8533. ms = 0;
  8534. }
  8535. }
  8536. }
  8537. static void wait_for_heater(long codenum, uint8_t extruder) {
  8538. if (!degTargetHotend(extruder))
  8539. return;
  8540. #ifdef TEMP_RESIDENCY_TIME
  8541. long residencyStart;
  8542. residencyStart = -1;
  8543. /* continue to loop until we have reached the target temp
  8544. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8545. cancel_heatup = false;
  8546. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8547. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8548. #else
  8549. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8550. #endif //TEMP_RESIDENCY_TIME
  8551. if ((_millis() - codenum) > 1000UL)
  8552. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8553. if (!farm_mode) {
  8554. SERIAL_PROTOCOLPGM("T:");
  8555. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8556. SERIAL_PROTOCOLPGM(" E:");
  8557. SERIAL_PROTOCOL((int)extruder);
  8558. #ifdef TEMP_RESIDENCY_TIME
  8559. SERIAL_PROTOCOLPGM(" W:");
  8560. if (residencyStart > -1)
  8561. {
  8562. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8563. SERIAL_PROTOCOLLN(codenum);
  8564. }
  8565. else
  8566. {
  8567. SERIAL_PROTOCOLLN('?');
  8568. }
  8569. }
  8570. #else
  8571. SERIAL_PROTOCOLLN();
  8572. #endif
  8573. codenum = _millis();
  8574. }
  8575. manage_heater();
  8576. manage_inactivity(true); //do not disable steppers
  8577. lcd_update(0);
  8578. #ifdef TEMP_RESIDENCY_TIME
  8579. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8580. or when current temp falls outside the hysteresis after target temp was reached */
  8581. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8582. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8583. (residencyStart > -1 && fabs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8584. {
  8585. residencyStart = _millis();
  8586. }
  8587. #endif //TEMP_RESIDENCY_TIME
  8588. }
  8589. }
  8590. void check_babystep()
  8591. {
  8592. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8593. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8594. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8595. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8596. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8597. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8598. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8599. babystep_z);
  8600. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8601. lcd_update_enable(true);
  8602. }
  8603. }
  8604. #ifdef HEATBED_ANALYSIS
  8605. void d_setup()
  8606. {
  8607. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8608. pinMode(D_DATA, INPUT_PULLUP);
  8609. pinMode(D_REQUIRE, OUTPUT);
  8610. digitalWrite(D_REQUIRE, HIGH);
  8611. }
  8612. float d_ReadData()
  8613. {
  8614. int digit[13];
  8615. String mergeOutput;
  8616. float output;
  8617. digitalWrite(D_REQUIRE, HIGH);
  8618. for (int i = 0; i<13; i++)
  8619. {
  8620. for (int j = 0; j < 4; j++)
  8621. {
  8622. while (digitalRead(D_DATACLOCK) == LOW) {}
  8623. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8624. bitWrite(digit[i], j, digitalRead(D_DATA));
  8625. }
  8626. }
  8627. digitalWrite(D_REQUIRE, LOW);
  8628. mergeOutput = "";
  8629. output = 0;
  8630. for (int r = 5; r <= 10; r++) //Merge digits
  8631. {
  8632. mergeOutput += digit[r];
  8633. }
  8634. output = mergeOutput.toFloat();
  8635. if (digit[4] == 8) //Handle sign
  8636. {
  8637. output *= -1;
  8638. }
  8639. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8640. {
  8641. output /= 10;
  8642. }
  8643. return output;
  8644. }
  8645. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8646. int t1 = 0;
  8647. int t_delay = 0;
  8648. int digit[13];
  8649. int m;
  8650. char str[3];
  8651. //String mergeOutput;
  8652. char mergeOutput[15];
  8653. float output;
  8654. int mesh_point = 0; //index number of calibration point
  8655. float bed_zero_ref_x = (-22.f + X_PROBE_OFFSET_FROM_EXTRUDER); //shift between zero point on bed and target and between probe and nozzle
  8656. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8657. float mesh_home_z_search = 4;
  8658. float measure_z_height = 0.2f;
  8659. float row[x_points_num];
  8660. int ix = 0;
  8661. int iy = 0;
  8662. const char* filename_wldsd = "mesh.txt";
  8663. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8664. char numb_wldsd[8]; // (" -A.BCD" + null)
  8665. #ifdef MICROMETER_LOGGING
  8666. d_setup();
  8667. #endif //MICROMETER_LOGGING
  8668. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8669. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8670. unsigned int custom_message_type_old = custom_message_type;
  8671. unsigned int custom_message_state_old = custom_message_state;
  8672. custom_message_type = CustomMsg::MeshBedLeveling;
  8673. custom_message_state = (x_points_num * y_points_num) + 10;
  8674. lcd_update(1);
  8675. //mbl.reset();
  8676. babystep_undo();
  8677. card.openFile(filename_wldsd, false);
  8678. /*destination[Z_AXIS] = mesh_home_z_search;
  8679. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8680. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8681. for(int8_t i=0; i < NUM_AXIS; i++) {
  8682. current_position[i] = destination[i];
  8683. }
  8684. st_synchronize();
  8685. */
  8686. destination[Z_AXIS] = measure_z_height;
  8687. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8688. for(int8_t i=0; i < NUM_AXIS; i++) {
  8689. current_position[i] = destination[i];
  8690. }
  8691. st_synchronize();
  8692. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8693. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8694. SERIAL_PROTOCOL(x_points_num);
  8695. SERIAL_PROTOCOLPGM(",");
  8696. SERIAL_PROTOCOL(y_points_num);
  8697. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8698. SERIAL_PROTOCOL(mesh_home_z_search);
  8699. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8700. SERIAL_PROTOCOL(x_dimension);
  8701. SERIAL_PROTOCOLPGM(",");
  8702. SERIAL_PROTOCOL(y_dimension);
  8703. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8704. while (mesh_point != x_points_num * y_points_num) {
  8705. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8706. iy = mesh_point / x_points_num;
  8707. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8708. float z0 = 0.f;
  8709. /*destination[Z_AXIS] = mesh_home_z_search;
  8710. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8711. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8712. for(int8_t i=0; i < NUM_AXIS; i++) {
  8713. current_position[i] = destination[i];
  8714. }
  8715. st_synchronize();*/
  8716. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8717. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8718. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8719. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8720. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8721. set_current_to_destination();
  8722. st_synchronize();
  8723. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8724. delay_keep_alive(1000);
  8725. #ifdef MICROMETER_LOGGING
  8726. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8727. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8728. //strcat(data_wldsd, numb_wldsd);
  8729. //MYSERIAL.println(data_wldsd);
  8730. //delay(1000);
  8731. //delay(3000);
  8732. //t1 = millis();
  8733. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8734. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8735. memset(digit, 0, sizeof(digit));
  8736. //cli();
  8737. digitalWrite(D_REQUIRE, LOW);
  8738. for (int i = 0; i<13; i++)
  8739. {
  8740. //t1 = millis();
  8741. for (int j = 0; j < 4; j++)
  8742. {
  8743. while (digitalRead(D_DATACLOCK) == LOW) {}
  8744. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8745. //printf_P(PSTR("Done %d\n"), j);
  8746. bitWrite(digit[i], j, digitalRead(D_DATA));
  8747. }
  8748. //t_delay = (millis() - t1);
  8749. //SERIAL_PROTOCOLPGM(" ");
  8750. //SERIAL_PROTOCOL_F(t_delay, 5);
  8751. //SERIAL_PROTOCOLPGM(" ");
  8752. }
  8753. //sei();
  8754. digitalWrite(D_REQUIRE, HIGH);
  8755. mergeOutput[0] = '\0';
  8756. output = 0;
  8757. for (int r = 5; r <= 10; r++) //Merge digits
  8758. {
  8759. sprintf(str, "%d", digit[r]);
  8760. strcat(mergeOutput, str);
  8761. }
  8762. output = atof(mergeOutput);
  8763. if (digit[4] == 8) //Handle sign
  8764. {
  8765. output *= -1;
  8766. }
  8767. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8768. {
  8769. output *= 0.1;
  8770. }
  8771. //output = d_ReadData();
  8772. //row[ix] = current_position[Z_AXIS];
  8773. //row[ix] = d_ReadData();
  8774. row[ix] = output;
  8775. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8776. memset(data_wldsd, 0, sizeof(data_wldsd));
  8777. for (int i = 0; i < x_points_num; i++) {
  8778. SERIAL_PROTOCOLPGM(" ");
  8779. SERIAL_PROTOCOL_F(row[i], 5);
  8780. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8781. dtostrf(row[i], 7, 3, numb_wldsd);
  8782. strcat(data_wldsd, numb_wldsd);
  8783. }
  8784. card.write_command(data_wldsd);
  8785. SERIAL_PROTOCOLPGM("\n");
  8786. }
  8787. custom_message_state--;
  8788. mesh_point++;
  8789. lcd_update(1);
  8790. }
  8791. #endif //MICROMETER_LOGGING
  8792. card.closefile();
  8793. //clean_up_after_endstop_move(l_feedmultiply);
  8794. }
  8795. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8796. int t1 = 0;
  8797. int t_delay = 0;
  8798. int digit[13];
  8799. int m;
  8800. char str[3];
  8801. //String mergeOutput;
  8802. char mergeOutput[15];
  8803. float output;
  8804. int mesh_point = 0; //index number of calibration point
  8805. float bed_zero_ref_x = (-22.f + X_PROBE_OFFSET_FROM_EXTRUDER); //shift between zero point on bed and target and between probe and nozzle
  8806. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8807. float mesh_home_z_search = 4;
  8808. float row[x_points_num];
  8809. int ix = 0;
  8810. int iy = 0;
  8811. const char* filename_wldsd = "wldsd.txt";
  8812. char data_wldsd[70];
  8813. char numb_wldsd[10];
  8814. d_setup();
  8815. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8816. // We don't know where we are! HOME!
  8817. // Push the commands to the front of the message queue in the reverse order!
  8818. // There shall be always enough space reserved for these commands.
  8819. repeatcommand_front(); // repeat G80 with all its parameters
  8820. enquecommand_front_P(G28W0);
  8821. enquecommand_front_P((PSTR("G1 Z5")));
  8822. return;
  8823. }
  8824. unsigned int custom_message_type_old = custom_message_type;
  8825. unsigned int custom_message_state_old = custom_message_state;
  8826. custom_message_type = CustomMsg::MeshBedLeveling;
  8827. custom_message_state = (x_points_num * y_points_num) + 10;
  8828. lcd_update(1);
  8829. mbl.reset();
  8830. babystep_undo();
  8831. card.openFile(filename_wldsd, false);
  8832. current_position[Z_AXIS] = mesh_home_z_search;
  8833. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8834. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8835. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8836. int l_feedmultiply = setup_for_endstop_move(false);
  8837. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8838. SERIAL_PROTOCOL(x_points_num);
  8839. SERIAL_PROTOCOLPGM(",");
  8840. SERIAL_PROTOCOL(y_points_num);
  8841. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8842. SERIAL_PROTOCOL(mesh_home_z_search);
  8843. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8844. SERIAL_PROTOCOL(x_dimension);
  8845. SERIAL_PROTOCOLPGM(",");
  8846. SERIAL_PROTOCOL(y_dimension);
  8847. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8848. while (mesh_point != x_points_num * y_points_num) {
  8849. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8850. iy = mesh_point / x_points_num;
  8851. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8852. float z0 = 0.f;
  8853. current_position[Z_AXIS] = mesh_home_z_search;
  8854. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8855. st_synchronize();
  8856. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8857. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8858. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8859. st_synchronize();
  8860. if (!find_bed_induction_sensor_point_z(-10.f)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  8861. break;
  8862. card.closefile();
  8863. }
  8864. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8865. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8866. //strcat(data_wldsd, numb_wldsd);
  8867. //MYSERIAL.println(data_wldsd);
  8868. //_delay(1000);
  8869. //_delay(3000);
  8870. //t1 = _millis();
  8871. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8872. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8873. memset(digit, 0, sizeof(digit));
  8874. //cli();
  8875. digitalWrite(D_REQUIRE, LOW);
  8876. for (int i = 0; i<13; i++)
  8877. {
  8878. //t1 = _millis();
  8879. for (int j = 0; j < 4; j++)
  8880. {
  8881. while (digitalRead(D_DATACLOCK) == LOW) {}
  8882. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8883. bitWrite(digit[i], j, digitalRead(D_DATA));
  8884. }
  8885. //t_delay = (_millis() - t1);
  8886. //SERIAL_PROTOCOLPGM(" ");
  8887. //SERIAL_PROTOCOL_F(t_delay, 5);
  8888. //SERIAL_PROTOCOLPGM(" ");
  8889. }
  8890. //sei();
  8891. digitalWrite(D_REQUIRE, HIGH);
  8892. mergeOutput[0] = '\0';
  8893. output = 0;
  8894. for (int r = 5; r <= 10; r++) //Merge digits
  8895. {
  8896. sprintf(str, "%d", digit[r]);
  8897. strcat(mergeOutput, str);
  8898. }
  8899. output = atof(mergeOutput);
  8900. if (digit[4] == 8) //Handle sign
  8901. {
  8902. output *= -1;
  8903. }
  8904. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8905. {
  8906. output *= 0.1;
  8907. }
  8908. //output = d_ReadData();
  8909. //row[ix] = current_position[Z_AXIS];
  8910. memset(data_wldsd, 0, sizeof(data_wldsd));
  8911. for (int i = 0; i <3; i++) {
  8912. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8913. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8914. strcat(data_wldsd, numb_wldsd);
  8915. strcat(data_wldsd, ";");
  8916. }
  8917. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8918. dtostrf(output, 8, 5, numb_wldsd);
  8919. strcat(data_wldsd, numb_wldsd);
  8920. //strcat(data_wldsd, ";");
  8921. card.write_command(data_wldsd);
  8922. //row[ix] = d_ReadData();
  8923. row[ix] = output; // current_position[Z_AXIS];
  8924. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8925. for (int i = 0; i < x_points_num; i++) {
  8926. SERIAL_PROTOCOLPGM(" ");
  8927. SERIAL_PROTOCOL_F(row[i], 5);
  8928. }
  8929. SERIAL_PROTOCOLPGM("\n");
  8930. }
  8931. custom_message_state--;
  8932. mesh_point++;
  8933. lcd_update(1);
  8934. }
  8935. card.closefile();
  8936. clean_up_after_endstop_move(l_feedmultiply);
  8937. }
  8938. #endif //HEATBED_ANALYSIS
  8939. #ifndef PINDA_THERMISTOR
  8940. static void temp_compensation_start() {
  8941. custom_message_type = CustomMsg::TempCompPreheat;
  8942. custom_message_state = PINDA_HEAT_T + 1;
  8943. lcd_update(2);
  8944. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8945. current_position[E_AXIS] -= default_retraction;
  8946. }
  8947. plan_buffer_line_curposXYZE(400, active_extruder);
  8948. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8949. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8950. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8951. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8952. st_synchronize();
  8953. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8954. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8955. delay_keep_alive(1000);
  8956. custom_message_state = PINDA_HEAT_T - i;
  8957. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8958. else lcd_update(1);
  8959. }
  8960. custom_message_type = CustomMsg::Status;
  8961. custom_message_state = 0;
  8962. }
  8963. static void temp_compensation_apply() {
  8964. int i_add;
  8965. int z_shift = 0;
  8966. float z_shift_mm;
  8967. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8968. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8969. i_add = (target_temperature_bed - 60) / 10;
  8970. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  8971. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8972. }else {
  8973. //interpolation
  8974. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8975. }
  8976. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8977. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] - z_shift_mm, current_position[E_AXIS], homing_feedrate[Z_AXIS] / 40, active_extruder);
  8978. st_synchronize();
  8979. plan_set_z_position(current_position[Z_AXIS]);
  8980. }
  8981. else {
  8982. //we have no temp compensation data
  8983. }
  8984. }
  8985. #endif //ndef PINDA_THERMISTOR
  8986. float temp_comp_interpolation(float inp_temperature) {
  8987. //cubic spline interpolation
  8988. int n, i, j;
  8989. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8990. int shift[10];
  8991. int temp_C[10];
  8992. n = 6; //number of measured points
  8993. shift[0] = 0;
  8994. for (i = 0; i < n; i++) {
  8995. if (i > 0) {
  8996. //read shift in steps from EEPROM
  8997. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  8998. }
  8999. temp_C[i] = 50 + i * 10; //temperature in C
  9000. #ifdef PINDA_THERMISTOR
  9001. constexpr int start_compensating_temp = 35;
  9002. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  9003. #ifdef SUPERPINDA_SUPPORT
  9004. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  9005. #endif //SUPERPINDA_SUPPORT
  9006. #else
  9007. temp_C[i] = 50 + i * 10; //temperature in C
  9008. #endif
  9009. x[i] = (float)temp_C[i];
  9010. f[i] = (float)shift[i];
  9011. }
  9012. if (inp_temperature < x[0]) return 0;
  9013. for (i = n - 1; i>0; i--) {
  9014. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9015. h[i - 1] = x[i] - x[i - 1];
  9016. }
  9017. //*********** formation of h, s , f matrix **************
  9018. for (i = 1; i<n - 1; i++) {
  9019. m[i][i] = 2 * (h[i - 1] + h[i]);
  9020. if (i != 1) {
  9021. m[i][i - 1] = h[i - 1];
  9022. m[i - 1][i] = h[i - 1];
  9023. }
  9024. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9025. }
  9026. //*********** forward elimination **************
  9027. for (i = 1; i<n - 2; i++) {
  9028. temp = (m[i + 1][i] / m[i][i]);
  9029. for (j = 1; j <= n - 1; j++)
  9030. m[i + 1][j] -= temp*m[i][j];
  9031. }
  9032. //*********** backward substitution *********
  9033. for (i = n - 2; i>0; i--) {
  9034. sum = 0;
  9035. for (j = i; j <= n - 2; j++)
  9036. sum += m[i][j] * s[j];
  9037. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9038. }
  9039. for (i = 0; i<n - 1; i++)
  9040. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9041. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9042. b = s[i] / 2;
  9043. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9044. d = f[i];
  9045. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9046. }
  9047. return sum;
  9048. }
  9049. #ifdef PINDA_THERMISTOR
  9050. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9051. {
  9052. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9053. if (!calibration_status_pinda()) return 0;
  9054. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9055. }
  9056. #endif //PINDA_THERMISTOR
  9057. void long_pause() //long pause print
  9058. {
  9059. st_synchronize();
  9060. start_pause_print = _millis();
  9061. // Stop heaters
  9062. heating_status = HeatingStatus::NO_HEATING;
  9063. setAllTargetHotends(0);
  9064. // Lift z
  9065. raise_z(Z_PAUSE_LIFT);
  9066. // Move XY to side
  9067. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9068. current_position[X_AXIS] = X_PAUSE_POS;
  9069. current_position[Y_AXIS] = Y_PAUSE_POS;
  9070. plan_buffer_line_curposXYZE(50);
  9071. }
  9072. // did we come here from a thermal error?
  9073. if(get_temp_error()) {
  9074. // time to stop the error beep
  9075. WRITE(BEEPER, LOW);
  9076. } else {
  9077. // Turn off the print fan
  9078. fanSpeed = 0;
  9079. }
  9080. }
  9081. void serialecho_temperatures() {
  9082. float tt = degHotend(active_extruder);
  9083. SERIAL_PROTOCOLPGM("T:");
  9084. SERIAL_PROTOCOL(tt);
  9085. SERIAL_PROTOCOLPGM(" E:");
  9086. SERIAL_PROTOCOL((int)active_extruder);
  9087. SERIAL_PROTOCOLPGM(" B:");
  9088. SERIAL_PROTOCOL_F(degBed(), 1);
  9089. SERIAL_PROTOCOLLN();
  9090. }
  9091. #ifdef UVLO_SUPPORT
  9092. void uvlo_drain_reset()
  9093. {
  9094. // burn all that residual power
  9095. wdt_enable(WDTO_1S);
  9096. WRITE(BEEPER,HIGH);
  9097. lcd_clear();
  9098. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9099. while(1);
  9100. }
  9101. void uvlo_()
  9102. {
  9103. unsigned long time_start = _millis();
  9104. bool sd_print = card.sdprinting;
  9105. // Conserve power as soon as possible.
  9106. #ifdef LCD_BL_PIN
  9107. backlightMode = BACKLIGHT_MODE_DIM;
  9108. backlightLevel_LOW = 0;
  9109. backlight_update();
  9110. #endif //LCD_BL_PIN
  9111. disable_x();
  9112. disable_y();
  9113. #ifdef TMC2130
  9114. tmc2130_set_current_h(Z_AXIS, 20);
  9115. tmc2130_set_current_r(Z_AXIS, 20);
  9116. tmc2130_set_current_h(E_AXIS, 20);
  9117. tmc2130_set_current_r(E_AXIS, 20);
  9118. #endif //TMC2130
  9119. // Stop all heaters
  9120. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9121. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9122. setAllTargetHotends(0);
  9123. setTargetBed(0);
  9124. // Calculate the file position, from which to resume this print.
  9125. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9126. {
  9127. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9128. sd_position -= sdlen_planner;
  9129. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9130. sd_position -= sdlen_cmdqueue;
  9131. if (sd_position < 0) sd_position = 0;
  9132. }
  9133. // save the global state at planning time
  9134. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9135. uint16_t feedrate_bckp;
  9136. if (current_block && !pos_invalid)
  9137. {
  9138. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9139. feedrate_bckp = current_block->gcode_feedrate;
  9140. saved_segment_idx = current_block->segment_idx;
  9141. }
  9142. else
  9143. {
  9144. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9145. feedrate_bckp = feedrate;
  9146. saved_segment_idx = 0;
  9147. }
  9148. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9149. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9150. // get the physical Z for further manipulation.
  9151. bool mbl_was_active = mbl.active;
  9152. mbl.active = false;
  9153. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9154. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9155. // are in action.
  9156. planner_abort_hard();
  9157. // Store the print logical Z position, which we need to recover (a slight error here would be
  9158. // recovered on the next Gcode instruction, while a physical location error would not)
  9159. float logical_z = current_position[Z_AXIS];
  9160. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9161. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9162. // Store the print E position before we lose track
  9163. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9164. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9165. // Clean the input command queue, inhibit serial processing using saved_printing
  9166. cmdqueue_reset();
  9167. card.sdprinting = false;
  9168. saved_printing = true;
  9169. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9170. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9171. planner_aborted = false;
  9172. sei();
  9173. // Retract
  9174. current_position[E_AXIS] -= default_retraction;
  9175. plan_buffer_line_curposXYZE(95);
  9176. st_synchronize();
  9177. disable_e0();
  9178. // Read out the current Z motor microstep counter to move the axis up towards
  9179. // a full step before powering off. NOTE: we need to ensure to schedule more
  9180. // than "dropsegments" steps in order to move (this is always the case here
  9181. // due to UVLO_Z_AXIS_SHIFT being used)
  9182. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9183. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9184. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9185. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9186. + UVLO_Z_AXIS_SHIFT;
  9187. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9188. st_synchronize();
  9189. poweroff_z();
  9190. // Write the file position.
  9191. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9192. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9193. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9194. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9195. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9196. // Scale the z value to 1u resolution.
  9197. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9198. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9199. }
  9200. // Write the _final_ Z position and motor microstep counter (unused).
  9201. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9202. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9203. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9204. // Store the current position.
  9205. if (pos_invalid)
  9206. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9207. else
  9208. {
  9209. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9210. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9211. }
  9212. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9213. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9214. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9215. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9216. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9217. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9218. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9219. #if EXTRUDERS > 1
  9220. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9221. #if EXTRUDERS > 2
  9222. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9223. #endif
  9224. #endif
  9225. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9226. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9227. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9228. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9229. // Store the saved target
  9230. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9231. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9232. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9233. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9234. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9235. #ifdef LIN_ADVANCE
  9236. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9237. #endif
  9238. // Finaly store the "power outage" flag.
  9239. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9240. // Increment power failure counter
  9241. eeprom_increment_byte((uint8_t*)EEPROM_POWER_COUNT);
  9242. eeprom_increment_word((uint16_t*)EEPROM_POWER_COUNT_TOT);
  9243. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9244. WRITE(BEEPER,HIGH);
  9245. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9246. poweron_z();
  9247. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9248. plan_buffer_line_curposXYZE(500);
  9249. st_synchronize();
  9250. wdt_enable(WDTO_1S);
  9251. while(1);
  9252. }
  9253. void uvlo_tiny()
  9254. {
  9255. unsigned long time_start = _millis();
  9256. // Conserve power as soon as possible.
  9257. disable_x();
  9258. disable_y();
  9259. disable_e0();
  9260. #ifdef TMC2130
  9261. tmc2130_set_current_h(Z_AXIS, 20);
  9262. tmc2130_set_current_r(Z_AXIS, 20);
  9263. #endif //TMC2130
  9264. // Stop all heaters
  9265. setAllTargetHotends(0);
  9266. setTargetBed(0);
  9267. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9268. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9269. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9270. // Disable MBL (if not already) to work with physical coordinates.
  9271. mbl.active = false;
  9272. planner_abort_hard();
  9273. // Allow for small roundoffs to be ignored
  9274. if(fabs(current_position[Z_AXIS] - eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))) >= 1.f/cs.axis_steps_per_unit[Z_AXIS])
  9275. {
  9276. // Clean the input command queue, inhibit serial processing using saved_printing
  9277. cmdqueue_reset();
  9278. card.sdprinting = false;
  9279. saved_printing = true;
  9280. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9281. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9282. planner_aborted = false;
  9283. sei();
  9284. // The axis was moved: adjust Z as done on a regular UVLO.
  9285. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9286. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9287. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9288. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9289. + UVLO_TINY_Z_AXIS_SHIFT;
  9290. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9291. st_synchronize();
  9292. poweroff_z();
  9293. // Update Z position
  9294. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9295. // Update the _final_ Z motor microstep counter (unused).
  9296. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9297. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9298. }
  9299. // Update the the "power outage" flag.
  9300. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9301. // Increment power failure counter
  9302. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9303. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9304. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9305. uvlo_drain_reset();
  9306. }
  9307. #endif //UVLO_SUPPORT
  9308. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9309. void setup_fan_interrupt() {
  9310. //INT7
  9311. DDRE &= ~(1 << 7); //input pin
  9312. PORTE &= ~(1 << 7); //no internal pull-up
  9313. //start with sensing rising edge
  9314. EICRB &= ~(1 << 6);
  9315. EICRB |= (1 << 7);
  9316. //enable INT7 interrupt
  9317. EIMSK |= (1 << 7);
  9318. }
  9319. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9320. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9321. ISR(INT7_vect) {
  9322. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9323. #ifdef FAN_SOFT_PWM
  9324. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9325. #else //FAN_SOFT_PWM
  9326. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9327. #endif //FAN_SOFT_PWM
  9328. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9329. t_fan_rising_edge = millis_nc();
  9330. }
  9331. else { //interrupt was triggered by falling edge
  9332. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9333. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9334. }
  9335. }
  9336. EICRB ^= (1 << 6); //change edge
  9337. }
  9338. #endif
  9339. #ifdef UVLO_SUPPORT
  9340. void setup_uvlo_interrupt() {
  9341. DDRE &= ~(1 << 4); //input pin
  9342. PORTE &= ~(1 << 4); //no internal pull-up
  9343. // sensing falling edge
  9344. EICRB |= (1 << 0);
  9345. EICRB &= ~(1 << 1);
  9346. // enable INT4 interrupt
  9347. EIMSK |= (1 << 4);
  9348. // check if power was lost before we armed the interrupt
  9349. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9350. {
  9351. SERIAL_ECHOLNPGM("INT4");
  9352. uvlo_drain_reset();
  9353. }
  9354. }
  9355. ISR(INT4_vect) {
  9356. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9357. SERIAL_ECHOLNPGM("INT4");
  9358. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9359. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9360. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9361. }
  9362. void recover_print(uint8_t automatic) {
  9363. char cmd[30];
  9364. lcd_update_enable(true);
  9365. lcd_update(2);
  9366. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9367. // Recover position, temperatures and extrude_multipliers
  9368. bool mbl_was_active = recover_machine_state_after_power_panic();
  9369. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9370. // and second also so one may remove the excess priming material.
  9371. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9372. {
  9373. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9374. enquecommand(cmd);
  9375. }
  9376. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9377. // transformation status. G28 will not touch Z when MBL is off.
  9378. enquecommand_P(PSTR("G28 X Y"));
  9379. // Set the target bed and nozzle temperatures and wait.
  9380. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9381. enquecommand(cmd);
  9382. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9383. enquecommand(cmd);
  9384. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9385. enquecommand(cmd);
  9386. enquecommand_P(PSTR("M83")); //E axis relative mode
  9387. // If not automatically recoreverd (long power loss)
  9388. if(automatic == 0){
  9389. //Extrude some filament to stabilize the pressure
  9390. enquecommand_P(PSTR("G1 E5 F120"));
  9391. // Retract to be consistent with a short pause
  9392. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9393. enquecommand(cmd);
  9394. }
  9395. printf_P(_N("After waiting for temp:\nCurrent pos X_AXIS:%.3f\nCurrent pos Y_AXIS:%.3f\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  9396. // Restart the print.
  9397. restore_print_from_eeprom(mbl_was_active);
  9398. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9399. }
  9400. bool recover_machine_state_after_power_panic()
  9401. {
  9402. // 1) Preset some dummy values for the XY axes
  9403. current_position[X_AXIS] = 0;
  9404. current_position[Y_AXIS] = 0;
  9405. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9406. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9407. bool mbl_was_active = false;
  9408. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9409. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9410. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9411. // Scale the z value to 10u resolution.
  9412. int16_t v;
  9413. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9414. if (v != 0)
  9415. mbl_was_active = true;
  9416. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9417. }
  9418. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9419. // The current position after power panic is moved to the next closest 0th full step.
  9420. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9421. // Recover last E axis position
  9422. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9423. // 3) Initialize the logical to physical coordinate system transformation.
  9424. world2machine_initialize();
  9425. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9426. // print_mesh_bed_leveling_table();
  9427. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9428. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9429. babystep_load();
  9430. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9431. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9432. clamp_to_software_endstops(current_position);
  9433. set_destination_to_current();
  9434. plan_set_position_curposXYZE();
  9435. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9436. print_world_coordinates();
  9437. // 6) Power up the Z motors, mark their positions as known.
  9438. axis_known_position[Z_AXIS] = true;
  9439. enable_z();
  9440. // 7) Recover the target temperatures.
  9441. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9442. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9443. // 8) Recover extruder multipilers
  9444. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9445. #if EXTRUDERS > 1
  9446. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9447. #if EXTRUDERS > 2
  9448. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9449. #endif
  9450. #endif
  9451. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9452. // 9) Recover the saved target
  9453. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9454. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9455. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9456. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9457. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9458. #ifdef LIN_ADVANCE
  9459. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9460. #endif
  9461. return mbl_was_active;
  9462. }
  9463. void restore_print_from_eeprom(bool mbl_was_active) {
  9464. int feedrate_rec;
  9465. int feedmultiply_rec;
  9466. uint8_t fan_speed_rec;
  9467. char cmd[48];
  9468. char filename[FILENAME_LENGTH];
  9469. uint8_t depth = 0;
  9470. char dir_name[9];
  9471. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9472. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9473. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9474. SERIAL_ECHOPGM("Feedrate:");
  9475. MYSERIAL.print(feedrate_rec);
  9476. SERIAL_ECHOPGM(", feedmultiply:");
  9477. MYSERIAL.println(feedmultiply_rec);
  9478. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9479. MYSERIAL.println(int(depth));
  9480. for (uint8_t i = 0; i < depth; i++) {
  9481. for (uint8_t j = 0; j < 8; j++) {
  9482. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9483. }
  9484. dir_name[8] = '\0';
  9485. MYSERIAL.println(dir_name);
  9486. // strcpy(card.dir_names[i], dir_name);
  9487. card.chdir(dir_name, false);
  9488. }
  9489. for (uint8_t i = 0; i < 8; i++) {
  9490. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9491. }
  9492. filename[8] = '\0';
  9493. MYSERIAL.print(filename);
  9494. strcat_P(filename, PSTR(".gco"));
  9495. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9496. enquecommand(cmd);
  9497. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9498. SERIAL_ECHOPGM("Position read from eeprom:");
  9499. MYSERIAL.println(position);
  9500. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9501. // without shifting Z along the way. This requires performing the move without mbl.
  9502. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9503. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9504. if (pos_x != X_COORD_INVALID)
  9505. {
  9506. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9507. enquecommand(cmd);
  9508. }
  9509. // Enable MBL and switch to logical positioning
  9510. if (mbl_was_active)
  9511. enquecommand_P(PSTR("PRUSA MBL V1"));
  9512. // Move the Z axis down to the print, in logical coordinates.
  9513. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9514. enquecommand(cmd);
  9515. // Restore acceleration settings
  9516. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9517. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9518. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9519. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9520. enquecommand(cmd);
  9521. // Unretract.
  9522. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9523. enquecommand(cmd);
  9524. // Recover final E axis position and mode
  9525. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9526. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9527. enquecommand(cmd);
  9528. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9529. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9530. // Set the feedrates saved at the power panic.
  9531. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9532. enquecommand(cmd);
  9533. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9534. enquecommand(cmd);
  9535. // Set the fan speed saved at the power panic.
  9536. sprintf_P(cmd, PSTR("M106 S%u"), fan_speed_rec);
  9537. enquecommand(cmd);
  9538. // Set a position in the file.
  9539. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9540. enquecommand(cmd);
  9541. enquecommand_P(PSTR("G4 S0"));
  9542. enquecommand_P(PSTR("PRUSA uvlo"));
  9543. }
  9544. #endif //UVLO_SUPPORT
  9545. //! @brief Immediately stop print moves
  9546. //!
  9547. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9548. //! If printing from sd card, position in file is saved.
  9549. //! If printing from USB, line number is saved.
  9550. //!
  9551. //! @param z_move
  9552. //! @param e_move
  9553. void stop_and_save_print_to_ram(float z_move, float e_move)
  9554. {
  9555. if (saved_printing) return;
  9556. #if 0
  9557. unsigned char nplanner_blocks;
  9558. #endif
  9559. unsigned char nlines;
  9560. uint16_t sdlen_planner;
  9561. uint16_t sdlen_cmdqueue;
  9562. cli();
  9563. if (card.sdprinting) {
  9564. #if 0
  9565. nplanner_blocks = number_of_blocks();
  9566. #endif
  9567. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9568. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9569. saved_sdpos -= sdlen_planner;
  9570. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9571. saved_sdpos -= sdlen_cmdqueue;
  9572. saved_printing_type = PRINTING_TYPE_SD;
  9573. }
  9574. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9575. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9576. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9577. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9578. saved_sdpos -= nlines;
  9579. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9580. saved_printing_type = PRINTING_TYPE_USB;
  9581. }
  9582. else {
  9583. saved_printing_type = PRINTING_TYPE_NONE;
  9584. //not sd printing nor usb printing
  9585. }
  9586. #if 0
  9587. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9588. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9589. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9590. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9591. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9592. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9593. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9594. {
  9595. card.setIndex(saved_sdpos);
  9596. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9597. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9598. MYSERIAL.print(char(card.get()));
  9599. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9600. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9601. MYSERIAL.print(char(card.get()));
  9602. SERIAL_ECHOLNPGM("End of command buffer");
  9603. }
  9604. {
  9605. // Print the content of the planner buffer, line by line:
  9606. card.setIndex(saved_sdpos);
  9607. int8_t iline = 0;
  9608. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9609. SERIAL_ECHOPGM("Planner line (from file): ");
  9610. MYSERIAL.print(int(iline), DEC);
  9611. SERIAL_ECHOPGM(", length: ");
  9612. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9613. SERIAL_ECHOPGM(", steps: (");
  9614. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9615. SERIAL_ECHOPGM(",");
  9616. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9617. SERIAL_ECHOPGM(",");
  9618. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9619. SERIAL_ECHOPGM(",");
  9620. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9621. SERIAL_ECHOPGM("), events: ");
  9622. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9623. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9624. MYSERIAL.print(char(card.get()));
  9625. }
  9626. }
  9627. {
  9628. // Print the content of the command buffer, line by line:
  9629. int8_t iline = 0;
  9630. union {
  9631. struct {
  9632. char lo;
  9633. char hi;
  9634. } lohi;
  9635. uint16_t value;
  9636. } sdlen_single;
  9637. int _bufindr = bufindr;
  9638. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9639. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9640. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9641. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9642. }
  9643. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9644. MYSERIAL.print(int(iline), DEC);
  9645. SERIAL_ECHOPGM(", type: ");
  9646. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9647. SERIAL_ECHOPGM(", len: ");
  9648. MYSERIAL.println(sdlen_single.value, DEC);
  9649. // Print the content of the buffer line.
  9650. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9651. SERIAL_ECHOPGM("Buffer line (from file): ");
  9652. MYSERIAL.println(int(iline), DEC);
  9653. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9654. MYSERIAL.print(char(card.get()));
  9655. if (-- _buflen == 0)
  9656. break;
  9657. // First skip the current command ID and iterate up to the end of the string.
  9658. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9659. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9660. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9661. // If the end of the buffer was empty,
  9662. if (_bufindr == sizeof(cmdbuffer)) {
  9663. // skip to the start and find the nonzero command.
  9664. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9665. }
  9666. }
  9667. }
  9668. #endif
  9669. // save the global state at planning time
  9670. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9671. if (current_block && !pos_invalid)
  9672. {
  9673. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9674. saved_feedrate2 = current_block->gcode_feedrate;
  9675. saved_segment_idx = current_block->segment_idx;
  9676. // printf_P(PSTR("stop_and_save_print_to_ram: %f, %f, %f, %f, %u\n"), saved_start_position[0], saved_start_position[1], saved_start_position[2], saved_start_position[3], saved_segment_idx);
  9677. }
  9678. else
  9679. {
  9680. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9681. saved_feedrate2 = feedrate;
  9682. saved_segment_idx = 0;
  9683. }
  9684. planner_abort_hard(); //abort printing
  9685. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9686. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9687. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9688. saved_extruder_temperature = degTargetHotend(active_extruder);
  9689. saved_bed_temperature = degTargetBed();
  9690. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9691. saved_fan_speed = fanSpeed;
  9692. cmdqueue_reset(); //empty cmdqueue
  9693. card.sdprinting = false;
  9694. // card.closefile();
  9695. saved_printing = true;
  9696. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9697. st_reset_timer();
  9698. sei();
  9699. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9700. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9701. // the caller can continue processing. This is used during powerpanic to save the state as we
  9702. // move away from the print.
  9703. char buf[48];
  9704. if(e_move)
  9705. {
  9706. // First unretract (relative extrusion)
  9707. if(!saved_extruder_relative_mode){
  9708. enquecommand(PSTR("M83"), true);
  9709. }
  9710. //retract 45mm/s
  9711. // A single sprintf may not be faster, but is definitely 20B shorter
  9712. // than a sequence of commands building the string piece by piece
  9713. // A snprintf would have been a safer call, but since it is not used
  9714. // in the whole program, its implementation would bring more bytes to the total size
  9715. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9716. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9717. enquecommand(buf, false);
  9718. }
  9719. if(z_move)
  9720. {
  9721. // Then lift Z axis
  9722. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9723. enquecommand(buf, false);
  9724. }
  9725. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9726. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9727. repeatcommand_front();
  9728. }
  9729. }
  9730. void restore_extruder_temperature_from_ram() {
  9731. if (degTargetHotend(active_extruder) != saved_extruder_temperature)
  9732. {
  9733. setTargetHotendSafe(saved_extruder_temperature, active_extruder);
  9734. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9735. wait_for_heater(_millis(), active_extruder);
  9736. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9737. }
  9738. }
  9739. //! @brief Restore print from ram
  9740. //!
  9741. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9742. //! print fan speed, waits for extruder temperature restore, then restores
  9743. //! position and continues print moves.
  9744. //!
  9745. //! Internally lcd_update() is called by wait_for_heater().
  9746. //!
  9747. //! @param e_move
  9748. void restore_print_from_ram_and_continue(float e_move)
  9749. {
  9750. if (!saved_printing) return;
  9751. #ifdef FANCHECK
  9752. // Do not allow resume printing if fans are still not ok
  9753. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9754. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9755. #endif
  9756. // Make sure fan is turned off
  9757. fanSpeed = 0;
  9758. // restore bed temperature (bed can be disabled during a thermal warning)
  9759. if (degBed() != saved_bed_temperature)
  9760. setTargetBed(saved_bed_temperature);
  9761. restore_extruder_temperature_from_ram();
  9762. // Restore saved fan speed
  9763. fanSpeed = saved_fan_speed;
  9764. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9765. float e = saved_pos[E_AXIS] - e_move;
  9766. plan_set_e_position(e);
  9767. #ifdef FANCHECK
  9768. fans_check_enabled = false;
  9769. #endif
  9770. // do not restore XY for commands that do not require that
  9771. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9772. {
  9773. saved_pos[X_AXIS] = current_position[X_AXIS];
  9774. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9775. }
  9776. //first move print head in XY to the saved position:
  9777. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], current_position[Z_AXIS], saved_pos[E_AXIS] - e_move, homing_feedrate[Z_AXIS]/13, active_extruder);
  9778. //then move Z
  9779. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS] - e_move, homing_feedrate[Z_AXIS]/13, active_extruder);
  9780. //and finaly unretract (35mm/s)
  9781. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9782. st_synchronize();
  9783. #ifdef FANCHECK
  9784. fans_check_enabled = true;
  9785. #endif
  9786. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9787. feedrate = saved_feedrate2;
  9788. feedmultiply = saved_feedmultiply2;
  9789. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9790. set_destination_to_current();
  9791. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9792. card.setIndex(saved_sdpos);
  9793. sdpos_atomic = saved_sdpos;
  9794. card.sdprinting = true;
  9795. }
  9796. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9797. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9798. serial_count = 0;
  9799. FlushSerialRequestResend();
  9800. }
  9801. else {
  9802. //not sd printing nor usb printing
  9803. }
  9804. lcd_setstatuspgm(MSG_WELCOME);
  9805. saved_printing_type = PRINTING_TYPE_NONE;
  9806. saved_printing = false;
  9807. planner_aborted = true; // unroll the stack
  9808. }
  9809. // Cancel the state related to a currently saved print
  9810. void cancel_saved_printing()
  9811. {
  9812. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9813. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9814. saved_printing_type = PRINTING_TYPE_NONE;
  9815. saved_printing = false;
  9816. }
  9817. void print_world_coordinates()
  9818. {
  9819. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9820. }
  9821. void print_physical_coordinates()
  9822. {
  9823. printf_P(_N("physical coordinates: (%.3f, %.3f, %.3f)\n"), st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS), st_get_position_mm(Z_AXIS));
  9824. }
  9825. void print_mesh_bed_leveling_table()
  9826. {
  9827. SERIAL_ECHOPGM("mesh bed leveling: ");
  9828. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9829. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9830. MYSERIAL.print(mbl.z_values[y][x], 3);
  9831. SERIAL_ECHO(' ');
  9832. }
  9833. SERIAL_ECHOLN();
  9834. }
  9835. uint8_t calc_percent_done()
  9836. {
  9837. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9838. uint8_t percent_done = 0;
  9839. #ifdef TMC2130
  9840. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9841. {
  9842. percent_done = print_percent_done_normal;
  9843. }
  9844. else if (print_percent_done_silent <= 100)
  9845. {
  9846. percent_done = print_percent_done_silent;
  9847. }
  9848. #else
  9849. if (print_percent_done_normal <= 100)
  9850. {
  9851. percent_done = print_percent_done_normal;
  9852. }
  9853. #endif //TMC2130
  9854. else
  9855. {
  9856. percent_done = card.percentDone();
  9857. }
  9858. return percent_done;
  9859. }
  9860. static void print_time_remaining_init()
  9861. {
  9862. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9863. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9864. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9865. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9866. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9867. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9868. }
  9869. void load_filament_final_feed()
  9870. {
  9871. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9872. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9873. }
  9874. //! @brief Wait for user to check the state
  9875. //! @par nozzle_temp nozzle temperature to load filament
  9876. void M600_check_state(float nozzle_temp)
  9877. {
  9878. uint8_t lcd_change_filament_state = 0;
  9879. while (lcd_change_filament_state != 1)
  9880. {
  9881. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9882. lcd_change_filament_state = lcd_alright();
  9883. KEEPALIVE_STATE(IN_HANDLER);
  9884. switch(lcd_change_filament_state)
  9885. {
  9886. // Filament failed to load so load it again
  9887. case 2:
  9888. if (MMU2::mmu2.Enabled()){
  9889. // Unload filament
  9890. mmu_M600_unload_filament();
  9891. // Ask to remove any old filament and load new
  9892. mmu_M600_wait_and_beep();
  9893. // After user clicks knob, MMU will load the filament
  9894. mmu_M600_load_filament(false, nozzle_temp);
  9895. } else {
  9896. M600_load_filament_movements();
  9897. }
  9898. break;
  9899. // Filament loaded properly but color is not clear
  9900. case 3:
  9901. st_synchronize();
  9902. load_filament_final_feed();
  9903. lcd_loading_color();
  9904. st_synchronize();
  9905. break;
  9906. // Everything good
  9907. default:
  9908. lcd_change_success();
  9909. break;
  9910. }
  9911. }
  9912. }
  9913. //! @brief Wait for user action
  9914. //!
  9915. //! Beep, manage nozzle heater and wait for user to start unload filament
  9916. //! If times out, active extruder temperature is set to 0.
  9917. //!
  9918. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9919. void M600_wait_for_user(float HotendTempBckp) {
  9920. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9921. int counterBeep = 0;
  9922. unsigned long waiting_start_time = _millis();
  9923. uint8_t wait_for_user_state = 0;
  9924. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9925. bool bFirst=true;
  9926. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9927. manage_heater();
  9928. manage_inactivity(true);
  9929. #if BEEPER > 0
  9930. if (counterBeep == 500) {
  9931. counterBeep = 0;
  9932. }
  9933. SET_OUTPUT(BEEPER);
  9934. if (counterBeep == 0) {
  9935. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9936. {
  9937. bFirst=false;
  9938. WRITE(BEEPER, HIGH);
  9939. }
  9940. }
  9941. if (counterBeep == 20) {
  9942. WRITE(BEEPER, LOW);
  9943. }
  9944. counterBeep++;
  9945. #endif //BEEPER > 0
  9946. switch (wait_for_user_state) {
  9947. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9948. delay_keep_alive(4);
  9949. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9950. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9951. wait_for_user_state = 1;
  9952. setAllTargetHotends(0);
  9953. st_synchronize();
  9954. disable_e0();
  9955. disable_e1();
  9956. disable_e2();
  9957. }
  9958. break;
  9959. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9960. delay_keep_alive(4);
  9961. if (lcd_clicked()) {
  9962. setTargetHotend(HotendTempBckp, active_extruder);
  9963. lcd_wait_for_heater();
  9964. wait_for_user_state = 2;
  9965. }
  9966. break;
  9967. case 2: //waiting for nozzle to reach target temperature
  9968. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9969. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9970. waiting_start_time = _millis();
  9971. wait_for_user_state = 0;
  9972. }
  9973. else {
  9974. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9975. lcd_set_cursor(1, 4);
  9976. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  9977. }
  9978. break;
  9979. }
  9980. }
  9981. WRITE(BEEPER, LOW);
  9982. }
  9983. void M600_load_filament_movements()
  9984. {
  9985. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  9986. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  9987. load_filament_final_feed();
  9988. lcd_loading_filament();
  9989. st_synchronize();
  9990. }
  9991. void M600_load_filament() {
  9992. //load filament for single material and MMU
  9993. lcd_wait_interact();
  9994. //load_filament_time = _millis();
  9995. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9996. while(!lcd_clicked())
  9997. {
  9998. manage_heater();
  9999. manage_inactivity(true);
  10000. #ifdef FILAMENT_SENSOR
  10001. if (fsensor.getFilamentLoadEvent()) {
  10002. Sound_MakeCustom(50,1000,false);
  10003. break;
  10004. }
  10005. #endif //FILAMENT_SENSOR
  10006. }
  10007. KEEPALIVE_STATE(IN_HANDLER);
  10008. M600_load_filament_movements();
  10009. Sound_MakeCustom(50,1000,false);
  10010. lcd_update_enable(false);
  10011. }
  10012. //! @brief Wait for click
  10013. //!
  10014. //! Set
  10015. void marlin_wait_for_click()
  10016. {
  10017. int8_t busy_state_backup = busy_state;
  10018. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10019. lcd_consume_click();
  10020. while(!lcd_clicked())
  10021. {
  10022. manage_heater();
  10023. manage_inactivity(true);
  10024. lcd_update(0);
  10025. }
  10026. KEEPALIVE_STATE(busy_state_backup);
  10027. }
  10028. #ifdef PSU_Delta
  10029. bool bEnableForce_z;
  10030. void init_force_z()
  10031. {
  10032. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10033. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10034. disable_force_z();
  10035. }
  10036. void check_force_z()
  10037. {
  10038. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10039. init_force_z(); // causes enforced switching into disable-state
  10040. }
  10041. void disable_force_z()
  10042. {
  10043. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10044. bEnableForce_z=false;
  10045. // switching to silent mode
  10046. #ifdef TMC2130
  10047. tmc2130_mode=TMC2130_MODE_SILENT;
  10048. update_mode_profile();
  10049. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10050. #endif // TMC2130
  10051. }
  10052. void enable_force_z()
  10053. {
  10054. if(bEnableForce_z)
  10055. return; // motor already enabled (may be ;-p )
  10056. bEnableForce_z=true;
  10057. // mode recovering
  10058. #ifdef TMC2130
  10059. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10060. update_mode_profile();
  10061. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10062. #endif // TMC2130
  10063. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10064. }
  10065. #endif // PSU_Delta