Marlin_main.cpp 387 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648
  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. #ifdef ULTRALCD
  99. #include "ultralcd.h"
  100. #endif
  101. #if NUM_SERVOS > 0
  102. #include "Servo.h"
  103. #endif
  104. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  105. #include <SPI.h>
  106. #endif
  107. #include "mmu2.h"
  108. #define VERSION_STRING "1.0.2"
  109. #include "ultralcd.h"
  110. #include "sound.h"
  111. #include "cmdqueue.h"
  112. //Macro for print fan speed
  113. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  114. //filament types
  115. #define FILAMENT_DEFAULT 0
  116. #define FILAMENT_FLEX 1
  117. #define FILAMENT_PVA 2
  118. #define FILAMENT_UNDEFINED 255
  119. //Stepper Movement Variables
  120. //===========================================================================
  121. //=============================imported variables============================
  122. //===========================================================================
  123. //===========================================================================
  124. //=============================public variables=============================
  125. //===========================================================================
  126. #ifdef SDSUPPORT
  127. CardReader card;
  128. #endif
  129. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  130. //used for PINDA temp calibration and pause print
  131. #define DEFAULT_RETRACTION 1
  132. #define DEFAULT_RETRACTION_MM 4 //MM
  133. float default_retraction = DEFAULT_RETRACTION;
  134. float homing_feedrate[] = HOMING_FEEDRATE;
  135. //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
  136. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  137. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  138. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  139. uint8_t axis_relative_modes = 0;
  140. int feedmultiply=100; //100->1 200->2
  141. int extrudemultiply=100; //100->1 200->2
  142. int extruder_multiply[EXTRUDERS] = {100
  143. #if EXTRUDERS > 1
  144. , 100
  145. #if EXTRUDERS > 2
  146. , 100
  147. #endif
  148. #endif
  149. };
  150. bool homing_flag = false;
  151. unsigned long pause_time = 0;
  152. unsigned long start_pause_print = _millis();
  153. unsigned long t_fan_rising_edge = _millis();
  154. LongTimer safetyTimer;
  155. static LongTimer crashDetTimer;
  156. //unsigned long load_filament_time;
  157. bool mesh_bed_leveling_flag = false;
  158. unsigned long total_filament_used;
  159. HeatingStatus heating_status;
  160. uint8_t heating_status_counter;
  161. bool loading_flag = false;
  162. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  163. bool fan_state[2];
  164. int fan_edge_counter[2];
  165. int fan_speed[2];
  166. float extruder_multiplier[EXTRUDERS] = {1.0
  167. #if EXTRUDERS > 1
  168. , 1.0
  169. #if EXTRUDERS > 2
  170. , 1.0
  171. #endif
  172. #endif
  173. };
  174. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  175. //shortcuts for more readable code
  176. #define _x current_position[X_AXIS]
  177. #define _y current_position[Y_AXIS]
  178. #define _z current_position[Z_AXIS]
  179. #define _e current_position[E_AXIS]
  180. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  181. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  182. bool axis_known_position[3] = {false, false, false};
  183. // Extruder offset
  184. #if EXTRUDERS > 1
  185. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  186. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  187. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  188. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  189. #endif
  190. };
  191. #endif
  192. int fanSpeed=0;
  193. uint8_t newFanSpeed = 0;
  194. #ifdef FWRETRACT
  195. bool retracted[EXTRUDERS]={false
  196. #if EXTRUDERS > 1
  197. , false
  198. #if EXTRUDERS > 2
  199. , false
  200. #endif
  201. #endif
  202. };
  203. bool retracted_swap[EXTRUDERS]={false
  204. #if EXTRUDERS > 1
  205. , false
  206. #if EXTRUDERS > 2
  207. , false
  208. #endif
  209. #endif
  210. };
  211. float retract_length_swap = RETRACT_LENGTH_SWAP;
  212. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  213. #endif
  214. #ifdef PS_DEFAULT_OFF
  215. bool powersupply = false;
  216. #else
  217. bool powersupply = true;
  218. #endif
  219. bool cancel_heatup = false;
  220. int8_t busy_state = NOT_BUSY;
  221. static long prev_busy_signal_ms = -1;
  222. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  223. const char errormagic[] PROGMEM = "Error:";
  224. const char echomagic[] PROGMEM = "echo:";
  225. const char G28W0[] PROGMEM = "G28 W0";
  226. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  227. // that they can be used later for various logical checks
  228. #define X_COORD_INVALID (X_MIN_POS-1)
  229. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  230. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  231. uint16_t saved_segment_idx = 0;
  232. // storing estimated time to end of print counted by slicer
  233. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  234. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  235. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  236. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  237. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  238. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  239. uint32_t IP_address = 0;
  240. //===========================================================================
  241. //=============================Private Variables=============================
  242. //===========================================================================
  243. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  244. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  245. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  246. // For tracing an arc
  247. static float offset[3] = {0.0, 0.0, 0.0};
  248. // Current feedrate
  249. float feedrate = 1500.0;
  250. // Feedrate for the next move
  251. static float next_feedrate;
  252. // Original feedrate saved during homing moves
  253. static float saved_feedrate;
  254. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  255. //static float tt = 0;
  256. //static float bt = 0;
  257. //Inactivity shutdown variables
  258. static LongTimer previous_millis_cmd;
  259. unsigned long max_inactive_time = 0;
  260. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  261. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  262. unsigned long starttime=0;
  263. unsigned long stoptime=0;
  264. ShortTimer usb_timer;
  265. bool Stopped=false;
  266. #if NUM_SERVOS > 0
  267. Servo servos[NUM_SERVOS];
  268. #endif
  269. bool target_direction;
  270. //Insert variables if CHDK is defined
  271. #ifdef CHDK
  272. unsigned long chdkHigh = 0;
  273. bool chdkActive = false;
  274. #endif
  275. //! @name RAM save/restore printing
  276. //! @{
  277. bool saved_printing = false; //!< Print is paused and saved in RAM
  278. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  279. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  280. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  281. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  282. static int saved_feedmultiply2 = 0;
  283. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  284. float saved_bed_temperature = 0.0;
  285. static bool saved_extruder_relative_mode = false;
  286. int saved_fan_speed = 0; //!< Print fan speed
  287. //! @}
  288. static int saved_feedmultiply_mm = 100;
  289. class AutoReportFeatures {
  290. union {
  291. struct {
  292. uint8_t temp : 1; //Temperature flag
  293. uint8_t fans : 1; //Fans flag
  294. uint8_t pos: 1; //Position flag
  295. uint8_t ar4 : 1; //Unused
  296. uint8_t ar5 : 1; //Unused
  297. uint8_t ar6 : 1; //Unused
  298. uint8_t ar7 : 1; //Unused
  299. } __attribute__((packed)) bits;
  300. uint8_t byte;
  301. } arFunctionsActive;
  302. uint8_t auto_report_period;
  303. public:
  304. LongTimer auto_report_timer;
  305. AutoReportFeatures():auto_report_period(0){
  306. #if defined(AUTO_REPORT)
  307. arFunctionsActive.byte = 0xff;
  308. #else
  309. arFunctionsActive.byte = 0;
  310. #endif //AUTO_REPORT
  311. }
  312. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  313. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  314. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  315. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  316. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  317. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  318. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  319. /// sets the autoreporting timer's period
  320. /// setting it to zero stops the timer
  321. void SetPeriod(uint8_t p){
  322. auto_report_period = p;
  323. if (auto_report_period != 0){
  324. auto_report_timer.start();
  325. } else{
  326. auto_report_timer.stop();
  327. }
  328. }
  329. inline void TimerStart() { auto_report_timer.start(); }
  330. inline bool TimerRunning()const { return auto_report_timer.running(); }
  331. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  332. };
  333. AutoReportFeatures autoReportFeatures;
  334. //===========================================================================
  335. //=============================Routines======================================
  336. //===========================================================================
  337. static bool setTargetedHotend(int code, uint8_t &extruder);
  338. static void print_time_remaining_init();
  339. static void wait_for_heater(long codenum, uint8_t extruder);
  340. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  341. static void gcode_M105(uint8_t extruder);
  342. #ifndef PINDA_THERMISTOR
  343. static void temp_compensation_start();
  344. static void temp_compensation_apply();
  345. #endif
  346. #ifdef PRUSA_SN_SUPPORT
  347. static uint8_t get_PRUSA_SN(char* SN);
  348. #endif //PRUSA_SN_SUPPORT
  349. uint16_t gcode_in_progress = 0;
  350. uint16_t mcode_in_progress = 0;
  351. void serial_echopair_P(const char *s_P, float v)
  352. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  353. void serial_echopair_P(const char *s_P, double v)
  354. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  355. void serial_echopair_P(const char *s_P, unsigned long v)
  356. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  357. void serialprintPGM(const char *str) {
  358. while(uint8_t ch = pgm_read_byte(str)) {
  359. MYSERIAL.write((char)ch);
  360. ++str;
  361. }
  362. }
  363. void serialprintlnPGM(const char *str) {
  364. serialprintPGM(str);
  365. MYSERIAL.println();
  366. }
  367. #ifdef SDSUPPORT
  368. #include "SdFatUtil.h"
  369. int freeMemory() { return SdFatUtil::FreeRam(); }
  370. #else
  371. extern "C" {
  372. extern unsigned int __bss_end;
  373. extern unsigned int __heap_start;
  374. extern void *__brkval;
  375. int freeMemory() {
  376. int free_memory;
  377. if ((int)__brkval == 0)
  378. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  379. else
  380. free_memory = ((int)&free_memory) - ((int)__brkval);
  381. return free_memory;
  382. }
  383. }
  384. #endif //!SDSUPPORT
  385. void setup_killpin()
  386. {
  387. #if defined(KILL_PIN) && KILL_PIN > -1
  388. SET_INPUT(KILL_PIN);
  389. WRITE(KILL_PIN,HIGH);
  390. #endif
  391. }
  392. // Set home pin
  393. void setup_homepin(void)
  394. {
  395. #if defined(HOME_PIN) && HOME_PIN > -1
  396. SET_INPUT(HOME_PIN);
  397. WRITE(HOME_PIN,HIGH);
  398. #endif
  399. }
  400. void setup_photpin()
  401. {
  402. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  403. SET_OUTPUT(PHOTOGRAPH_PIN);
  404. WRITE(PHOTOGRAPH_PIN, LOW);
  405. #endif
  406. }
  407. void setup_powerhold()
  408. {
  409. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  410. SET_OUTPUT(SUICIDE_PIN);
  411. WRITE(SUICIDE_PIN, HIGH);
  412. #endif
  413. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  414. SET_OUTPUT(PS_ON_PIN);
  415. #if defined(PS_DEFAULT_OFF)
  416. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  417. #else
  418. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  419. #endif
  420. #endif
  421. }
  422. void suicide()
  423. {
  424. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  425. SET_OUTPUT(SUICIDE_PIN);
  426. WRITE(SUICIDE_PIN, LOW);
  427. #endif
  428. }
  429. void servo_init()
  430. {
  431. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  432. servos[0].attach(SERVO0_PIN);
  433. #endif
  434. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  435. servos[1].attach(SERVO1_PIN);
  436. #endif
  437. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  438. servos[2].attach(SERVO2_PIN);
  439. #endif
  440. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  441. servos[3].attach(SERVO3_PIN);
  442. #endif
  443. #if (NUM_SERVOS >= 5)
  444. #error "TODO: enter initalisation code for more servos"
  445. #endif
  446. }
  447. bool __attribute__((noinline)) printer_active() {
  448. return IS_SD_PRINTING
  449. || usb_timer.running()
  450. || isPrintPaused
  451. || (custom_message_type == CustomMsg::TempCal)
  452. || saved_printing
  453. || (lcd_commands_type == LcdCommands::Layer1Cal)
  454. || MMU2::mmu2.MMU_PRINT_SAVED()
  455. || homing_flag
  456. || mesh_bed_leveling_flag;
  457. }
  458. // Currently only used in one place, allowed to be inlined
  459. bool check_fsensor() {
  460. return (IS_SD_PRINTING || usb_timer.running())
  461. && mcode_in_progress != 600
  462. && !saved_printing
  463. && e_active();
  464. }
  465. bool fans_check_enabled = true;
  466. #ifdef TMC2130
  467. void crashdet_stop_and_save_print()
  468. {
  469. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  470. }
  471. void crashdet_restore_print_and_continue()
  472. {
  473. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  474. // babystep_apply();
  475. }
  476. void crashdet_fmt_error(char* buf, uint8_t mask)
  477. {
  478. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  479. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  480. *buf++ = ' ';
  481. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  482. }
  483. void crashdet_detected(uint8_t mask)
  484. {
  485. st_synchronize();
  486. static uint8_t crashDet_counter = 0;
  487. static uint8_t crashDet_axes = 0;
  488. bool automatic_recovery_after_crash = true;
  489. char msg[LCD_WIDTH+1] = "";
  490. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  491. crashDet_counter = 0;
  492. }
  493. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  494. automatic_recovery_after_crash = false;
  495. }
  496. crashDetTimer.start();
  497. crashDet_axes |= mask;
  498. lcd_update_enable(true);
  499. lcd_clear();
  500. lcd_update(2);
  501. if (mask & X_AXIS_MASK)
  502. {
  503. eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_X);
  504. eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT);
  505. }
  506. if (mask & Y_AXIS_MASK)
  507. {
  508. eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_Y);
  509. eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT);
  510. }
  511. lcd_update_enable(true);
  512. lcd_update(2);
  513. // prepare the status message with the _current_ axes status
  514. crashdet_fmt_error(msg, mask);
  515. lcd_setstatus(msg);
  516. gcode_G28(true, true, false); //home X and Y
  517. if (automatic_recovery_after_crash) {
  518. enquecommand_P(PSTR("CRASH_RECOVER"));
  519. }else{
  520. setTargetHotend(0, active_extruder);
  521. // notify the user of *all* the axes previously affected, not just the last one
  522. lcd_update_enable(false);
  523. lcd_clear();
  524. crashdet_fmt_error(msg, crashDet_axes);
  525. crashDet_axes = 0;
  526. lcd_print(msg);
  527. // ask whether to resume printing
  528. lcd_set_cursor(0, 1);
  529. lcd_puts_P(_T(MSG_RESUME_PRINT));
  530. lcd_putc('?');
  531. uint8_t yesno = lcd_show_yes_no_and_wait(false);
  532. if (yesno == LCD_LEFT_BUTTON_CHOICE)
  533. {
  534. enquecommand_P(PSTR("CRASH_RECOVER"));
  535. }
  536. else // LCD_MIDDLE_BUTTON_CHOICE
  537. {
  538. enquecommand_P(PSTR("CRASH_CANCEL"));
  539. }
  540. }
  541. }
  542. void crashdet_recover()
  543. {
  544. crashdet_restore_print_and_continue();
  545. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  546. }
  547. void crashdet_cancel()
  548. {
  549. saved_printing = false;
  550. tmc2130_sg_stop_on_crash = true;
  551. if (saved_printing_type == PRINTING_TYPE_SD) {
  552. print_stop();
  553. }else if(saved_printing_type == PRINTING_TYPE_USB){
  554. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  555. cmdqueue_reset();
  556. }
  557. }
  558. #endif //TMC2130
  559. void failstats_reset_print()
  560. {
  561. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  562. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  563. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  564. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  565. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  566. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  567. }
  568. void watchdogEarlyDisable(void) {
  569. // Regardless if the watchdog support is enabled or not, disable the watchdog very early
  570. // after the program starts since there's no danger in doing this.
  571. // The reason for this is because old bootloaders might not handle the watchdog timer at all,
  572. // leaving it enabled when jumping to the program. This could cause another watchdog reset
  573. // during setup() if not handled properly. So to avoid any issue of this kind, stop the
  574. // watchdog timer manually.
  575. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  576. wdt_reset();
  577. MCUSR &= ~_BV(WDRF);
  578. wdt_disable();
  579. }
  580. }
  581. void softReset(void) {
  582. cli();
  583. #ifdef WATCHDOG
  584. // If the watchdog support is enabled, use that for resetting. The timeout value is customized
  585. // for each board since the miniRambo ships with a bootloader which doesn't properly handle the
  586. // WDT. In order to avoid bootlooping, the watchdog is set to a value large enough for the
  587. // usual timeout of the bootloader to pass.
  588. wdt_enable(WATCHDOG_SOFT_RESET_VALUE);
  589. #else
  590. #warning WATCHDOG not defined. See the following comment for more details about the implications
  591. // In case the watchdog is not enabled, the reset is acomplished by jumping to the bootloader
  592. // vector manually. This however is somewhat dangerous since the peripherals don't get reset
  593. // by this operation. Considering this is not going to be used in any production firmware,
  594. // it can be left as is and just be cautious with it. The only way to accomplish a peripheral
  595. // reset is by an external reset, by a watchdog reset or by a power cycle. All of these options
  596. // can't be accomplished just from software. One way to minimize the dangers of this is by
  597. // setting all dangerous pins to INPUT before jumping to the bootloader, but that still doesn't
  598. // reset other peripherals such as UART, timers, INT, PCINT, etc...
  599. asm volatile("jmp 0x3E000");
  600. #endif
  601. while(1);
  602. }
  603. #ifdef MESH_BED_LEVELING
  604. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  605. #endif
  606. static void factory_reset_stats(){
  607. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  608. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  609. failstats_reset_print();
  610. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  611. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  612. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  613. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  614. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  615. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  616. eeprom_update_dword((uint32_t *)EEPROM_TOTAL_TOOLCHANGE_COUNT, 0);
  617. }
  618. // Factory reset function
  619. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  620. // Level input parameter sets depth of reset
  621. static void factory_reset(char level)
  622. {
  623. lcd_clear();
  624. Sound_MakeCustom(100,0,false);
  625. switch (level) {
  626. case 0: // Level 0: Language reset
  627. lang_reset();
  628. break;
  629. case 1: //Level 1: Reset statistics
  630. factory_reset_stats();
  631. lcd_menu_statistics();
  632. break;
  633. case 2: // Level 2: Prepare for shipping
  634. factory_reset_stats();
  635. // FALLTHRU
  636. case 3: // Level 3: Preparation after being serviced
  637. // Force language selection at the next boot up.
  638. lang_reset();
  639. // Force the "Follow calibration flow" message at the next boot up.
  640. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  641. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  642. farm_disable();
  643. #ifdef FILAMENT_SENSOR
  644. fsensor.setEnabled(true);
  645. fsensor.setAutoLoadEnabled(true, true);
  646. fsensor.setRunoutEnabled(true, true);
  647. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  648. fsensor.setJamDetectionEnabled(true, true);
  649. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  650. #endif //FILAMENT_SENSOR
  651. break;
  652. case 4:
  653. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  654. // Erase EEPROM
  655. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  656. eeprom_update_byte((uint8_t*)i, 0xFF);
  657. menu_progressbar_update(i);
  658. }
  659. menu_progressbar_finish();
  660. softReset();
  661. break;
  662. default:
  663. break;
  664. }
  665. }
  666. extern "C" {
  667. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  668. }
  669. int uart_putchar(char c, FILE *)
  670. {
  671. MYSERIAL.write(c);
  672. return 0;
  673. }
  674. void lcd_splash()
  675. {
  676. lcd_clear(); // clears display and homes screen
  677. lcd_printf_P(PSTR("\n Original Prusa i3\n Prusa Research\n%20.20S"), PSTR(FW_VERSION));
  678. }
  679. void factory_reset()
  680. {
  681. KEEPALIVE_STATE(PAUSED_FOR_USER);
  682. if (!READ(BTN_ENC))
  683. {
  684. _delay_ms(1000);
  685. if (!READ(BTN_ENC))
  686. {
  687. lcd_clear();
  688. lcd_puts_P(PSTR("Factory RESET"));
  689. SET_OUTPUT(BEEPER);
  690. if(eSoundMode!=e_SOUND_MODE_SILENT)
  691. WRITE(BEEPER, HIGH);
  692. while (!READ(BTN_ENC));
  693. WRITE(BEEPER, LOW);
  694. _delay_ms(2000);
  695. char level = reset_menu();
  696. factory_reset(level);
  697. switch (level) {
  698. case 0:
  699. case 1:
  700. case 2:
  701. case 3:
  702. case 4: _delay_ms(0); break;
  703. }
  704. }
  705. }
  706. KEEPALIVE_STATE(IN_HANDLER);
  707. }
  708. #if 0
  709. void show_fw_version_warnings() {
  710. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  711. switch (FW_DEV_VERSION) {
  712. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(MSG_FW_VERSION_BETA); break;
  713. case(FW_VERSION_ALPHA):
  714. case(FW_VERSION_DEVEL):
  715. case(FW_VERSION_DEBUG):
  716. lcd_update_enable(false);
  717. lcd_clear();
  718. #if (FW_DEV_VERSION == FW_VERSION_DEVEL || FW_DEV_VERSION == FW_VERSION_ALPHA)
  719. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  720. #else
  721. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  722. #endif
  723. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  724. lcd_puts_at_P(0, 2, PSTR("FW")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  725. lcd_puts_at_P(0, 3, PSTR("Repo: ")); lcd_puts_P(PSTR(FW_REPOSITORY));
  726. lcd_wait_for_click();
  727. break;
  728. // 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
  729. }
  730. lcd_update_enable(true);
  731. }
  732. #endif
  733. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  734. //! @brief try to check if firmware is on right type of printer
  735. static void check_if_fw_is_on_right_printer() {
  736. if (fsensor.probeOtherType()) {
  737. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  738. }
  739. }
  740. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  741. uint8_t check_printer_version()
  742. {
  743. uint8_t version_changed = 0;
  744. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  745. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  746. if (printer_type != PRINTER_TYPE) {
  747. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  748. else version_changed |= 0b10;
  749. }
  750. if (motherboard != MOTHERBOARD) {
  751. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  752. else version_changed |= 0b01;
  753. }
  754. return version_changed;
  755. }
  756. #ifdef BOOTAPP
  757. #include "bootapp.h" //bootloader support
  758. #endif //BOOTAPP
  759. #if (LANG_MODE != 0) //secondary language support
  760. #ifdef XFLASH
  761. // language update from external flash
  762. #define LANGBOOT_BLOCKSIZE 0x1000u
  763. #define LANGBOOT_RAMBUFFER 0x0800
  764. void update_sec_lang_from_external_flash()
  765. {
  766. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  767. {
  768. uint8_t lang = boot_reserved >> 3;
  769. uint8_t state = boot_reserved & 0x07;
  770. lang_table_header_t header;
  771. uint32_t src_addr;
  772. if (lang_get_header(lang, &header, &src_addr))
  773. {
  774. lcd_puts_at_P(1,3,PSTR("Language update."));
  775. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  776. _delay(100);
  777. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  778. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  779. {
  780. cli();
  781. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  782. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  783. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  784. if (state == 0)
  785. {
  786. //TODO - check header integrity
  787. }
  788. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  789. }
  790. else
  791. {
  792. //TODO - check sec lang data integrity
  793. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  794. }
  795. }
  796. }
  797. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  798. }
  799. #ifdef DEBUG_XFLASH
  800. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  801. {
  802. lang_table_header_t header;
  803. uint8_t count = 0;
  804. uint32_t addr = 0x00000;
  805. while (1)
  806. {
  807. printf_P(_n("LANGTABLE%d:"), count);
  808. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  809. if (header.magic != LANG_MAGIC)
  810. {
  811. puts_P(_n("NG!"));
  812. break;
  813. }
  814. puts_P(_n("OK"));
  815. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  816. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  817. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  818. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  819. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  820. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  821. addr += header.size;
  822. codes[count] = header.code;
  823. count ++;
  824. }
  825. return count;
  826. }
  827. void list_sec_lang_from_external_flash()
  828. {
  829. uint16_t codes[8];
  830. uint8_t count = lang_xflash_enum_codes(codes);
  831. printf_P(_n("XFlash lang count = %hhd\n"), count);
  832. }
  833. #endif //DEBUG_XFLASH
  834. #endif //XFLASH
  835. #endif //(LANG_MODE != 0)
  836. static void fw_crash_init()
  837. {
  838. #ifdef XFLASH_DUMP
  839. dump_crash_reason crash_reason;
  840. if(xfdump_check_state(&crash_reason))
  841. {
  842. // always signal to the host that a dump is available for retrieval
  843. puts_P(_N("// action:dump_available"));
  844. #ifdef EMERGENCY_DUMP
  845. if(crash_reason != dump_crash_reason::manual &&
  846. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  847. {
  848. lcd_show_fullscreen_message_and_wait_P(
  849. _n("FW crash detected! "
  850. "You can continue printing. "
  851. "Debug data available for analysis. "
  852. "Contact support to submit details."));
  853. }
  854. #endif
  855. }
  856. #else //XFLASH_DUMP
  857. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  858. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  859. {
  860. lcd_beeper_quick_feedback();
  861. lcd_clear();
  862. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  863. switch(crash_reason)
  864. {
  865. case dump_crash_reason::stack_error:
  866. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  867. break;
  868. case dump_crash_reason::watchdog:
  869. lcd_puts_P(_n("Watchdog timeout"));
  870. break;
  871. case dump_crash_reason::bad_isr:
  872. lcd_puts_P(_n("Bad interrupt"));
  873. break;
  874. default:
  875. lcd_print((uint8_t)crash_reason);
  876. break;
  877. }
  878. lcd_wait_for_click();
  879. }
  880. #endif //XFLASH_DUMP
  881. // prevent crash prompts to reappear once acknowledged
  882. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  883. }
  884. static void xflash_err_msg()
  885. {
  886. puts_P(_n("XFLASH not responding."));
  887. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  888. }
  889. // "Setup" function is called by the Arduino framework on startup.
  890. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  891. // are initialized by the main() routine provided by the Arduino framework.
  892. void setup()
  893. {
  894. watchdogEarlyDisable();
  895. timer2_init(); // enables functional millis
  896. ultralcd_init();
  897. spi_init();
  898. lcd_splash();
  899. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  900. selectedSerialPort = eeprom_init_default_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, 0);
  901. MYSERIAL.begin(BAUDRATE);
  902. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  903. stdout = uartout;
  904. #ifdef XFLASH
  905. bool xflash_success = xflash_init();
  906. uint8_t optiboot_status = 1;
  907. if (xflash_success)
  908. {
  909. optiboot_status = optiboot_xflash_enter();
  910. #if (LANG_MODE != 0) //secondary language support
  911. update_sec_lang_from_external_flash();
  912. #endif //(LANG_MODE != 0)
  913. }
  914. #else
  915. const bool xflash_success = true;
  916. #endif //XFLASH
  917. setup_killpin();
  918. setup_powerhold();
  919. farm_mode_init();
  920. #ifdef TMC2130
  921. if( FarmOrUserECool() ){
  922. //increased extruder current (PFW363)
  923. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  924. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  925. }
  926. #endif //TMC2130
  927. #ifdef PRUSA_SN_SUPPORT
  928. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  929. //SN is valid only if it is NULL terminated and starts with "CZPX".
  930. {
  931. char SN[20];
  932. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  933. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  934. {
  935. if (!get_PRUSA_SN(SN))
  936. {
  937. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  938. puts_P(PSTR("SN updated"));
  939. }
  940. else
  941. puts_P(PSTR("SN update failed"));
  942. }
  943. }
  944. #endif //PRUSA_SN_SUPPORT
  945. #ifndef XFLASH
  946. SERIAL_PROTOCOLLNPGM("start");
  947. #else
  948. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  949. SERIAL_PROTOCOLLNPGM("start");
  950. #endif
  951. SERIAL_ECHO_START;
  952. puts_P(PSTR(" " FW_VERSION_FULL));
  953. if (eeprom_read_byte((uint8_t *)EEPROM_MMU_ENABLED)) {
  954. MMU2::mmu2.Start();
  955. }
  956. SpoolJoin::spooljoin.initSpoolJoinStatus();
  957. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  958. #ifdef DEBUG_SEC_LANG
  959. lang_table_header_t header;
  960. uint32_t src_addr = 0x00000;
  961. if (lang_get_header(1, &header, &src_addr))
  962. {
  963. printf_P(
  964. _n(
  965. " _src_addr = 0x%08lx\n"
  966. " _lt_magic = 0x%08lx %S\n"
  967. " _lt_size = 0x%04x (%d)\n"
  968. " _lt_count = 0x%04x (%d)\n"
  969. " _lt_chsum = 0x%04x\n"
  970. " _lt_code = 0x%04x (%c%c)\n"
  971. " _lt_resv1 = 0x%08lx\n"
  972. ),
  973. src_addr,
  974. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  975. header.size, header.size,
  976. header.count, header.count,
  977. header.checksum,
  978. header.code, header.code >> 8, header.code & 0xff,
  979. header.signature
  980. );
  981. #if 0
  982. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  983. for (uint16_t i = 0; i < 1024; i++)
  984. {
  985. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  986. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  987. if ((i % 16) == 15) putchar('\n');
  988. }
  989. #endif
  990. uint16_t sum = 0;
  991. for (uint16_t i = 0; i < header.size; i++)
  992. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  993. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  994. sum -= header.checksum; //subtract checksum
  995. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  996. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  997. if (sum == header.checksum)
  998. puts_P(_n("Checksum OK"));
  999. else
  1000. puts_P(_n("Checksum NG"));
  1001. }
  1002. else
  1003. puts_P(_n("lang_get_header failed!"));
  1004. #if 0
  1005. for (uint16_t i = 0; i < 1024*10; i++)
  1006. {
  1007. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  1008. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  1009. if ((i % 16) == 15) putchar('\n');
  1010. }
  1011. #endif
  1012. #if 0
  1013. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  1014. for (int i = 0; i < 4096; ++i) {
  1015. int b = eeprom_read_byte((unsigned char*)i);
  1016. if (b != 255) {
  1017. SERIAL_ECHO(i);
  1018. SERIAL_ECHO(":");
  1019. SERIAL_ECHO(b);
  1020. SERIAL_ECHOLN("");
  1021. }
  1022. }
  1023. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  1024. #endif
  1025. #endif //DEBUG_SEC_LANG
  1026. // Check startup - does nothing if bootloader sets MCUSR to 0
  1027. byte mcu = MCUSR;
  1028. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  1029. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  1030. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  1031. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1032. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1033. if (mcu & 1) puts_P(MSG_POWERUP);
  1034. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1035. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1036. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1037. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1038. MCUSR = 0;
  1039. //SERIAL_ECHORPGM(MSG_MARLIN);
  1040. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1041. #ifdef STRING_VERSION_CONFIG_H
  1042. #ifdef STRING_CONFIG_H_AUTHOR
  1043. SERIAL_ECHO_START;
  1044. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1045. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1046. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1047. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1048. #endif
  1049. #endif
  1050. SERIAL_ECHO_START;
  1051. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1052. SERIAL_ECHO(freeMemory());
  1053. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1054. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1055. //lcd_update_enable(false); // why do we need this?? - andre
  1056. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1057. bool previous_settings_retrieved = false;
  1058. uint8_t hw_changed = check_printer_version();
  1059. 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
  1060. previous_settings_retrieved = Config_RetrieveSettings();
  1061. }
  1062. else { //printer version was changed so use default settings
  1063. Config_ResetDefault();
  1064. }
  1065. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1066. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1067. // performed inside the soft_pwm_isr)
  1068. SdFatUtil::set_stack_guard();
  1069. // Initialize pwm/temperature loops
  1070. soft_pwm_init();
  1071. temp_mgr_init();
  1072. #ifdef EXTRUDER_ALTFAN_DETECT
  1073. SERIAL_ECHORPGM(_n("Hotend fan type: "));
  1074. if (extruder_altfan_detect())
  1075. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1076. else
  1077. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1078. #endif //EXTRUDER_ALTFAN_DETECT
  1079. plan_init(); // Initialize planner;
  1080. factory_reset();
  1081. eeprom_init_default_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1082. eeprom_init_default_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard if uninitialized
  1083. lcd_encoder_diff=0;
  1084. #ifdef TMC2130
  1085. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1086. if (silentMode == 0xff) silentMode = 0;
  1087. tmc2130_mode = TMC2130_MODE_NORMAL;
  1088. if (lcd_crash_detect_enabled() && !farm_mode)
  1089. {
  1090. lcd_crash_detect_enable();
  1091. puts_P(_N("CrashDetect ENABLED!"));
  1092. }
  1093. else
  1094. {
  1095. lcd_crash_detect_disable();
  1096. puts_P(_N("CrashDetect DISABLED"));
  1097. }
  1098. #ifdef TMC2130_LINEARITY_CORRECTION
  1099. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1100. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1101. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1102. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1103. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1104. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1105. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1106. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1107. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1108. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1109. #endif //TMC2130_LINEARITY_CORRECTION
  1110. #ifdef TMC2130_VARIABLE_RESOLUTION
  1111. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1112. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1113. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1114. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1115. #else //TMC2130_VARIABLE_RESOLUTION
  1116. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1117. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1118. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1119. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1120. #endif //TMC2130_VARIABLE_RESOLUTION
  1121. #endif //TMC2130
  1122. st_init(); // Initialize stepper, this enables interrupts!
  1123. #ifdef TMC2130
  1124. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1125. update_mode_profile();
  1126. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1127. #endif //TMC2130
  1128. #ifdef PSU_Delta
  1129. init_force_z(); // ! important for correct Z-axis initialization
  1130. #endif // PSU_Delta
  1131. setup_photpin();
  1132. #if 0
  1133. servo_init();
  1134. #endif
  1135. // Reset the machine correction matrix.
  1136. // It does not make sense to load the correction matrix until the machine is homed.
  1137. world2machine_reset();
  1138. // Initialize current_position accounting for software endstops to
  1139. // avoid unexpected initial shifts on the first move
  1140. clamp_to_software_endstops(current_position);
  1141. plan_set_position_curposXYZE();
  1142. // Show the xflash error message now that serial, lcd and encoder are available
  1143. if (!xflash_success)
  1144. xflash_err_msg();
  1145. #ifdef FILAMENT_SENSOR
  1146. fsensor.init();
  1147. #endif //FILAMENT_SENSOR
  1148. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1149. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1150. #endif
  1151. setup_homepin();
  1152. #if defined(Z_AXIS_ALWAYS_ON)
  1153. enable_z();
  1154. #endif
  1155. // The farm monitoring SW may accidentally expect
  1156. // 2 messages of "printer started" to consider a printer working.
  1157. prusa_statistics(8);
  1158. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1159. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1160. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1161. // but this times out if a blocking dialog is shown in setup().
  1162. card.initsd();
  1163. #ifdef DEBUG_SD_SPEED_TEST
  1164. if (card.cardOK)
  1165. {
  1166. uint8_t* buff = (uint8_t*)block_buffer;
  1167. uint32_t block = 0;
  1168. uint32_t sumr = 0;
  1169. uint32_t sumw = 0;
  1170. for (int i = 0; i < 1024; i++)
  1171. {
  1172. uint32_t u = _micros();
  1173. bool res = card.card.readBlock(i, buff);
  1174. u = _micros() - u;
  1175. if (res)
  1176. {
  1177. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1178. sumr += u;
  1179. u = _micros();
  1180. res = card.card.writeBlock(i, buff);
  1181. u = _micros() - u;
  1182. if (res)
  1183. {
  1184. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1185. sumw += u;
  1186. }
  1187. else
  1188. {
  1189. printf_P(PSTR("writeBlock %4d error\n"), i);
  1190. break;
  1191. }
  1192. }
  1193. else
  1194. {
  1195. printf_P(PSTR("readBlock %4d error\n"), i);
  1196. break;
  1197. }
  1198. }
  1199. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1200. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1201. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1202. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1203. }
  1204. else
  1205. printf_P(PSTR("Card NG!\n"));
  1206. #endif //DEBUG_SD_SPEED_TEST
  1207. eeprom_init();
  1208. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1209. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1210. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1211. #if (LANG_MODE != 0) //secondary language support
  1212. #ifdef DEBUG_XFLASH
  1213. XFLASH_SPI_ENTER();
  1214. uint8_t uid[8]; // 64bit unique id
  1215. xflash_rd_uid(uid);
  1216. puts_P(_n("XFLASH UID="));
  1217. for (uint8_t i = 0; i < 8; i ++)
  1218. printf_P(PSTR("%02x"), uid[i]);
  1219. putchar('\n');
  1220. list_sec_lang_from_external_flash();
  1221. #endif //DEBUG_XFLASH
  1222. // lang_reset();
  1223. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1224. lcd_language();
  1225. #ifdef DEBUG_SEC_LANG
  1226. uint16_t sec_lang_code = lang_get_code(1);
  1227. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1228. 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);
  1229. lang_print_sec_lang(uartout);
  1230. #endif //DEBUG_SEC_LANG
  1231. #endif //(LANG_MODE != 0)
  1232. eeprom_init_default_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1233. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1234. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1235. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1236. int16_t z_shift = 0;
  1237. for (uint8_t i = 0; i < 5; i++) {
  1238. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1239. }
  1240. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1241. }
  1242. eeprom_init_default_byte((uint8_t*)EEPROM_UVLO, 0);
  1243. eeprom_init_default_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1244. //mbl_mode_init();
  1245. mbl_settings_init();
  1246. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1247. if (SilentModeMenu_MMU == 255) {
  1248. SilentModeMenu_MMU = 1;
  1249. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1250. }
  1251. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1252. setup_fan_interrupt();
  1253. #endif //DEBUG_DISABLE_FANCHECK
  1254. #ifndef DEBUG_DISABLE_STARTMSGS
  1255. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1256. if (!farm_mode) {
  1257. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1258. check_if_fw_is_on_right_printer();
  1259. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1260. #if 0
  1261. show_fw_version_warnings();
  1262. #endif
  1263. }
  1264. switch (hw_changed) {
  1265. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1266. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1267. case(0b01):
  1268. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1269. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1270. break;
  1271. case(0b10):
  1272. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1273. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1274. break;
  1275. case(0b11):
  1276. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1277. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1278. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1279. break;
  1280. default: break; //no change, show no message
  1281. }
  1282. if (!previous_settings_retrieved) {
  1283. 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
  1284. Config_StoreSettings();
  1285. }
  1286. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1287. lcd_wizard(WizState::Run);
  1288. }
  1289. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1290. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1291. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1292. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1293. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1294. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1295. // Show the message.
  1296. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1297. }
  1298. #ifdef TEMP_MODEL
  1299. else if (calibration_status() == CALIBRATION_STATUS_TEMP_MODEL_CALIBRATION) {
  1300. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TM_NOT_CAL));
  1301. lcd_update_enable(true);
  1302. }
  1303. #endif //TEMP_MODEL
  1304. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1305. // Show the message.
  1306. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1307. lcd_update_enable(true);
  1308. }
  1309. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1310. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1311. lcd_update_enable(true);
  1312. }
  1313. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1314. // Show the message.
  1315. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1316. }
  1317. }
  1318. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1319. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1320. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1321. update_current_firmware_version_to_eeprom();
  1322. lcd_selftest();
  1323. }
  1324. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1325. KEEPALIVE_STATE(IN_PROCESS);
  1326. #endif //DEBUG_DISABLE_STARTMSGS
  1327. lcd_update_enable(true);
  1328. lcd_clear();
  1329. lcd_update(2);
  1330. // Store the currently running firmware into an eeprom,
  1331. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1332. update_current_firmware_version_to_eeprom();
  1333. #ifdef TMC2130
  1334. tmc2130_home_origin[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN, 0);
  1335. tmc2130_home_bsteps[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS, 48);
  1336. tmc2130_home_fsteps[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS, 48);
  1337. tmc2130_home_origin[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN, 0);
  1338. tmc2130_home_bsteps[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS, 48);
  1339. tmc2130_home_fsteps[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS, 48);
  1340. tmc2130_home_enabled = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED, 0);
  1341. #endif //TMC2130
  1342. // report crash failures
  1343. fw_crash_init();
  1344. #ifdef UVLO_SUPPORT
  1345. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1346. /*
  1347. if (!lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1348. else {
  1349. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1350. lcd_update_enable(true);
  1351. lcd_update(2);
  1352. lcd_setstatuspgm(MSG_WELCOME);
  1353. }
  1354. */
  1355. manage_heater(); // Update temperatures
  1356. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1357. 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));
  1358. #endif
  1359. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1360. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1361. puts_P(_N("Automatic recovery!"));
  1362. #endif
  1363. recover_print(1);
  1364. }
  1365. else{
  1366. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1367. puts_P(_N("Normal recovery!"));
  1368. #endif
  1369. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) == LCD_LEFT_BUTTON_CHOICE) {
  1370. recover_print(0);
  1371. } else {
  1372. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1373. lcd_update_enable(true);
  1374. lcd_update(2);
  1375. lcd_setstatuspgm(MSG_WELCOME);
  1376. }
  1377. }
  1378. }
  1379. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1380. // the entire state machine initialized.
  1381. setup_uvlo_interrupt();
  1382. #endif //UVLO_SUPPORT
  1383. fCheckModeInit();
  1384. KEEPALIVE_STATE(NOT_BUSY);
  1385. #ifdef WATCHDOG
  1386. wdt_enable(WDTO_4S);
  1387. #ifdef EMERGENCY_HANDLERS
  1388. WDTCSR |= (1 << WDIE);
  1389. #endif //EMERGENCY_HANDLERS
  1390. #endif //WATCHDOG
  1391. }
  1392. static inline void crash_and_burn(dump_crash_reason reason)
  1393. {
  1394. WRITE(BEEPER, HIGH);
  1395. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1396. #ifdef EMERGENCY_DUMP
  1397. xfdump_full_dump_and_reset(reason);
  1398. #elif defined(EMERGENCY_SERIAL_DUMP)
  1399. if(emergency_serial_dump)
  1400. serial_dump_and_reset(reason);
  1401. #endif
  1402. softReset();
  1403. }
  1404. #ifdef EMERGENCY_HANDLERS
  1405. #ifdef WATCHDOG
  1406. ISR(WDT_vect)
  1407. {
  1408. crash_and_burn(dump_crash_reason::watchdog);
  1409. }
  1410. #endif
  1411. ISR(BADISR_vect)
  1412. {
  1413. crash_and_burn(dump_crash_reason::bad_isr);
  1414. }
  1415. #endif //EMERGENCY_HANDLERS
  1416. void stack_error() {
  1417. crash_and_burn(dump_crash_reason::stack_error);
  1418. }
  1419. /**
  1420. * Output autoreport values according to features requested in M155
  1421. */
  1422. #if defined(AUTO_REPORT)
  1423. void host_autoreport()
  1424. {
  1425. if (autoReportFeatures.TimerExpired())
  1426. {
  1427. if(autoReportFeatures.Temp()){
  1428. gcode_M105(active_extruder);
  1429. }
  1430. if(autoReportFeatures.Pos()){
  1431. gcode_M114();
  1432. }
  1433. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1434. if(autoReportFeatures.Fans()){
  1435. gcode_M123();
  1436. }
  1437. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1438. autoReportFeatures.TimerStart();
  1439. }
  1440. }
  1441. #endif //AUTO_REPORT
  1442. /**
  1443. * Output a "busy" message at regular intervals
  1444. * while the machine is not accepting commands.
  1445. */
  1446. void host_keepalive() {
  1447. #ifndef HOST_KEEPALIVE_FEATURE
  1448. return;
  1449. #endif //HOST_KEEPALIVE_FEATURE
  1450. if (farm_mode) return;
  1451. long ms = _millis();
  1452. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1453. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1454. switch (busy_state) {
  1455. case IN_HANDLER:
  1456. case IN_PROCESS:
  1457. SERIAL_ECHO_START;
  1458. SERIAL_ECHOLNPGM("busy: processing");
  1459. break;
  1460. case PAUSED_FOR_USER:
  1461. SERIAL_ECHO_START;
  1462. SERIAL_ECHOLNPGM("busy: paused for user");
  1463. break;
  1464. case PAUSED_FOR_INPUT:
  1465. SERIAL_ECHO_START;
  1466. SERIAL_ECHOLNPGM("busy: paused for input");
  1467. break;
  1468. default:
  1469. break;
  1470. }
  1471. }
  1472. prev_busy_signal_ms = ms;
  1473. }
  1474. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1475. // Before loop(), the setup() function is called by the main() routine.
  1476. void loop()
  1477. {
  1478. // Reset a previously aborted command, we can now start processing motion again
  1479. planner_aborted = false;
  1480. if(Stopped) {
  1481. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1482. // Signal to the host that we're currently busy waiting for supervision.
  1483. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1484. } else {
  1485. // Printer is available for processing, reset state
  1486. KEEPALIVE_STATE(NOT_BUSY);
  1487. }
  1488. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1489. usb_timer.start();
  1490. }
  1491. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1492. ;
  1493. }
  1494. #ifdef PRUSA_M28
  1495. if (prusa_sd_card_upload)
  1496. {
  1497. //we read byte-by byte
  1498. serial_read_stream();
  1499. }
  1500. else
  1501. #endif
  1502. {
  1503. get_command();
  1504. #ifdef SDSUPPORT
  1505. card.checkautostart(false);
  1506. #endif
  1507. if(buflen)
  1508. {
  1509. cmdbuffer_front_already_processed = false;
  1510. #ifdef SDSUPPORT
  1511. if(card.saving)
  1512. {
  1513. // Saving a G-code file onto an SD-card is in progress.
  1514. // Saving starts with M28, saving until M29 is seen.
  1515. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1516. card.write_command(CMDBUFFER_CURRENT_STRING);
  1517. if(card.logging)
  1518. process_commands();
  1519. else
  1520. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1521. } else {
  1522. card.closefile();
  1523. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1524. }
  1525. } else {
  1526. process_commands();
  1527. }
  1528. #else
  1529. process_commands();
  1530. #endif //SDSUPPORT
  1531. if (! cmdbuffer_front_already_processed && buflen)
  1532. {
  1533. // ptr points to the start of the block currently being processed.
  1534. // The first character in the block is the block type.
  1535. char *ptr = cmdbuffer + bufindr;
  1536. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1537. // To support power panic, move the length of the command on the SD card to a planner buffer.
  1538. union {
  1539. struct {
  1540. char lo;
  1541. char hi;
  1542. } lohi;
  1543. uint16_t value;
  1544. } sdlen;
  1545. sdlen.value = 0;
  1546. {
  1547. // This block locks the interrupts globally for 3.25 us,
  1548. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1549. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1550. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1551. cli();
  1552. // Reset the command to something, which will be ignored by the power panic routine,
  1553. // so this buffer length will not be counted twice.
  1554. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1555. // Extract the current buffer length.
  1556. sdlen.lohi.lo = *ptr ++;
  1557. sdlen.lohi.hi = *ptr;
  1558. // and pass it to the planner queue.
  1559. planner_add_sd_length(sdlen.value);
  1560. sei();
  1561. }
  1562. }
  1563. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1564. cli();
  1565. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1566. // and one for each command to previous block in the planner queue.
  1567. planner_add_sd_length(1);
  1568. sei();
  1569. }
  1570. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1571. // this block's SD card length will not be counted twice as its command type has been replaced
  1572. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1573. cmdqueue_pop_front();
  1574. }
  1575. host_keepalive();
  1576. }
  1577. }
  1578. //check heater every n milliseconds
  1579. manage_heater();
  1580. manage_inactivity(isPrintPaused);
  1581. checkHitEndstops();
  1582. lcd_update(0);
  1583. #ifdef TMC2130
  1584. tmc2130_check_overtemp();
  1585. if (tmc2130_sg_crash)
  1586. {
  1587. uint8_t crash = tmc2130_sg_crash;
  1588. tmc2130_sg_crash = 0;
  1589. // crashdet_stop_and_save_print();
  1590. switch (crash)
  1591. {
  1592. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1593. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1594. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1595. }
  1596. }
  1597. #endif //TMC2130
  1598. MMU2::mmu2.mmu_loop();
  1599. }
  1600. #define DEFINE_PGM_READ_ANY(type, reader) \
  1601. static inline type pgm_read_any(const type *p) \
  1602. { return pgm_read_##reader##_near(p); }
  1603. DEFINE_PGM_READ_ANY(float, float);
  1604. DEFINE_PGM_READ_ANY(signed char, byte);
  1605. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1606. static const PROGMEM type array##_P[3] = \
  1607. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1608. static inline type array(uint8_t axis) \
  1609. { return pgm_read_any(&array##_P[axis]); } \
  1610. type array##_ext(uint8_t axis) \
  1611. { return pgm_read_any(&array##_P[axis]); }
  1612. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1613. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1614. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1615. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1616. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1617. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1618. static void axis_is_at_home(uint8_t axis) {
  1619. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1620. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1621. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1622. }
  1623. //! @return original feedmultiply
  1624. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1625. saved_feedrate = feedrate;
  1626. int l_feedmultiply = feedmultiply;
  1627. feedmultiply = 100;
  1628. previous_millis_cmd.start();
  1629. enable_endstops(enable_endstops_now);
  1630. return l_feedmultiply;
  1631. }
  1632. //! @param original_feedmultiply feedmultiply to restore
  1633. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1634. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1635. enable_endstops(false);
  1636. #endif
  1637. feedrate = saved_feedrate;
  1638. feedmultiply = original_feedmultiply;
  1639. previous_millis_cmd.start();
  1640. }
  1641. #ifdef ENABLE_AUTO_BED_LEVELING
  1642. #ifdef AUTO_BED_LEVELING_GRID
  1643. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1644. {
  1645. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1646. planeNormal.debug("planeNormal");
  1647. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1648. //bedLevel.debug("bedLevel");
  1649. //plan_bed_level_matrix.debug("bed level before");
  1650. //vector_3 uncorrected_position = plan_get_position_mm();
  1651. //uncorrected_position.debug("position before");
  1652. vector_3 corrected_position = plan_get_position();
  1653. // corrected_position.debug("position after");
  1654. current_position[X_AXIS] = corrected_position.x;
  1655. current_position[Y_AXIS] = corrected_position.y;
  1656. current_position[Z_AXIS] = corrected_position.z;
  1657. // put the bed at 0 so we don't go below it.
  1658. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1659. plan_set_position_curposXYZE();
  1660. }
  1661. #else // not AUTO_BED_LEVELING_GRID
  1662. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1663. plan_bed_level_matrix.set_to_identity();
  1664. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1665. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1666. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1667. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1668. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1669. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1670. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1671. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1672. vector_3 corrected_position = plan_get_position();
  1673. current_position[X_AXIS] = corrected_position.x;
  1674. current_position[Y_AXIS] = corrected_position.y;
  1675. current_position[Z_AXIS] = corrected_position.z;
  1676. // put the bed at 0 so we don't go below it.
  1677. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1678. plan_set_position_curposXYZE();
  1679. }
  1680. #endif // AUTO_BED_LEVELING_GRID
  1681. static void run_z_probe() {
  1682. plan_bed_level_matrix.set_to_identity();
  1683. feedrate = homing_feedrate[Z_AXIS];
  1684. // move down until you find the bed
  1685. float zPosition = -10;
  1686. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1687. st_synchronize();
  1688. // we have to let the planner know where we are right now as it is not where we said to go.
  1689. zPosition = st_get_position_mm(Z_AXIS);
  1690. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1691. // move up the retract distance
  1692. zPosition += home_retract_mm(Z_AXIS);
  1693. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1694. st_synchronize();
  1695. // move back down slowly to find bed
  1696. feedrate = homing_feedrate[Z_AXIS]/4;
  1697. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1698. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1699. st_synchronize();
  1700. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1701. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1702. plan_set_position_curposXYZE();
  1703. }
  1704. static void do_blocking_move_to(float x, float y, float z) {
  1705. float oldFeedRate = feedrate;
  1706. feedrate = homing_feedrate[Z_AXIS];
  1707. current_position[Z_AXIS] = z;
  1708. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1709. st_synchronize();
  1710. feedrate = XY_TRAVEL_SPEED;
  1711. current_position[X_AXIS] = x;
  1712. current_position[Y_AXIS] = y;
  1713. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1714. st_synchronize();
  1715. feedrate = oldFeedRate;
  1716. }
  1717. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1718. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1719. }
  1720. /// Probe bed height at position (x,y), returns the measured z value
  1721. static float probe_pt(float x, float y, float z_before) {
  1722. // move to right place
  1723. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1724. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1725. run_z_probe();
  1726. float measured_z = current_position[Z_AXIS];
  1727. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1728. SERIAL_PROTOCOLPGM(" x: ");
  1729. SERIAL_PROTOCOL(x);
  1730. SERIAL_PROTOCOLPGM(" y: ");
  1731. SERIAL_PROTOCOL(y);
  1732. SERIAL_PROTOCOLPGM(" z: ");
  1733. SERIAL_PROTOCOL(measured_z);
  1734. SERIAL_PROTOCOLPGM("\n");
  1735. return measured_z;
  1736. }
  1737. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1738. #ifdef LIN_ADVANCE
  1739. /**
  1740. * M900: Set and/or Get advance K factor
  1741. *
  1742. * K<factor> Set advance K factor
  1743. */
  1744. inline void gcode_M900() {
  1745. float newK = code_seen('K') ? code_value_float() : -2;
  1746. #ifdef LA_NOCOMPAT
  1747. if (newK >= 0 && newK < LA_K_MAX)
  1748. extruder_advance_K = newK;
  1749. else
  1750. SERIAL_ECHOLNPGM("K out of allowed range!");
  1751. #else
  1752. if (newK == 0)
  1753. {
  1754. extruder_advance_K = 0;
  1755. la10c_reset();
  1756. }
  1757. else
  1758. {
  1759. newK = la10c_value(newK);
  1760. if (newK < 0)
  1761. SERIAL_ECHOLNPGM("K out of allowed range!");
  1762. else
  1763. extruder_advance_K = newK;
  1764. }
  1765. #endif
  1766. SERIAL_ECHO_START;
  1767. SERIAL_ECHOPGM("Advance K=");
  1768. SERIAL_ECHOLN(extruder_advance_K);
  1769. }
  1770. #endif // LIN_ADVANCE
  1771. bool check_commands() {
  1772. bool end_command_found = false;
  1773. while (buflen)
  1774. {
  1775. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1776. if (!cmdbuffer_front_already_processed)
  1777. cmdqueue_pop_front();
  1778. cmdbuffer_front_already_processed = false;
  1779. }
  1780. return end_command_found;
  1781. }
  1782. /// @brief Safely move Z-axis by distance delta (mm)
  1783. /// @param delta travel distance in mm
  1784. /// @returns The actual travel distance in mm. Endstop may limit the requested move.
  1785. float raise_z(float delta)
  1786. {
  1787. float travel_z = current_position[Z_AXIS];
  1788. // Prepare to move Z axis
  1789. current_position[Z_AXIS] += delta;
  1790. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1791. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1792. #else
  1793. bool z_min_endstop = false;
  1794. #endif
  1795. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1796. {
  1797. // current position is known or very low, it's safe to raise Z
  1798. clamp_to_software_endstops(current_position);
  1799. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1800. st_synchronize();
  1801. // Get the final travel distance
  1802. travel_z = current_position[Z_AXIS] - travel_z;
  1803. } else {
  1804. // ensure Z is powered in normal mode to overcome initial load
  1805. enable_z();
  1806. st_synchronize();
  1807. // rely on crashguard to limit damage
  1808. bool z_endstop_enabled = enable_z_endstop(true);
  1809. #ifdef TMC2130
  1810. tmc2130_home_enter(Z_AXIS_MASK);
  1811. #endif //TMC2130
  1812. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1813. st_synchronize();
  1814. // Get the final travel distance
  1815. travel_z = st_get_position_mm(Z_AXIS) - travel_z;
  1816. #ifdef TMC2130
  1817. if (endstop_z_hit_on_purpose())
  1818. {
  1819. // not necessarily exact, but will avoid further vertical moves
  1820. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1821. plan_set_position_curposXYZE();
  1822. }
  1823. tmc2130_home_exit();
  1824. #endif //TMC2130
  1825. enable_z_endstop(z_endstop_enabled);
  1826. }
  1827. return travel_z;
  1828. }
  1829. // raise_z_above: slowly raise Z to the requested height
  1830. //
  1831. // contrarily to a simple move, this function will carefully plan a move
  1832. // when the current Z position is unknown. In such cases, stallguard is
  1833. // enabled and will prevent prolonged pushing against the Z tops
  1834. void raise_z_above(float target)
  1835. {
  1836. if (current_position[Z_AXIS] >= target)
  1837. return;
  1838. // Use absolute value in case the current position is unknown
  1839. raise_z(fabs(current_position[Z_AXIS] - target));
  1840. }
  1841. #ifdef TMC2130
  1842. bool calibrate_z_auto()
  1843. {
  1844. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1845. lcd_clear();
  1846. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1847. bool endstops_enabled = enable_endstops(true);
  1848. int axis_up_dir = -home_dir(Z_AXIS);
  1849. tmc2130_home_enter(Z_AXIS_MASK);
  1850. current_position[Z_AXIS] = 0;
  1851. plan_set_position_curposXYZE();
  1852. set_destination_to_current();
  1853. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1854. feedrate = homing_feedrate[Z_AXIS];
  1855. plan_buffer_line_destinationXYZE(feedrate / 60);
  1856. st_synchronize();
  1857. // current_position[axis] = 0;
  1858. // plan_set_position_curposXYZE();
  1859. tmc2130_home_exit();
  1860. enable_endstops(false);
  1861. current_position[Z_AXIS] = 0;
  1862. plan_set_position_curposXYZE();
  1863. set_destination_to_current();
  1864. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1865. feedrate = homing_feedrate[Z_AXIS] / 2;
  1866. plan_buffer_line_destinationXYZE(feedrate / 60);
  1867. st_synchronize();
  1868. enable_endstops(endstops_enabled);
  1869. if (PRINTER_TYPE == PRINTER_MK3) {
  1870. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1871. }
  1872. else {
  1873. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1874. }
  1875. plan_set_position_curposXYZE();
  1876. return true;
  1877. }
  1878. #endif //TMC2130
  1879. #ifdef TMC2130
  1880. static void check_Z_crash(void)
  1881. {
  1882. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1883. FORCE_HIGH_POWER_END;
  1884. current_position[Z_AXIS] = 0;
  1885. plan_set_position_curposXYZE();
  1886. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1887. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1888. st_synchronize();
  1889. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1890. }
  1891. }
  1892. #endif //TMC2130
  1893. #ifdef TMC2130
  1894. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1895. #else
  1896. void homeaxis(uint8_t axis, uint8_t cnt)
  1897. #endif //TMC2130
  1898. {
  1899. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1900. #define HOMEAXIS_DO(LETTER) \
  1901. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1902. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1903. {
  1904. int axis_home_dir = home_dir(axis);
  1905. feedrate = homing_feedrate[axis];
  1906. #ifdef TMC2130
  1907. tmc2130_home_enter(X_AXIS_MASK << axis);
  1908. #endif //TMC2130
  1909. // Move away a bit, so that the print head does not touch the end position,
  1910. // and the following movement to endstop has a chance to achieve the required velocity
  1911. // for the stall guard to work.
  1912. current_position[axis] = 0;
  1913. plan_set_position_curposXYZE();
  1914. set_destination_to_current();
  1915. // destination[axis] = 11.f;
  1916. destination[axis] = -3.f * axis_home_dir;
  1917. plan_buffer_line_destinationXYZE(feedrate/60);
  1918. st_synchronize();
  1919. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1920. endstops_hit_on_purpose();
  1921. enable_endstops(false);
  1922. current_position[axis] = 0;
  1923. plan_set_position_curposXYZE();
  1924. destination[axis] = 1. * axis_home_dir;
  1925. plan_buffer_line_destinationXYZE(feedrate/60);
  1926. st_synchronize();
  1927. // Now continue to move up to the left end stop with the collision detection enabled.
  1928. enable_endstops(true);
  1929. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1930. plan_buffer_line_destinationXYZE(feedrate/60);
  1931. st_synchronize();
  1932. for (uint8_t i = 0; i < cnt; i++)
  1933. {
  1934. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1935. endstops_hit_on_purpose();
  1936. enable_endstops(false);
  1937. current_position[axis] = 0;
  1938. plan_set_position_curposXYZE();
  1939. destination[axis] = -10.f * axis_home_dir;
  1940. plan_buffer_line_destinationXYZE(feedrate/60);
  1941. st_synchronize();
  1942. endstops_hit_on_purpose();
  1943. // Now move left up to the collision, this time with a repeatable velocity.
  1944. enable_endstops(true);
  1945. destination[axis] = 11.f * axis_home_dir;
  1946. #ifdef TMC2130
  1947. feedrate = homing_feedrate[axis];
  1948. #else //TMC2130
  1949. feedrate = homing_feedrate[axis] / 2;
  1950. #endif //TMC2130
  1951. plan_buffer_line_destinationXYZE(feedrate/60);
  1952. st_synchronize();
  1953. #ifdef TMC2130
  1954. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1955. if (pstep) pstep[i] = mscnt >> 4;
  1956. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1957. #endif //TMC2130
  1958. }
  1959. endstops_hit_on_purpose();
  1960. enable_endstops(false);
  1961. #ifdef TMC2130
  1962. uint8_t orig = tmc2130_home_origin[axis];
  1963. uint8_t back = tmc2130_home_bsteps[axis];
  1964. if (tmc2130_home_enabled && (orig <= 63))
  1965. {
  1966. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1967. if (back > 0)
  1968. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1969. }
  1970. else
  1971. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1972. tmc2130_home_exit();
  1973. #endif //TMC2130
  1974. axis_is_at_home(axis);
  1975. axis_known_position[axis] = true;
  1976. // Move from minimum
  1977. #ifdef TMC2130
  1978. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1979. #else //TMC2130
  1980. float dist = - axis_home_dir * 0.01f * 64;
  1981. #endif //TMC2130
  1982. current_position[axis] -= dist;
  1983. plan_set_position_curposXYZE();
  1984. current_position[axis] += dist;
  1985. destination[axis] = current_position[axis];
  1986. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1987. st_synchronize();
  1988. feedrate = 0.0;
  1989. }
  1990. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1991. {
  1992. #ifdef TMC2130
  1993. FORCE_HIGH_POWER_START;
  1994. #endif
  1995. int axis_home_dir = home_dir(axis);
  1996. current_position[axis] = 0;
  1997. plan_set_position_curposXYZE();
  1998. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1999. feedrate = homing_feedrate[axis];
  2000. plan_buffer_line_destinationXYZE(feedrate/60);
  2001. st_synchronize();
  2002. #ifdef TMC2130
  2003. check_Z_crash();
  2004. #endif //TMC2130
  2005. current_position[axis] = 0;
  2006. plan_set_position_curposXYZE();
  2007. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  2008. plan_buffer_line_destinationXYZE(feedrate/60);
  2009. st_synchronize();
  2010. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  2011. feedrate = homing_feedrate[axis]/2 ;
  2012. plan_buffer_line_destinationXYZE(feedrate/60);
  2013. st_synchronize();
  2014. #ifdef TMC2130
  2015. check_Z_crash();
  2016. #endif //TMC2130
  2017. axis_is_at_home(axis);
  2018. destination[axis] = current_position[axis];
  2019. feedrate = 0.0;
  2020. endstops_hit_on_purpose();
  2021. axis_known_position[axis] = true;
  2022. #ifdef TMC2130
  2023. FORCE_HIGH_POWER_END;
  2024. #endif
  2025. }
  2026. enable_endstops(endstops_enabled);
  2027. }
  2028. /**/
  2029. void home_xy()
  2030. {
  2031. set_destination_to_current();
  2032. homeaxis(X_AXIS);
  2033. homeaxis(Y_AXIS);
  2034. plan_set_position_curposXYZE();
  2035. endstops_hit_on_purpose();
  2036. }
  2037. void refresh_cmd_timeout(void)
  2038. {
  2039. previous_millis_cmd.start();
  2040. }
  2041. #ifdef FWRETRACT
  2042. void retract(bool retracting, bool swapretract = false) {
  2043. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2044. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2045. // position, which requires a sync
  2046. if(retracting && !retracted[active_extruder]) {
  2047. st_synchronize();
  2048. set_destination_to_current();
  2049. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2050. plan_set_e_position(current_position[E_AXIS]);
  2051. float oldFeedrate = feedrate;
  2052. feedrate=cs.retract_feedrate*60;
  2053. retracted[active_extruder]=true;
  2054. prepare_move();
  2055. if(cs.retract_zlift) {
  2056. st_synchronize();
  2057. current_position[Z_AXIS]-=cs.retract_zlift;
  2058. plan_set_position_curposXYZE();
  2059. prepare_move();
  2060. }
  2061. feedrate = oldFeedrate;
  2062. } else if(!retracting && retracted[active_extruder]) {
  2063. st_synchronize();
  2064. set_destination_to_current();
  2065. float oldFeedrate = feedrate;
  2066. feedrate=cs.retract_recover_feedrate*60;
  2067. if(cs.retract_zlift) {
  2068. current_position[Z_AXIS]+=cs.retract_zlift;
  2069. plan_set_position_curposXYZE();
  2070. prepare_move();
  2071. st_synchronize();
  2072. }
  2073. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2074. plan_set_e_position(current_position[E_AXIS]);
  2075. retracted[active_extruder]=false;
  2076. prepare_move();
  2077. feedrate = oldFeedrate;
  2078. }
  2079. } //retract
  2080. #endif //FWRETRACT
  2081. #ifdef TMC2130
  2082. void force_high_power_mode(bool start_high_power_section) {
  2083. #ifdef PSU_Delta
  2084. if (start_high_power_section == true) enable_force_z();
  2085. #endif //PSU_Delta
  2086. uint8_t silent;
  2087. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2088. if (silent == 1) {
  2089. //we are in silent mode, set to normal mode to enable crash detection
  2090. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2091. st_synchronize();
  2092. cli();
  2093. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2094. update_mode_profile();
  2095. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2096. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2097. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2098. st_reset_timer();
  2099. sei();
  2100. }
  2101. }
  2102. #endif //TMC2130
  2103. void gcode_M105(uint8_t extruder)
  2104. {
  2105. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2106. SERIAL_PROTOCOLPGM("T:");
  2107. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2108. SERIAL_PROTOCOLPGM(" /");
  2109. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2110. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2111. SERIAL_PROTOCOLPGM(" B:");
  2112. SERIAL_PROTOCOL_F(degBed(),1);
  2113. SERIAL_PROTOCOLPGM(" /");
  2114. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2115. #endif //TEMP_BED_PIN
  2116. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2117. SERIAL_PROTOCOLPGM(" T");
  2118. SERIAL_PROTOCOL(cur_extruder);
  2119. SERIAL_PROTOCOL(':');
  2120. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2121. SERIAL_PROTOCOLPGM(" /");
  2122. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2123. }
  2124. #else
  2125. SERIAL_ERROR_START;
  2126. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2127. #endif
  2128. SERIAL_PROTOCOLPGM(" @:");
  2129. #ifdef EXTRUDER_WATTS
  2130. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2131. SERIAL_PROTOCOLPGM("W");
  2132. #else
  2133. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2134. #endif
  2135. SERIAL_PROTOCOLPGM(" B@:");
  2136. #ifdef BED_WATTS
  2137. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2138. SERIAL_PROTOCOLPGM("W");
  2139. #else
  2140. SERIAL_PROTOCOL(getHeaterPower(-1));
  2141. #endif
  2142. #ifdef PINDA_THERMISTOR
  2143. SERIAL_PROTOCOLPGM(" P:");
  2144. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2145. #endif //PINDA_THERMISTOR
  2146. #ifdef AMBIENT_THERMISTOR
  2147. SERIAL_PROTOCOLPGM(" A:");
  2148. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2149. #endif //AMBIENT_THERMISTOR
  2150. #ifdef SHOW_TEMP_ADC_VALUES
  2151. {
  2152. float raw = 0.0;
  2153. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2154. SERIAL_PROTOCOLPGM(" ADC B:");
  2155. SERIAL_PROTOCOL_F(degBed(),1);
  2156. SERIAL_PROTOCOLPGM("C->");
  2157. raw = rawBedTemp();
  2158. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2159. SERIAL_PROTOCOLPGM(" Rb->");
  2160. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2161. SERIAL_PROTOCOLPGM(" Rxb->");
  2162. SERIAL_PROTOCOL_F(raw, 5);
  2163. #endif
  2164. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2165. SERIAL_PROTOCOLPGM(" T");
  2166. SERIAL_PROTOCOL(cur_extruder);
  2167. SERIAL_PROTOCOLPGM(":");
  2168. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2169. SERIAL_PROTOCOLPGM("C->");
  2170. raw = rawHotendTemp(cur_extruder);
  2171. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2172. SERIAL_PROTOCOLPGM(" Rt");
  2173. SERIAL_PROTOCOL(cur_extruder);
  2174. SERIAL_PROTOCOLPGM("->");
  2175. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2176. SERIAL_PROTOCOLPGM(" Rx");
  2177. SERIAL_PROTOCOL(cur_extruder);
  2178. SERIAL_PROTOCOLPGM("->");
  2179. SERIAL_PROTOCOL_F(raw, 5);
  2180. }
  2181. }
  2182. #endif
  2183. SERIAL_PROTOCOLLN();
  2184. }
  2185. #ifdef TMC2130
  2186. 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)
  2187. #else
  2188. 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)
  2189. #endif //TMC2130
  2190. {
  2191. // Flag for the display update routine and to disable the print cancelation during homing.
  2192. st_synchronize();
  2193. homing_flag = true;
  2194. #if 0
  2195. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2196. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2197. #endif
  2198. // Which axes should be homed?
  2199. bool home_x = home_x_axis;
  2200. bool home_y = home_y_axis;
  2201. bool home_z = home_z_axis;
  2202. // Either all X,Y,Z codes are present, or none of them.
  2203. bool home_all_axes = home_x == home_y && home_x == home_z;
  2204. if (home_all_axes)
  2205. // No X/Y/Z code provided means to home all axes.
  2206. home_x = home_y = home_z = true;
  2207. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2208. if (home_all_axes) {
  2209. raise_z_above(MESH_HOME_Z_SEARCH);
  2210. }
  2211. #ifdef ENABLE_AUTO_BED_LEVELING
  2212. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2213. #endif //ENABLE_AUTO_BED_LEVELING
  2214. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2215. // the planner will not perform any adjustments in the XY plane.
  2216. // Wait for the motors to stop and update the current position with the absolute values.
  2217. world2machine_revert_to_uncorrected();
  2218. // For mesh bed leveling deactivate the matrix temporarily.
  2219. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2220. // in a single axis only.
  2221. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2222. #ifdef MESH_BED_LEVELING
  2223. uint8_t mbl_was_active = mbl.active;
  2224. mbl.active = 0;
  2225. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2226. #endif
  2227. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2228. if (home_z)
  2229. babystep_undo();
  2230. int l_feedmultiply = setup_for_endstop_move();
  2231. set_destination_to_current();
  2232. feedrate = 0.0;
  2233. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2234. if(home_z)
  2235. homeaxis(Z_AXIS);
  2236. #endif
  2237. #ifdef QUICK_HOME
  2238. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2239. if(home_x && home_y) //first diagonal move
  2240. {
  2241. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2242. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2243. plan_set_position_curposXYZE();
  2244. 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);
  2245. feedrate = homing_feedrate[X_AXIS];
  2246. if(homing_feedrate[Y_AXIS]<feedrate)
  2247. feedrate = homing_feedrate[Y_AXIS];
  2248. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2249. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2250. } else {
  2251. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2252. }
  2253. plan_buffer_line_destinationXYZE(feedrate/60);
  2254. st_synchronize();
  2255. axis_is_at_home(X_AXIS);
  2256. axis_is_at_home(Y_AXIS);
  2257. plan_set_position_curposXYZE();
  2258. destination[X_AXIS] = current_position[X_AXIS];
  2259. destination[Y_AXIS] = current_position[Y_AXIS];
  2260. plan_buffer_line_destinationXYZE(feedrate/60);
  2261. feedrate = 0.0;
  2262. st_synchronize();
  2263. endstops_hit_on_purpose();
  2264. current_position[X_AXIS] = destination[X_AXIS];
  2265. current_position[Y_AXIS] = destination[Y_AXIS];
  2266. current_position[Z_AXIS] = destination[Z_AXIS];
  2267. }
  2268. #endif /* QUICK_HOME */
  2269. #ifdef TMC2130
  2270. if(home_x)
  2271. {
  2272. if (!calib)
  2273. homeaxis(X_AXIS);
  2274. else
  2275. tmc2130_home_calibrate(X_AXIS);
  2276. }
  2277. if(home_y)
  2278. {
  2279. if (!calib)
  2280. homeaxis(Y_AXIS);
  2281. else
  2282. tmc2130_home_calibrate(Y_AXIS);
  2283. }
  2284. #else //TMC2130
  2285. if(home_x) homeaxis(X_AXIS);
  2286. if(home_y) homeaxis(Y_AXIS);
  2287. #endif //TMC2130
  2288. if(home_x_axis && home_x_value != 0)
  2289. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2290. if(home_y_axis && home_y_value != 0)
  2291. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2292. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2293. #ifndef Z_SAFE_HOMING
  2294. if(home_z) {
  2295. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2296. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2297. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2298. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2299. raise_z_above(MESH_HOME_Z_SEARCH);
  2300. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2301. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2302. // 1st mesh bed leveling measurement point, corrected.
  2303. world2machine_initialize();
  2304. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2305. world2machine_reset();
  2306. if (destination[Y_AXIS] < Y_MIN_POS)
  2307. destination[Y_AXIS] = Y_MIN_POS;
  2308. feedrate = homing_feedrate[X_AXIS] / 20;
  2309. enable_endstops(false);
  2310. #ifdef DEBUG_BUILD
  2311. SERIAL_ECHOLNPGM("plan_set_position()");
  2312. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2313. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2314. #endif
  2315. plan_set_position_curposXYZE();
  2316. #ifdef DEBUG_BUILD
  2317. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2318. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2319. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2320. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2321. #endif
  2322. plan_buffer_line_destinationXYZE(feedrate);
  2323. st_synchronize();
  2324. current_position[X_AXIS] = destination[X_AXIS];
  2325. current_position[Y_AXIS] = destination[Y_AXIS];
  2326. enable_endstops(true);
  2327. endstops_hit_on_purpose();
  2328. homeaxis(Z_AXIS);
  2329. #else // MESH_BED_LEVELING
  2330. homeaxis(Z_AXIS);
  2331. #endif // MESH_BED_LEVELING
  2332. }
  2333. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2334. if(home_all_axes) {
  2335. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2336. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2337. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2338. feedrate = XY_TRAVEL_SPEED/60;
  2339. current_position[Z_AXIS] = 0;
  2340. plan_set_position_curposXYZE();
  2341. plan_buffer_line_destinationXYZE(feedrate);
  2342. st_synchronize();
  2343. current_position[X_AXIS] = destination[X_AXIS];
  2344. current_position[Y_AXIS] = destination[Y_AXIS];
  2345. homeaxis(Z_AXIS);
  2346. }
  2347. // Let's see if X and Y are homed and probe is inside bed area.
  2348. if(home_z) {
  2349. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2350. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2351. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2352. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2353. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2354. current_position[Z_AXIS] = 0;
  2355. plan_set_position_curposXYZE();
  2356. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2357. feedrate = max_feedrate[Z_AXIS];
  2358. plan_buffer_line_destinationXYZE(feedrate);
  2359. st_synchronize();
  2360. homeaxis(Z_AXIS);
  2361. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2362. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2363. SERIAL_ECHO_START;
  2364. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2365. } else {
  2366. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2367. SERIAL_ECHO_START;
  2368. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2369. }
  2370. }
  2371. #endif // Z_SAFE_HOMING
  2372. #endif // Z_HOME_DIR < 0
  2373. if(home_z_axis && home_z_value != 0)
  2374. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2375. #ifdef ENABLE_AUTO_BED_LEVELING
  2376. if(home_z)
  2377. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2378. #endif
  2379. // Set the planner and stepper routine positions.
  2380. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2381. // contains the machine coordinates.
  2382. plan_set_position_curposXYZE();
  2383. clean_up_after_endstop_move(l_feedmultiply);
  2384. endstops_hit_on_purpose();
  2385. // Load the machine correction matrix
  2386. world2machine_initialize();
  2387. // and correct the current_position XY axes to match the transformed coordinate system.
  2388. world2machine_update_current();
  2389. #ifdef MESH_BED_LEVELING
  2390. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2391. {
  2392. if (! home_z && mbl_was_active) {
  2393. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2394. mbl.active = true;
  2395. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2396. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2397. }
  2398. }
  2399. #endif
  2400. prusa_statistics(20);
  2401. st_synchronize();
  2402. homing_flag = false;
  2403. #if 0
  2404. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2405. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2406. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2407. #endif
  2408. }
  2409. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2410. {
  2411. #ifdef TMC2130
  2412. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2413. #else
  2414. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2415. #endif //TMC2130
  2416. }
  2417. // G80 - Automatic mesh bed leveling
  2418. static void gcode_G80()
  2419. {
  2420. st_synchronize();
  2421. if (planner_aborted)
  2422. return;
  2423. mesh_bed_leveling_flag = true;
  2424. #ifndef PINDA_THERMISTOR
  2425. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2426. #endif // ndef PINDA_THERMISTOR
  2427. #ifdef SUPPORT_VERBOSITY
  2428. int8_t verbosity_level = 0;
  2429. if (code_seen('V')) {
  2430. // Just 'V' without a number counts as V1.
  2431. char c = strchr_pointer[1];
  2432. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2433. }
  2434. #endif //SUPPORT_VERBOSITY
  2435. // Firstly check if we know where we are
  2436. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2437. // We don't know where we are! HOME!
  2438. // Push the commands to the front of the message queue in the reverse order!
  2439. // There shall be always enough space reserved for these commands.
  2440. repeatcommand_front(); // repeat G80 with all its parameters
  2441. enquecommand_front_P(G28W0);
  2442. return;
  2443. }
  2444. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2445. if (code_seen('N')) {
  2446. nMeasPoints = code_value_uint8();
  2447. if (nMeasPoints != 7) {
  2448. nMeasPoints = 3;
  2449. }
  2450. }
  2451. else {
  2452. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2453. }
  2454. uint8_t nProbeRetry = 3;
  2455. if (code_seen('R')) {
  2456. nProbeRetry = code_value_uint8();
  2457. if (nProbeRetry > 10) {
  2458. nProbeRetry = 10;
  2459. }
  2460. }
  2461. else {
  2462. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2463. }
  2464. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2465. #ifndef PINDA_THERMISTOR
  2466. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2467. {
  2468. temp_compensation_start();
  2469. run = true;
  2470. repeatcommand_front(); // repeat G80 with all its parameters
  2471. enquecommand_front_P(G28W0);
  2472. break;
  2473. }
  2474. run = false;
  2475. #endif //PINDA_THERMISTOR
  2476. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2477. CustomMsg custom_message_type_old = custom_message_type;
  2478. uint8_t custom_message_state_old = custom_message_state;
  2479. custom_message_type = CustomMsg::MeshBedLeveling;
  2480. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2481. lcd_update(1);
  2482. mbl.reset(); //reset mesh bed leveling
  2483. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2484. babystep_undo();
  2485. // Cycle through all points and probe them
  2486. // First move up. During this first movement, the babystepping will be reverted.
  2487. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2488. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2489. // The move to the first calibration point.
  2490. current_position[X_AXIS] = BED_X0;
  2491. current_position[Y_AXIS] = BED_Y0;
  2492. #ifdef SUPPORT_VERBOSITY
  2493. if (verbosity_level >= 1)
  2494. {
  2495. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2496. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2497. }
  2498. #else //SUPPORT_VERBOSITY
  2499. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2500. #endif //SUPPORT_VERBOSITY
  2501. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2502. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2503. // Wait until the move is finished.
  2504. st_synchronize();
  2505. if (planner_aborted)
  2506. {
  2507. custom_message_type = custom_message_type_old;
  2508. custom_message_state = custom_message_state_old;
  2509. return;
  2510. }
  2511. uint8_t mesh_point = 0; //index number of calibration point
  2512. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2513. 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)
  2514. #ifdef SUPPORT_VERBOSITY
  2515. if (verbosity_level >= 1) {
  2516. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2517. }
  2518. #endif // SUPPORT_VERBOSITY
  2519. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2520. while (mesh_point != nMeasPoints * nMeasPoints) {
  2521. // Get coords of a measuring point.
  2522. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2523. uint8_t iy = mesh_point / nMeasPoints;
  2524. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2525. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2526. custom_message_state--;
  2527. mesh_point++;
  2528. continue; //skip
  2529. }*/
  2530. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2531. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2532. {
  2533. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2534. }
  2535. float z0 = 0.f;
  2536. if (has_z && (mesh_point > 0)) {
  2537. uint16_t z_offset_u = 0;
  2538. if (nMeasPoints == 7) {
  2539. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2540. }
  2541. else {
  2542. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2543. }
  2544. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2545. #ifdef SUPPORT_VERBOSITY
  2546. if (verbosity_level >= 1) {
  2547. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2548. }
  2549. #endif // SUPPORT_VERBOSITY
  2550. }
  2551. // Move Z up to MESH_HOME_Z_SEARCH.
  2552. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2553. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2554. float init_z_bckp = current_position[Z_AXIS];
  2555. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2556. st_synchronize();
  2557. // Move to XY position of the sensor point.
  2558. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2559. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2560. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2561. #ifdef SUPPORT_VERBOSITY
  2562. if (verbosity_level >= 1) {
  2563. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2564. SERIAL_PROTOCOL(mesh_point);
  2565. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2566. }
  2567. #else //SUPPORT_VERBOSITY
  2568. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2569. #endif // SUPPORT_VERBOSITY
  2570. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2571. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2572. st_synchronize();
  2573. if (planner_aborted)
  2574. {
  2575. custom_message_type = custom_message_type_old;
  2576. custom_message_state = custom_message_state_old;
  2577. return;
  2578. }
  2579. // Go down until endstop is hit
  2580. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2581. 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
  2582. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2583. break;
  2584. }
  2585. 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.
  2586. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2587. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2588. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2589. st_synchronize();
  2590. 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
  2591. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2592. break;
  2593. }
  2594. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2595. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2596. break;
  2597. }
  2598. }
  2599. 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
  2600. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2601. break;
  2602. }
  2603. #ifdef SUPPORT_VERBOSITY
  2604. if (verbosity_level >= 10) {
  2605. SERIAL_ECHOPGM("X: ");
  2606. MYSERIAL.print(current_position[X_AXIS], 5);
  2607. SERIAL_ECHOLNPGM("");
  2608. SERIAL_ECHOPGM("Y: ");
  2609. MYSERIAL.print(current_position[Y_AXIS], 5);
  2610. SERIAL_PROTOCOLPGM("\n");
  2611. }
  2612. #endif // SUPPORT_VERBOSITY
  2613. float offset_z = 0;
  2614. #ifdef PINDA_THERMISTOR
  2615. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2616. #endif //PINDA_THERMISTOR
  2617. // #ifdef SUPPORT_VERBOSITY
  2618. /* if (verbosity_level >= 1)
  2619. {
  2620. SERIAL_ECHOPGM("mesh bed leveling: ");
  2621. MYSERIAL.print(current_position[Z_AXIS], 5);
  2622. SERIAL_ECHOPGM(" offset: ");
  2623. MYSERIAL.print(offset_z, 5);
  2624. SERIAL_ECHOLNPGM("");
  2625. }*/
  2626. // #endif // SUPPORT_VERBOSITY
  2627. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2628. custom_message_state--;
  2629. mesh_point++;
  2630. lcd_update(1);
  2631. }
  2632. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2633. #ifdef SUPPORT_VERBOSITY
  2634. if (verbosity_level >= 20) {
  2635. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2636. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2637. MYSERIAL.print(current_position[Z_AXIS], 5);
  2638. }
  2639. #endif // SUPPORT_VERBOSITY
  2640. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2641. st_synchronize();
  2642. if (mesh_point != nMeasPoints * nMeasPoints) {
  2643. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2644. bool bState;
  2645. do { // repeat until Z-leveling o.k.
  2646. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2647. #ifdef TMC2130
  2648. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2649. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2650. #else // TMC2130
  2651. lcd_wait_for_click_delay(0); // ~ no timeout
  2652. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2653. #endif // TMC2130
  2654. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2655. bState=enable_z_endstop(false);
  2656. raise_z(-1);
  2657. enable_z_endstop(true);
  2658. #ifdef TMC2130
  2659. tmc2130_home_enter(Z_AXIS_MASK);
  2660. #endif // TMC2130
  2661. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2662. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2663. st_synchronize();
  2664. #ifdef TMC2130
  2665. tmc2130_home_exit();
  2666. #endif // TMC2130
  2667. enable_z_endstop(bState);
  2668. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2669. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2670. custom_message_type = custom_message_type_old;
  2671. custom_message_state = custom_message_state_old;
  2672. lcd_update_enable(true); // display / status-line recovery
  2673. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2674. repeatcommand_front(); // re-run (i.e. of "G80")
  2675. return;
  2676. }
  2677. clean_up_after_endstop_move(l_feedmultiply);
  2678. // SERIAL_ECHOLNPGM("clean up finished ");
  2679. #ifndef PINDA_THERMISTOR
  2680. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2681. #endif
  2682. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2683. // SERIAL_ECHOLNPGM("babystep applied");
  2684. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2685. #ifdef SUPPORT_VERBOSITY
  2686. if (verbosity_level >= 1) {
  2687. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2688. }
  2689. #endif // SUPPORT_VERBOSITY
  2690. for (uint8_t i = 0; i < 4; ++i) {
  2691. static const char codes[4] PROGMEM = { 'L', 'R', 'F', 'B' };
  2692. static uint8_t *const eep_addresses[4] PROGMEM = {
  2693. (uint8_t*)EEPROM_BED_CORRECTION_LEFT,
  2694. (uint8_t*)EEPROM_BED_CORRECTION_RIGHT,
  2695. (uint8_t*)EEPROM_BED_CORRECTION_FRONT,
  2696. (uint8_t*)EEPROM_BED_CORRECTION_REAR,
  2697. };
  2698. long correction = 0;
  2699. if (code_seen(pgm_read_byte(&codes[i])))
  2700. correction = code_value_long();
  2701. else if (eeprom_bed_correction_valid)
  2702. correction = (int8_t)eeprom_read_byte((uint8_t*)pgm_read_ptr(&eep_addresses[i]));
  2703. if (correction == 0)
  2704. continue;
  2705. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2706. SERIAL_ERROR_START;
  2707. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2708. SERIAL_ECHO(correction);
  2709. SERIAL_ECHOLNPGM(" microns");
  2710. }
  2711. else {
  2712. float offset = float(correction) * 0.001f;
  2713. switch (i) {
  2714. case 0:
  2715. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2716. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2717. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2718. }
  2719. }
  2720. break;
  2721. case 1:
  2722. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2723. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2724. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2725. }
  2726. }
  2727. break;
  2728. case 2:
  2729. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2730. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2731. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2732. }
  2733. }
  2734. break;
  2735. case 3:
  2736. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2737. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2738. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2739. }
  2740. }
  2741. break;
  2742. }
  2743. }
  2744. }
  2745. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2746. if (nMeasPoints == 3) {
  2747. 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)
  2748. }
  2749. /*
  2750. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2751. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2752. SERIAL_PROTOCOLPGM(",");
  2753. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2754. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2755. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2756. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2757. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2758. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2759. SERIAL_PROTOCOLPGM(" ");
  2760. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2761. }
  2762. SERIAL_PROTOCOLPGM("\n");
  2763. }
  2764. */
  2765. if (nMeasPoints == 7 && magnet_elimination) {
  2766. mbl_interpolation(nMeasPoints);
  2767. }
  2768. /*
  2769. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2770. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2771. SERIAL_PROTOCOLPGM(",");
  2772. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2773. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2774. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2775. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2776. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2777. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2778. SERIAL_PROTOCOLPGM(" ");
  2779. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2780. }
  2781. SERIAL_PROTOCOLPGM("\n");
  2782. }
  2783. */
  2784. // SERIAL_ECHOLNPGM("Upsample finished");
  2785. mbl.active = 1; //activate mesh bed leveling
  2786. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2787. go_home_with_z_lift();
  2788. // SERIAL_ECHOLNPGM("Go home finished");
  2789. //unretract (after PINDA preheat retraction)
  2790. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2791. current_position[E_AXIS] += default_retraction;
  2792. plan_buffer_line_curposXYZE(400);
  2793. }
  2794. KEEPALIVE_STATE(NOT_BUSY);
  2795. // Restore custom message state
  2796. lcd_setstatuspgm(MSG_WELCOME);
  2797. custom_message_type = custom_message_type_old;
  2798. custom_message_state = custom_message_state_old;
  2799. lcd_update(2);
  2800. st_synchronize();
  2801. mesh_bed_leveling_flag = false;
  2802. }
  2803. void adjust_bed_reset()
  2804. {
  2805. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2806. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2807. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2808. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2809. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2810. }
  2811. //! @brief Calibrate XYZ
  2812. //! @param onlyZ if true, calibrate only Z axis
  2813. //! @param verbosity_level
  2814. //! @retval true Succeeded
  2815. //! @retval false Failed
  2816. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2817. {
  2818. bool final_result = false;
  2819. #ifdef TMC2130
  2820. FORCE_HIGH_POWER_START;
  2821. #endif // TMC2130
  2822. FORCE_BL_ON_START;
  2823. // Only Z calibration?
  2824. if (!onlyZ)
  2825. {
  2826. setTargetBed(0);
  2827. setAllTargetHotends(0);
  2828. adjust_bed_reset(); //reset bed level correction
  2829. }
  2830. // Disable the default update procedure of the display. We will do a modal dialog.
  2831. lcd_update_enable(false);
  2832. // Let the planner use the uncorrected coordinates.
  2833. mbl.reset();
  2834. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2835. // the planner will not perform any adjustments in the XY plane.
  2836. // Wait for the motors to stop and update the current position with the absolute values.
  2837. world2machine_revert_to_uncorrected();
  2838. // Reset the baby step value applied without moving the axes.
  2839. babystep_reset();
  2840. // Mark all axes as in a need for homing.
  2841. memset(axis_known_position, 0, sizeof(axis_known_position));
  2842. // Home in the XY plane.
  2843. //set_destination_to_current();
  2844. int l_feedmultiply = setup_for_endstop_move();
  2845. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2846. raise_z_above(MESH_HOME_Z_SEARCH);
  2847. home_xy();
  2848. enable_endstops(false);
  2849. current_position[X_AXIS] += 5;
  2850. current_position[Y_AXIS] += 5;
  2851. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2852. st_synchronize();
  2853. // Let the user move the Z axes up to the end stoppers.
  2854. #ifdef TMC2130
  2855. if (calibrate_z_auto())
  2856. {
  2857. #else //TMC2130
  2858. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2859. {
  2860. #endif //TMC2130
  2861. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2862. if(onlyZ){
  2863. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2864. lcd_puts_at_P(0,3,_n("1/9"));
  2865. }else{
  2866. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2867. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2868. lcd_puts_at_P(0,3,_n("1/4"));
  2869. }
  2870. refresh_cmd_timeout();
  2871. #ifndef STEEL_SHEET
  2872. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2873. {
  2874. lcd_wait_for_cool_down();
  2875. }
  2876. #endif //STEEL_SHEET
  2877. if(!onlyZ)
  2878. {
  2879. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2880. #ifdef STEEL_SHEET
  2881. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  2882. if(result == LCD_LEFT_BUTTON_CHOICE) {
  2883. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2884. }
  2885. #endif //STEEL_SHEET
  2886. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2887. KEEPALIVE_STATE(IN_HANDLER);
  2888. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2889. lcd_puts_at_P(0,3,_n("1/4"));
  2890. }
  2891. bool endstops_enabled = enable_endstops(false);
  2892. raise_z(-1);
  2893. // Move the print head close to the bed.
  2894. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2895. enable_endstops(true);
  2896. #ifdef TMC2130
  2897. tmc2130_home_enter(Z_AXIS_MASK);
  2898. #endif //TMC2130
  2899. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2900. st_synchronize();
  2901. #ifdef TMC2130
  2902. tmc2130_home_exit();
  2903. #endif //TMC2130
  2904. enable_endstops(endstops_enabled);
  2905. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2906. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2907. {
  2908. if (onlyZ)
  2909. {
  2910. clean_up_after_endstop_move(l_feedmultiply);
  2911. // Z only calibration.
  2912. // Load the machine correction matrix
  2913. world2machine_initialize();
  2914. // and correct the current_position to match the transformed coordinate system.
  2915. world2machine_update_current();
  2916. //FIXME
  2917. bool result = sample_mesh_and_store_reference();
  2918. if (result)
  2919. {
  2920. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2921. {
  2922. // Shipped, the nozzle height has been set already. The user can start printing now.
  2923. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2924. }
  2925. final_result = true;
  2926. // babystep_apply();
  2927. }
  2928. }
  2929. else
  2930. {
  2931. // Reset the baby step value and the baby step applied flag.
  2932. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2933. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2934. // Complete XYZ calibration.
  2935. uint8_t point_too_far_mask = 0;
  2936. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2937. clean_up_after_endstop_move(l_feedmultiply);
  2938. // Print head up.
  2939. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2940. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2941. st_synchronize();
  2942. //#ifndef NEW_XYZCAL
  2943. if (result >= 0)
  2944. {
  2945. #ifdef HEATBED_V2
  2946. sample_z();
  2947. #else //HEATBED_V2
  2948. point_too_far_mask = 0;
  2949. // Second half: The fine adjustment.
  2950. // Let the planner use the uncorrected coordinates.
  2951. mbl.reset();
  2952. world2machine_reset();
  2953. // Home in the XY plane.
  2954. int l_feedmultiply = setup_for_endstop_move();
  2955. home_xy();
  2956. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2957. clean_up_after_endstop_move(l_feedmultiply);
  2958. // Print head up.
  2959. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2960. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2961. st_synchronize();
  2962. // if (result >= 0) babystep_apply();
  2963. #endif //HEATBED_V2
  2964. }
  2965. //#endif //NEW_XYZCAL
  2966. lcd_update_enable(true);
  2967. lcd_update(2);
  2968. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2969. if (result >= 0)
  2970. {
  2971. #ifdef TEMP_MODEL
  2972. calibration_status_store(CALIBRATION_STATUS_TEMP_MODEL_CALIBRATION);
  2973. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_TM_NOT_CAL));
  2974. #else
  2975. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2976. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2977. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2978. #endif //TEMP_MODEL
  2979. final_result = true;
  2980. }
  2981. }
  2982. #ifdef TMC2130
  2983. tmc2130_home_exit();
  2984. #endif
  2985. }
  2986. else
  2987. {
  2988. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2989. final_result = false;
  2990. }
  2991. }
  2992. else
  2993. {
  2994. // Timeouted.
  2995. }
  2996. lcd_update_enable(true);
  2997. #ifdef TMC2130
  2998. FORCE_HIGH_POWER_END;
  2999. #endif // TMC2130
  3000. FORCE_BL_ON_END;
  3001. return final_result;
  3002. }
  3003. void gcode_M114()
  3004. {
  3005. SERIAL_PROTOCOLPGM("X:");
  3006. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3007. SERIAL_PROTOCOLPGM(" Y:");
  3008. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3009. SERIAL_PROTOCOLPGM(" Z:");
  3010. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3011. SERIAL_PROTOCOLPGM(" E:");
  3012. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3013. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  3014. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  3015. SERIAL_PROTOCOLPGM(" Y:");
  3016. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  3017. SERIAL_PROTOCOLPGM(" Z:");
  3018. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  3019. SERIAL_PROTOCOLPGM(" E:");
  3020. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3021. }
  3022. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3023. void gcode_M123()
  3024. {
  3025. 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);
  3026. }
  3027. #endif //FANCHECK and TACH_0 or TACH_1
  3028. static void mmu_M600_wait_and_beep() {
  3029. // Beep and wait for user to remove old filament and prepare new filament for load
  3030. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3031. int counterBeep = 0;
  3032. 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
  3033. bool bFirst = true;
  3034. while (!lcd_clicked()) {
  3035. manage_heater();
  3036. manage_inactivity(true);
  3037. #if BEEPER > 0
  3038. if (counterBeep == 500) {
  3039. counterBeep = 0;
  3040. }
  3041. SET_OUTPUT(BEEPER);
  3042. if (counterBeep == 0) {
  3043. if ((eSoundMode == e_SOUND_MODE_BLIND) || (eSoundMode == e_SOUND_MODE_LOUD) || ((eSoundMode == e_SOUND_MODE_ONCE) && bFirst)) {
  3044. bFirst = false;
  3045. WRITE(BEEPER, HIGH);
  3046. }
  3047. }
  3048. if (counterBeep == 20) {
  3049. WRITE(BEEPER, LOW);
  3050. }
  3051. counterBeep++;
  3052. #endif // BEEPER > 0
  3053. delay_keep_alive(4);
  3054. }
  3055. WRITE(BEEPER, LOW);
  3056. }
  3057. /**
  3058. * @brief Handling of unload when using MMU with M600
  3059. * A fullscreen message showing "Unloading Filament x"
  3060. * should be shown on the LCD and LCD updates should be
  3061. * are disabled in the meantime.
  3062. */
  3063. static void mmu_M600_unload_filament() {
  3064. if (MMU2::mmu2.get_current_tool() == (uint8_t)MMU2::FILAMENT_UNKNOWN) return;
  3065. lcd_update_enable(false);
  3066. lcd_clear();
  3067. lcd_puts_at_P(0, 1, _T(MSG_UNLOADING_FILAMENT));
  3068. lcd_print(' ');
  3069. lcd_print(MMU2::mmu2.get_current_tool() + 1);
  3070. // unload just current filament for multimaterial printers (used also in M702)
  3071. MMU2::mmu2.unload();
  3072. lcd_update_enable(true);
  3073. }
  3074. /// @brief load filament for mmu v2
  3075. /// @par nozzle_temp nozzle temperature to load filament
  3076. static void mmu_M600_load_filament(bool automatic, float nozzle_temp) {
  3077. uint8_t slot;
  3078. if (automatic) {
  3079. slot = SpoolJoin::spooljoin.nextSlot();
  3080. } else {
  3081. // Only ask for the slot if automatic/SpoolJoin is off
  3082. slot = choose_menu_P(_T(MSG_SELECT_EXTRUDER), _T(MSG_EXTRUDER));
  3083. }
  3084. setTargetHotend(nozzle_temp, active_extruder);
  3085. MMU2::mmu2.load_filament_to_nozzle(slot);
  3086. load_filament_final_feed(); // @@TODO verify
  3087. st_synchronize();
  3088. }
  3089. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3090. st_synchronize();
  3091. float lastpos[4];
  3092. prusa_statistics(22);
  3093. //First backup current position and settings
  3094. int feedmultiplyBckp = feedmultiply;
  3095. float HotendTempBckp = degTargetHotend(active_extruder);
  3096. int fanSpeedBckp = fanSpeed;
  3097. memcpy(lastpos, current_position, sizeof(lastpos));
  3098. // Turn off the fan
  3099. fanSpeed = 0;
  3100. // Retract E
  3101. current_position[E_AXIS] += e_shift;
  3102. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3103. st_synchronize();
  3104. // Raise the Z axis
  3105. raise_z(z_shift);
  3106. // Move XY to side
  3107. current_position[X_AXIS] = x_position;
  3108. current_position[Y_AXIS] = y_position;
  3109. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3110. st_synchronize();
  3111. // Beep, manage nozzle heater and wait for user to start unload filament
  3112. if (!MMU2::mmu2.Enabled())
  3113. M600_wait_for_user(HotendTempBckp);
  3114. // Unload filament
  3115. if (MMU2::mmu2.Enabled())
  3116. mmu_M600_unload_filament();
  3117. else
  3118. unload_filament(FILAMENTCHANGE_FINALRETRACT);
  3119. st_synchronize(); // finish moves
  3120. {
  3121. FSensorBlockRunout fsBlockRunout;
  3122. if (!MMU2::mmu2.Enabled())
  3123. {
  3124. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3125. uint8_t choice =
  3126. 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
  3127. if (choice == LCD_MIDDLE_BUTTON_CHOICE) {
  3128. lcd_clear();
  3129. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3130. current_position[X_AXIS] -= 100;
  3131. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3132. st_synchronize();
  3133. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually.")); ////MSG_CHECK_IDLER c=20 r=5
  3134. }
  3135. M600_load_filament();
  3136. }
  3137. else // MMU is enabled
  3138. {
  3139. if (!automatic) {
  3140. if (saved_printing){
  3141. // if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3142. MMU2::mmu2.eject_filament(MMU2::mmu2.get_current_tool(), false);
  3143. }
  3144. mmu_M600_wait_and_beep();
  3145. if (saved_printing) {
  3146. lcd_clear();
  3147. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3148. //@@TODO mmu_command(MmuCmd::R0);
  3149. // manage_response(false, false);
  3150. }
  3151. }
  3152. mmu_M600_load_filament(automatic, HotendTempBckp);
  3153. }
  3154. if (!automatic)
  3155. M600_check_state(HotendTempBckp);
  3156. lcd_update_enable(true);
  3157. // Not let's go back to print
  3158. fanSpeed = fanSpeedBckp;
  3159. // Feed a little of filament to stabilize pressure
  3160. if (!automatic) {
  3161. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3162. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3163. }
  3164. // Move XY back
  3165. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3166. st_synchronize();
  3167. // Move Z back
  3168. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3169. st_synchronize();
  3170. // Set E position to original
  3171. plan_set_e_position(lastpos[E_AXIS]);
  3172. memcpy(current_position, lastpos, sizeof(lastpos));
  3173. set_destination_to_current();
  3174. // Recover feed rate
  3175. feedmultiply = feedmultiplyBckp;
  3176. char cmd[9];
  3177. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3178. enquecommand(cmd);
  3179. }
  3180. lcd_setstatuspgm(MSG_WELCOME);
  3181. custom_message_type = CustomMsg::Status;
  3182. }
  3183. void gcode_M701(float fastLoadLength, uint8_t mmuSlotIndex){
  3184. FSensorBlockRunout fsBlockRunout;
  3185. prusa_statistics(22);
  3186. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3187. MMU2::mmu2.load_filament_to_nozzle(mmuSlotIndex);
  3188. } else {
  3189. custom_message_type = CustomMsg::FilamentLoading;
  3190. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3191. current_position[E_AXIS] += fastLoadLength;
  3192. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3193. load_filament_final_feed(); // slow sequence
  3194. st_synchronize();
  3195. Sound_MakeCustom(50, 500, false);
  3196. if (!farm_mode && loading_flag) {
  3197. lcd_load_filament_color_check();
  3198. }
  3199. lcd_update_enable(true);
  3200. lcd_update(2);
  3201. lcd_setstatuspgm(MSG_WELCOME);
  3202. loading_flag = false;
  3203. custom_message_type = CustomMsg::Status;
  3204. }
  3205. eFilamentAction = FilamentAction::None;
  3206. }
  3207. // Common gcode shared by the gcodes. This saves some flash memory
  3208. static void gcodes_M704_M705_M706(uint16_t gcode)
  3209. {
  3210. uint8_t mmuSlotIndex = 0xffU;
  3211. if (MMU2::mmu2.Enabled() && code_seen('P'))
  3212. {
  3213. mmuSlotIndex = code_value_uint8();
  3214. if (mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3215. switch (gcode)
  3216. {
  3217. case 704:
  3218. MMU2::mmu2.load_filament(mmuSlotIndex);
  3219. break;
  3220. case 705:
  3221. MMU2::mmu2.eject_filament(mmuSlotIndex, false);
  3222. break;
  3223. case 706:
  3224. #ifdef MMU_HAS_CUTTER
  3225. if (eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED) != 0){
  3226. MMU2::mmu2.cut_filament(mmuSlotIndex);
  3227. }
  3228. #endif // MMU_HAS_CUTTER
  3229. break;
  3230. default:
  3231. break;
  3232. }
  3233. }
  3234. }
  3235. }
  3236. /**
  3237. * @brief Get serial number from 32U2 processor
  3238. *
  3239. * Typical format of S/N is:CZPX0917X003XC13518
  3240. *
  3241. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3242. * reply is stored in *SN.
  3243. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3244. * and returns a general failure flag.
  3245. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3246. * In that case the value that is stored in the EEPROM should be used instead.
  3247. *
  3248. * @return 0 on success
  3249. * @return 1 on general failure
  3250. */
  3251. #ifdef PRUSA_SN_SUPPORT
  3252. static uint8_t get_PRUSA_SN(char* SN)
  3253. {
  3254. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3255. uint8_t rxIndex;
  3256. bool SN_valid = false;
  3257. ShortTimer timeout;
  3258. selectedSerialPort = 0;
  3259. timeout.start();
  3260. while (!SN_valid)
  3261. {
  3262. rxIndex = 0;
  3263. _delay(50);
  3264. MYSERIAL.flush(); //clear RX buffer
  3265. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3266. while (rxIndex < 19)
  3267. {
  3268. if (timeout.expired(250u))
  3269. goto exit;
  3270. if (MYSERIAL.available() > 0)
  3271. {
  3272. SN[rxIndex] = MYSERIAL.read();
  3273. rxIndex++;
  3274. }
  3275. }
  3276. SN[rxIndex] = 0;
  3277. // printf_P(PSTR("SN:%s\n"), SN);
  3278. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3279. }
  3280. exit:
  3281. selectedSerialPort = selectedSerialPort_bak;
  3282. return !SN_valid;
  3283. }
  3284. #endif //PRUSA_SN_SUPPORT
  3285. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3286. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3287. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3288. //! it may even interfere with other functions of the printer! You have been warned!
  3289. //! The test idea is to measure the time necessary to charge the capacitor.
  3290. //! So the algorithm is as follows:
  3291. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3292. //! 2. Wait a few ms
  3293. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3294. //! Repeat 1.-3. several times
  3295. //! Good RAMBo's times are in the range of approx. 260-320 us
  3296. //! Bad RAMBo's times are approx. 260-1200 us
  3297. //! So basically we are interested in maximum time, the minima are mostly the same.
  3298. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3299. static void gcode_PRUSA_BadRAMBoFanTest(){
  3300. //printf_P(PSTR("Enter fan pin test\n"));
  3301. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3302. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3303. unsigned long tach1max = 0;
  3304. uint8_t tach1cntr = 0;
  3305. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3306. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3307. SET_OUTPUT(TACH_1);
  3308. WRITE(TACH_1, LOW);
  3309. _delay(20); // the delay may be lower
  3310. unsigned long tachMeasure = _micros();
  3311. cli();
  3312. SET_INPUT(TACH_1);
  3313. // just wait brutally in an endless cycle until we reach HIGH
  3314. // if this becomes a problem it may be improved to non-endless cycle
  3315. while( READ(TACH_1) == 0 ) ;
  3316. sei();
  3317. tachMeasure = _micros() - tachMeasure;
  3318. if( tach1max < tachMeasure )
  3319. tach1max = tachMeasure;
  3320. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3321. }
  3322. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3323. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3324. if( tach1max > 500 ){
  3325. // bad RAMBo
  3326. SERIAL_PROTOCOLLNPGM("BAD");
  3327. } else {
  3328. SERIAL_PROTOCOLLNPGM("OK");
  3329. }
  3330. // cleanup after the test function
  3331. SET_INPUT(TACH_1);
  3332. WRITE(TACH_1, HIGH);
  3333. #endif
  3334. }
  3335. // G92 - Set current position to coordinates given
  3336. static void gcode_G92()
  3337. {
  3338. bool codes[NUM_AXIS];
  3339. float values[NUM_AXIS];
  3340. // Check which axes need to be set
  3341. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3342. {
  3343. codes[i] = code_seen(axis_codes[i]);
  3344. if(codes[i])
  3345. values[i] = code_value();
  3346. }
  3347. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3348. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3349. {
  3350. // As a special optimization, when _just_ clearing the E position
  3351. // we schedule a flag asynchronously along with the next block to
  3352. // reset the starting E position instead of stopping the planner
  3353. current_position[E_AXIS] = 0;
  3354. plan_reset_next_e();
  3355. }
  3356. else
  3357. {
  3358. // In any other case we're forced to synchronize
  3359. st_synchronize();
  3360. for(uint8_t i = 0; i < 3; ++i)
  3361. {
  3362. if(codes[i])
  3363. current_position[i] = values[i] + cs.add_homing[i];
  3364. }
  3365. if(codes[E_AXIS])
  3366. current_position[E_AXIS] = values[E_AXIS];
  3367. // Set all at once
  3368. plan_set_position_curposXYZE();
  3369. }
  3370. }
  3371. #ifdef EXTENDED_CAPABILITIES_REPORT
  3372. static void cap_line(const char* name, bool ena = false) {
  3373. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3374. }
  3375. static void extended_capabilities_report()
  3376. {
  3377. // AUTOREPORT_TEMP (M155)
  3378. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3379. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3380. // AUTOREPORT_FANS (M123)
  3381. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3382. #endif //FANCHECK and TACH_0 or TACH_1
  3383. // AUTOREPORT_POSITION (M114)
  3384. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3385. // EXTENDED_M20 (support for L and T parameters)
  3386. cap_line(PSTR("EXTENDED_M20"), 1);
  3387. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3388. }
  3389. #endif //EXTENDED_CAPABILITIES_REPORT
  3390. #ifdef BACKLASH_X
  3391. extern uint8_t st_backlash_x;
  3392. #endif //BACKLASH_X
  3393. #ifdef BACKLASH_Y
  3394. extern uint8_t st_backlash_y;
  3395. #endif //BACKLASH_Y
  3396. //! \ingroup marlin_main
  3397. //! @brief Parse and process commands
  3398. //!
  3399. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3400. //!
  3401. //!
  3402. //! Implemented Codes
  3403. //! -------------------
  3404. //!
  3405. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3406. //!
  3407. //!@n PRUSA CODES
  3408. //!@n P F - Returns FW versions
  3409. //!@n P R - Returns revision of printer
  3410. //!
  3411. //!@n G0 -> G1
  3412. //!@n G1 - Coordinated Movement X Y Z E
  3413. //!@n G2 - CW ARC
  3414. //!@n G3 - CCW ARC
  3415. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3416. //!@n G10 - retract filament according to settings of M207
  3417. //!@n G11 - retract recover filament according to settings of M208
  3418. //!@n G28 - Home all Axes
  3419. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3420. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3421. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3422. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3423. //!@n G80 - Automatic mesh bed leveling
  3424. //!@n G81 - Print bed profile
  3425. //!@n G90 - Use Absolute Coordinates
  3426. //!@n G91 - Use Relative Coordinates
  3427. //!@n G92 - Set current position to coordinates given
  3428. //!
  3429. //!@n M Codes
  3430. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3431. //!@n M1 - Same as M0
  3432. //!@n M17 - Enable/Power all stepper motors
  3433. //!@n M18 - Disable all stepper motors; same as M84
  3434. //!@n M20 - List SD card
  3435. //!@n M21 - Init SD card
  3436. //!@n M22 - Release SD card
  3437. //!@n M23 - Select SD file (M23 filename.g)
  3438. //!@n M24 - Start/resume SD print
  3439. //!@n M25 - Pause SD print
  3440. //!@n M26 - Set SD position in bytes (M26 S12345)
  3441. //!@n M27 - Report SD print status
  3442. //!@n M28 - Start SD write (M28 filename.g)
  3443. //!@n M29 - Stop SD write
  3444. //!@n M30 - Delete file from SD (M30 filename.g)
  3445. //!@n M31 - Output time since last M109 or SD card start to serial
  3446. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3447. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3448. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3449. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3450. //!@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.
  3451. //!@n M73 - Show percent done and print time remaining
  3452. //!@n M80 - Turn on Power Supply
  3453. //!@n M81 - Turn off Power Supply
  3454. //!@n M82 - Set E codes absolute (default)
  3455. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3456. //!@n M84 - Disable steppers until next move,
  3457. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3458. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3459. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3460. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3461. //!@n M104 - Set extruder target temp
  3462. //!@n M105 - Read current temp
  3463. //!@n M106 - Fan on
  3464. //!@n M107 - Fan off
  3465. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3466. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3467. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3468. //!@n M112 - Emergency stop
  3469. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3470. //!@n M114 - Output current position to serial port
  3471. //!@n M115 - Capabilities string
  3472. //!@n M117 - display message
  3473. //!@n M119 - Output Endstop status to serial port
  3474. //!@n M123 - Tachometer value
  3475. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3476. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3477. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3478. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3479. //!@n M140 - Set bed target temp
  3480. //!@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.
  3481. //!@n M155 - Automatically send temperatures, fan speeds, position
  3482. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3483. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3484. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3485. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3486. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3487. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3488. //!@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
  3489. //!@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
  3490. //!@n M206 - set additional homing offset
  3491. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3492. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3493. //!@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.
  3494. //!@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>
  3495. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3496. //!@n M220 S<factor in percent>- set speed factor override percentage
  3497. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3498. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3499. //!@n M240 - Trigger a camera to take a photograph
  3500. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3501. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3502. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3503. //!@n M301 - Set PID parameters P I and D
  3504. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3505. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3506. //!@n M304 - Set bed PID parameters P I and D
  3507. //!@n M310 - Temperature model settings
  3508. //!@n M400 - Finish all moves
  3509. //!@n M401 - Lower z-probe if present
  3510. //!@n M402 - Raise z-probe if present
  3511. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3512. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3513. //!@n M406 - Turn off Filament Sensor extrusion control
  3514. //!@n M407 - Displays measured filament diameter
  3515. //!@n M500 - stores parameters in EEPROM
  3516. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3517. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3518. //!@n M503 - print the current settings (from memory not from EEPROM)
  3519. //!@n M509 - force language selection on next restart
  3520. //!@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)
  3521. //!@n M552 - Set IP address
  3522. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3523. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3524. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3525. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3526. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3527. //!@n M907 - Set digital trimpot motor current using axis codes.
  3528. //!@n M908 - Control digital trimpot directly.
  3529. //!@n M350 - Set microstepping mode.
  3530. //!@n M351 - Toggle MS1 MS2 pins directly.
  3531. //!
  3532. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3533. //!@n M999 - Restart after being stopped by error
  3534. //! <br><br>
  3535. /** @defgroup marlin_main Marlin main */
  3536. /** \ingroup GCodes */
  3537. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3538. /**
  3539. They are shown in order of appearance in the code.
  3540. There are reasons why some G Codes aren't in numerical order.
  3541. */
  3542. void process_commands()
  3543. {
  3544. if (!buflen) return; //empty command
  3545. #ifdef CMDBUFFER_DEBUG
  3546. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3547. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3548. SERIAL_ECHOLNPGM("");
  3549. SERIAL_ECHOPGM("In cmdqueue: ");
  3550. SERIAL_ECHO(buflen);
  3551. SERIAL_ECHOLNPGM("");
  3552. #endif /* CMDBUFFER_DEBUG */
  3553. unsigned long codenum; //throw away variable
  3554. char *starpos = NULL;
  3555. #ifdef ENABLE_AUTO_BED_LEVELING
  3556. float x_tmp, y_tmp, z_tmp, real_z;
  3557. #endif
  3558. // PRUSA GCODES
  3559. KEEPALIVE_STATE(IN_HANDLER);
  3560. /*!
  3561. ---------------------------------------------------------------------------------
  3562. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3563. This causes the given message to be shown in the status line on an attached LCD.
  3564. It is processed early as to allow printing messages that contain G, M, N or T.
  3565. ---------------------------------------------------------------------------------
  3566. ### Special internal commands
  3567. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3568. They are processed early as the commands are complex (strings).
  3569. These are only available on the MK3(S) as these require TMC2130 drivers:
  3570. - CRASH DETECTED
  3571. - CRASH RECOVER
  3572. - CRASH_CANCEL
  3573. - TMC_SET_WAVE
  3574. - TMC_SET_STEP
  3575. - TMC_SET_CHOP
  3576. */
  3577. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3578. {
  3579. starpos = (strchr(strchr_pointer + 5, '*'));
  3580. if (starpos != NULL)
  3581. *(starpos) = '\0';
  3582. lcd_setstatus(strchr_pointer + 5);
  3583. custom_message_type = CustomMsg::M117;
  3584. }
  3585. /*!
  3586. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3587. #### Usage
  3588. M0 [P<ms<] [S<sec>] [string]
  3589. M1 [P<ms>] [S<sec>] [string]
  3590. #### Parameters
  3591. - `P<ms>` - Expire time, in milliseconds
  3592. - `S<sec>` - Expire time, in seconds
  3593. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3594. */
  3595. 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
  3596. const char *src = strchr_pointer + 2;
  3597. codenum = 0;
  3598. bool hasP = false, hasS = false;
  3599. if (code_seen('P')) {
  3600. codenum = code_value_long(); // milliseconds to wait
  3601. hasP = codenum > 0;
  3602. }
  3603. if (code_seen('S')) {
  3604. codenum = code_value_long() * 1000; // seconds to wait
  3605. hasS = codenum > 0;
  3606. }
  3607. starpos = strchr(src, '*');
  3608. if (starpos != NULL) *(starpos) = '\0';
  3609. while (*src == ' ') ++src;
  3610. custom_message_type = CustomMsg::M0Wait;
  3611. if (!hasP && !hasS && *src != '\0') {
  3612. lcd_setstatus(src);
  3613. } else {
  3614. // farmers want to abuse a bug from the previous firmware releases
  3615. // - they need to see the filename on the status screen instead of "Wait for user..."
  3616. // So we won't update the message in farm mode...
  3617. if( ! farm_mode){
  3618. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3619. } else {
  3620. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3621. }
  3622. }
  3623. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3624. st_synchronize();
  3625. previous_millis_cmd.start();
  3626. if (codenum > 0 ) {
  3627. codenum += _millis(); // keep track of when we started waiting
  3628. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3629. while(_millis() < codenum && !lcd_clicked()) {
  3630. manage_heater();
  3631. manage_inactivity(true);
  3632. lcd_update(0);
  3633. }
  3634. KEEPALIVE_STATE(IN_HANDLER);
  3635. lcd_ignore_click(false);
  3636. } else {
  3637. marlin_wait_for_click();
  3638. }
  3639. if (IS_SD_PRINTING)
  3640. custom_message_type = CustomMsg::Status;
  3641. else
  3642. LCD_MESSAGERPGM(MSG_WELCOME);
  3643. }
  3644. #ifdef TMC2130
  3645. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3646. {
  3647. // ### CRASH_DETECTED - TMC2130
  3648. // ---------------------------------
  3649. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3650. {
  3651. uint8_t mask = 0;
  3652. if (code_seen('X')) mask |= X_AXIS_MASK;
  3653. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3654. crashdet_detected(mask);
  3655. }
  3656. // ### CRASH_RECOVER - TMC2130
  3657. // ----------------------------------
  3658. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3659. crashdet_recover();
  3660. // ### CRASH_CANCEL - TMC2130
  3661. // ----------------------------------
  3662. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3663. crashdet_cancel();
  3664. }
  3665. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3666. {
  3667. // ### TMC_SET_WAVE_
  3668. // --------------------
  3669. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3670. {
  3671. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3672. axis = (axis == 'E')?3:(axis - 'X');
  3673. if (axis < 4)
  3674. {
  3675. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3676. tmc2130_set_wave(axis, 247, fac);
  3677. }
  3678. }
  3679. // ### TMC_SET_STEP_
  3680. // ------------------
  3681. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3682. {
  3683. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3684. axis = (axis == 'E')?3:(axis - 'X');
  3685. if (axis < 4)
  3686. {
  3687. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3688. uint16_t res = tmc2130_get_res(axis);
  3689. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3690. }
  3691. }
  3692. // ### TMC_SET_CHOP_
  3693. // -------------------
  3694. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3695. {
  3696. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3697. axis = (axis == 'E')?3:(axis - 'X');
  3698. if (axis < 4)
  3699. {
  3700. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3701. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3702. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3703. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3704. char* str_end = 0;
  3705. if (CMDBUFFER_CURRENT_STRING[14])
  3706. {
  3707. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3708. if (str_end && *str_end)
  3709. {
  3710. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3711. if (str_end && *str_end)
  3712. {
  3713. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3714. if (str_end && *str_end)
  3715. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3716. }
  3717. }
  3718. }
  3719. tmc2130_chopper_config[axis].toff = chop0;
  3720. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3721. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3722. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3723. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3724. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3725. }
  3726. }
  3727. }
  3728. #ifdef BACKLASH_X
  3729. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3730. {
  3731. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3732. st_backlash_x = bl;
  3733. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3734. }
  3735. #endif //BACKLASH_X
  3736. #ifdef BACKLASH_Y
  3737. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3738. {
  3739. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3740. st_backlash_y = bl;
  3741. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3742. }
  3743. #endif //BACKLASH_Y
  3744. #endif //TMC2130
  3745. else if(code_seen_P(PSTR("PRUSA"))){
  3746. /*!
  3747. ---------------------------------------------------------------------------------
  3748. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3749. Set of internal PRUSA commands
  3750. #### Usage
  3751. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3752. #### Parameters
  3753. - `PRN` - Prints revision of the printer
  3754. - `FAN` - Prints fan details
  3755. - `thx`
  3756. - `uvlo`
  3757. - `MMURES` - Reset MMU
  3758. - `RESET` - (Careful!)
  3759. - `fv` - ?
  3760. - `M28`
  3761. - `SN`
  3762. - `Fir` - Prints firmware version
  3763. - `Rev`- Prints filament size, elelectronics, nozzle type
  3764. - `Lang` - Reset the language
  3765. - `Lz`
  3766. - `FR` - Full factory reset
  3767. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3768. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3769. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3770. */
  3771. if (farm_prusa_code_seen()) {}
  3772. else if(code_seen_P(PSTR("FANPINTST"))) {
  3773. gcode_PRUSA_BadRAMBoFanTest();
  3774. }
  3775. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3776. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3777. }
  3778. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3779. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3780. enquecommand_P(PSTR("M24"));
  3781. }
  3782. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3783. {
  3784. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  3785. }
  3786. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3787. #if defined(XFLASH) && defined(BOOTAPP)
  3788. boot_app_magic = BOOT_APP_MAGIC;
  3789. boot_app_flags = BOOT_APP_FLG_RUN;
  3790. #endif //defined(XFLASH) && defined(BOOTAPP)
  3791. softReset();
  3792. }
  3793. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3794. char SN[20];
  3795. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3796. if (SN[19])
  3797. puts_P(PSTR("SN invalid"));
  3798. else
  3799. puts(SN);
  3800. }
  3801. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3802. SERIAL_PROTOCOLLNPGM(FW_VERSION_FULL);
  3803. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3804. SERIAL_PROTOCOLLNPGM(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3805. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3806. lang_reset();
  3807. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3808. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3809. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3810. // Factory full reset
  3811. factory_reset(0);
  3812. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3813. // Change the MBL status without changing the logical Z position.
  3814. if(code_seen('V')) {
  3815. bool value = code_value_short();
  3816. st_synchronize();
  3817. if(value != mbl.active) {
  3818. mbl.active = value;
  3819. // Use plan_set_z_position to reset the physical values
  3820. plan_set_z_position(current_position[Z_AXIS]);
  3821. }
  3822. }
  3823. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3824. uint16_t nDiameter;
  3825. if(code_seen('D'))
  3826. {
  3827. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3828. nozzle_diameter_check(nDiameter);
  3829. }
  3830. else if(code_seen_P(PSTR("set")) && farm_mode)
  3831. {
  3832. strchr_pointer++; // skip 1st char (~ 's')
  3833. strchr_pointer++; // skip 2nd char (~ 'e')
  3834. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3835. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3836. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3837. }
  3838. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3839. }
  3840. }
  3841. else if(code_seen('G'))
  3842. {
  3843. gcode_in_progress = code_value_short();
  3844. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3845. switch (gcode_in_progress)
  3846. {
  3847. /*!
  3848. ---------------------------------------------------------------------------------
  3849. # G Codes
  3850. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3851. In Prusa Firmware G0 and G1 are the same.
  3852. #### Usage
  3853. G0 [ X | Y | Z | E | F | S ]
  3854. G1 [ X | Y | Z | E | F | S ]
  3855. #### Parameters
  3856. - `X` - The position to move to on the X axis
  3857. - `Y` - The position to move to on the Y axis
  3858. - `Z` - The position to move to on the Z axis
  3859. - `E` - The amount to extrude between the starting point and ending point
  3860. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3861. */
  3862. case 0: // G0 -> G1
  3863. case 1: // G1
  3864. {
  3865. uint16_t start_segment_idx = restore_interrupted_gcode();
  3866. get_coordinates(); // For X Y Z E F
  3867. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3868. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3869. }
  3870. #ifdef FWRETRACT
  3871. if(cs.autoretract_enabled) {
  3872. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3873. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3874. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3875. st_synchronize();
  3876. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3877. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3878. retract(!retracted[active_extruder]);
  3879. return;
  3880. }
  3881. }
  3882. }
  3883. #endif //FWRETRACT
  3884. prepare_move(start_segment_idx);
  3885. //ClearToSend();
  3886. }
  3887. break;
  3888. /*!
  3889. ### 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>
  3890. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3891. #### Usage
  3892. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3893. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3894. #### Parameters
  3895. - `X` - The position to move to on the X axis
  3896. - `Y` - The position to move to on the Y axis
  3897. - 'Z' - The position to move to on the Z axis
  3898. - `I` - The point in X space from the current X position to maintain a constant distance from
  3899. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3900. - `E` - The amount to extrude between the starting point and ending point
  3901. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3902. */
  3903. case 2:
  3904. case 3:
  3905. {
  3906. uint16_t start_segment_idx = restore_interrupted_gcode();
  3907. #ifdef SF_ARC_FIX
  3908. bool relative_mode_backup = relative_mode;
  3909. relative_mode = true;
  3910. #endif
  3911. get_coordinates(); // For X Y Z E F
  3912. #ifdef SF_ARC_FIX
  3913. relative_mode=relative_mode_backup;
  3914. #endif
  3915. offset[0] = code_seen('I') ? code_value() : 0.f;
  3916. offset[1] = code_seen('J') ? code_value() : 0.f;
  3917. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3918. } break;
  3919. /*!
  3920. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3921. Pause the machine for a period of time.
  3922. #### Usage
  3923. G4 [ P | S ]
  3924. #### Parameters
  3925. - `P` - Time to wait, in milliseconds
  3926. - `S` - Time to wait, in seconds
  3927. */
  3928. case 4:
  3929. codenum = 0;
  3930. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3931. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3932. if(codenum != 0)
  3933. {
  3934. if(custom_message_type != CustomMsg::M117)
  3935. {
  3936. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3937. }
  3938. }
  3939. st_synchronize();
  3940. codenum += _millis(); // keep track of when we started waiting
  3941. previous_millis_cmd.start();
  3942. while(_millis() < codenum) {
  3943. manage_heater();
  3944. manage_inactivity();
  3945. lcd_update(0);
  3946. }
  3947. break;
  3948. #ifdef FWRETRACT
  3949. /*!
  3950. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3951. Retracts filament according to settings of `M207`
  3952. */
  3953. case 10:
  3954. #if EXTRUDERS > 1
  3955. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3956. retract(true,retracted_swap[active_extruder]);
  3957. #else
  3958. retract(true);
  3959. #endif
  3960. break;
  3961. /*!
  3962. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3963. Unretracts/recovers filament according to settings of `M208`
  3964. */
  3965. case 11:
  3966. #if EXTRUDERS > 1
  3967. retract(false,retracted_swap[active_extruder]);
  3968. #else
  3969. retract(false);
  3970. #endif
  3971. break;
  3972. #endif //FWRETRACT
  3973. /*!
  3974. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  3975. Units are in millimeters. Prusa doesn't support inches.
  3976. */
  3977. case 21:
  3978. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  3979. /*!
  3980. ### 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>
  3981. 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).
  3982. #### Usage
  3983. G28 [ X | Y | Z | W | C ]
  3984. #### Parameters
  3985. - `X` - Flag to go back to the X axis origin
  3986. - `Y` - Flag to go back to the Y axis origin
  3987. - `Z` - Flag to go back to the Z axis origin
  3988. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  3989. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  3990. */
  3991. case 28:
  3992. {
  3993. long home_x_value = 0;
  3994. long home_y_value = 0;
  3995. long home_z_value = 0;
  3996. // Which axes should be homed?
  3997. bool home_x = code_seen(axis_codes[X_AXIS]);
  3998. if (home_x) home_x_value = code_value_long();
  3999. bool home_y = code_seen(axis_codes[Y_AXIS]);
  4000. if (home_y) home_y_value = code_value_long();
  4001. bool home_z = code_seen(axis_codes[Z_AXIS]);
  4002. if (home_z) home_z_value = code_value_long();
  4003. bool without_mbl = code_seen('W');
  4004. // calibrate?
  4005. #ifdef TMC2130
  4006. bool calib = code_seen('C');
  4007. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4008. #else
  4009. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4010. #endif //TMC2130
  4011. if ((home_x || home_y || without_mbl || home_z) == false) {
  4012. gcode_G80();
  4013. }
  4014. break;
  4015. }
  4016. #ifdef ENABLE_AUTO_BED_LEVELING
  4017. /*!
  4018. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4019. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4020. See `G81`
  4021. */
  4022. case 29:
  4023. {
  4024. #if Z_MIN_PIN == -1
  4025. #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."
  4026. #endif
  4027. // Prevent user from running a G29 without first homing in X and Y
  4028. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4029. {
  4030. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4031. SERIAL_ECHO_START;
  4032. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4033. break; // abort G29, since we don't know where we are
  4034. }
  4035. st_synchronize();
  4036. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4037. //vector_3 corrected_position = plan_get_position_mm();
  4038. //corrected_position.debug("position before G29");
  4039. plan_bed_level_matrix.set_to_identity();
  4040. vector_3 uncorrected_position = plan_get_position();
  4041. //uncorrected_position.debug("position durring G29");
  4042. current_position[X_AXIS] = uncorrected_position.x;
  4043. current_position[Y_AXIS] = uncorrected_position.y;
  4044. current_position[Z_AXIS] = uncorrected_position.z;
  4045. plan_set_position_curposXYZE();
  4046. int l_feedmultiply = setup_for_endstop_move();
  4047. feedrate = homing_feedrate[Z_AXIS];
  4048. #ifdef AUTO_BED_LEVELING_GRID
  4049. // probe at the points of a lattice grid
  4050. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4051. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4052. // solve the plane equation ax + by + d = z
  4053. // A is the matrix with rows [x y 1] for all the probed points
  4054. // B is the vector of the Z positions
  4055. // 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
  4056. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4057. // "A" matrix of the linear system of equations
  4058. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4059. // "B" vector of Z points
  4060. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4061. int probePointCounter = 0;
  4062. bool zig = true;
  4063. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4064. {
  4065. int xProbe, xInc;
  4066. if (zig)
  4067. {
  4068. xProbe = LEFT_PROBE_BED_POSITION;
  4069. //xEnd = RIGHT_PROBE_BED_POSITION;
  4070. xInc = xGridSpacing;
  4071. zig = false;
  4072. } else // zag
  4073. {
  4074. xProbe = RIGHT_PROBE_BED_POSITION;
  4075. //xEnd = LEFT_PROBE_BED_POSITION;
  4076. xInc = -xGridSpacing;
  4077. zig = true;
  4078. }
  4079. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4080. {
  4081. float z_before;
  4082. if (probePointCounter == 0)
  4083. {
  4084. // raise before probing
  4085. z_before = Z_RAISE_BEFORE_PROBING;
  4086. } else
  4087. {
  4088. // raise extruder
  4089. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4090. }
  4091. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4092. eqnBVector[probePointCounter] = measured_z;
  4093. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4094. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4095. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4096. probePointCounter++;
  4097. xProbe += xInc;
  4098. }
  4099. }
  4100. clean_up_after_endstop_move(l_feedmultiply);
  4101. // solve lsq problem
  4102. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4103. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4104. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4105. SERIAL_PROTOCOLPGM(" b: ");
  4106. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4107. SERIAL_PROTOCOLPGM(" d: ");
  4108. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4109. set_bed_level_equation_lsq(plane_equation_coefficients);
  4110. free(plane_equation_coefficients);
  4111. #else // AUTO_BED_LEVELING_GRID not defined
  4112. // Probe at 3 arbitrary points
  4113. // probe 1
  4114. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4115. // probe 2
  4116. 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);
  4117. // probe 3
  4118. 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);
  4119. clean_up_after_endstop_move(l_feedmultiply);
  4120. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4121. #endif // AUTO_BED_LEVELING_GRID
  4122. st_synchronize();
  4123. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4124. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4125. // When the bed is uneven, this height must be corrected.
  4126. 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)
  4127. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4128. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4129. z_tmp = current_position[Z_AXIS];
  4130. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4131. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4132. plan_set_position_curposXYZE();
  4133. }
  4134. break;
  4135. #ifndef Z_PROBE_SLED
  4136. /*!
  4137. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4138. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4139. */
  4140. case 30:
  4141. {
  4142. st_synchronize();
  4143. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4144. int l_feedmultiply = setup_for_endstop_move();
  4145. feedrate = homing_feedrate[Z_AXIS];
  4146. run_z_probe();
  4147. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4148. SERIAL_PROTOCOLPGM(" X: ");
  4149. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4150. SERIAL_PROTOCOLPGM(" Y: ");
  4151. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4152. SERIAL_PROTOCOLPGM(" Z: ");
  4153. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4154. SERIAL_PROTOCOLPGM("\n");
  4155. clean_up_after_endstop_move(l_feedmultiply);
  4156. }
  4157. break;
  4158. #else
  4159. /*!
  4160. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4161. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4162. */
  4163. case 31:
  4164. dock_sled(true);
  4165. break;
  4166. /*!
  4167. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4168. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4169. */
  4170. case 32:
  4171. dock_sled(false);
  4172. break;
  4173. #endif // Z_PROBE_SLED
  4174. #endif // ENABLE_AUTO_BED_LEVELING
  4175. #ifdef MESH_BED_LEVELING
  4176. /*!
  4177. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4178. Sensor must be over the bed.
  4179. The maximum travel distance before an error is triggered is 10mm.
  4180. */
  4181. case 30:
  4182. {
  4183. st_synchronize();
  4184. homing_flag = true;
  4185. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4186. int l_feedmultiply = setup_for_endstop_move();
  4187. feedrate = homing_feedrate[Z_AXIS];
  4188. find_bed_induction_sensor_point_z(-10.f, 3);
  4189. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4190. clean_up_after_endstop_move(l_feedmultiply);
  4191. homing_flag = false;
  4192. }
  4193. break;
  4194. /*!
  4195. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4196. Show/print PINDA temperature interpolating.
  4197. */
  4198. case 75:
  4199. {
  4200. for (uint8_t i = 40; i <= 110; i++)
  4201. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4202. }
  4203. break;
  4204. /*!
  4205. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4206. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4207. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4208. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4209. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4210. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4211. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4212. #### Example
  4213. ```
  4214. G76
  4215. echo PINDA probe calibration start
  4216. echo start temperature: 35.0°
  4217. echo ...
  4218. echo PINDA temperature -- Z shift (mm): 0.---
  4219. ```
  4220. */
  4221. case 76:
  4222. {
  4223. #ifdef PINDA_THERMISTOR
  4224. if (!has_temperature_compensation())
  4225. {
  4226. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4227. break;
  4228. }
  4229. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4230. //we need to know accurate position of first calibration point
  4231. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4232. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4233. break;
  4234. }
  4235. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4236. {
  4237. // We don't know where we are! HOME!
  4238. // Push the commands to the front of the message queue in the reverse order!
  4239. // There shall be always enough space reserved for these commands.
  4240. repeatcommand_front(); // repeat G76 with all its parameters
  4241. enquecommand_front_P(G28W0);
  4242. break;
  4243. }
  4244. 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
  4245. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  4246. if (result == LCD_LEFT_BUTTON_CHOICE)
  4247. {
  4248. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4249. plan_buffer_line_curposXYZE(3000 / 60);
  4250. current_position[Z_AXIS] = 50;
  4251. current_position[Y_AXIS] = 180;
  4252. plan_buffer_line_curposXYZE(3000 / 60);
  4253. st_synchronize();
  4254. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4255. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4256. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4257. plan_buffer_line_curposXYZE(3000 / 60);
  4258. st_synchronize();
  4259. gcode_G28(false, false, true);
  4260. }
  4261. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4262. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4263. current_position[Z_AXIS] = 100;
  4264. plan_buffer_line_curposXYZE(3000 / 60);
  4265. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4266. lcd_temp_cal_show_result(false);
  4267. break;
  4268. }
  4269. }
  4270. st_synchronize();
  4271. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4272. lcd_update_enable(true);
  4273. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4274. float zero_z;
  4275. int z_shift = 0; //unit: steps
  4276. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4277. if (start_temp < 35) start_temp = 35;
  4278. if (start_temp < current_temperature_pinda) start_temp += 5;
  4279. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4280. // setTargetHotend(200, 0);
  4281. setTargetBed(70 + (start_temp - 30));
  4282. custom_message_type = CustomMsg::TempCal;
  4283. custom_message_state = 1;
  4284. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4285. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4286. plan_buffer_line_curposXYZE(3000 / 60);
  4287. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4288. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4289. plan_buffer_line_curposXYZE(3000 / 60);
  4290. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4291. plan_buffer_line_curposXYZE(3000 / 60);
  4292. st_synchronize();
  4293. while (current_temperature_pinda < start_temp)
  4294. {
  4295. delay_keep_alive(1000);
  4296. serialecho_temperatures();
  4297. }
  4298. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4299. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4300. plan_buffer_line_curposXYZE(3000 / 60);
  4301. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4302. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4303. plan_buffer_line_curposXYZE(3000 / 60);
  4304. st_synchronize();
  4305. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4306. if (find_z_result == false) {
  4307. lcd_temp_cal_show_result(find_z_result);
  4308. homing_flag = false;
  4309. break;
  4310. }
  4311. zero_z = current_position[Z_AXIS];
  4312. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4313. int i = -1; for (; i < 5; i++)
  4314. {
  4315. float temp = (40 + i * 5);
  4316. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4317. if (i >= 0) {
  4318. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4319. }
  4320. if (start_temp <= temp) break;
  4321. }
  4322. for (i++; i < 5; i++)
  4323. {
  4324. float temp = (40 + i * 5);
  4325. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4326. custom_message_state = i + 2;
  4327. setTargetBed(50 + 10 * (temp - 30) / 5);
  4328. // setTargetHotend(255, 0);
  4329. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4330. plan_buffer_line_curposXYZE(3000 / 60);
  4331. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4332. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4333. plan_buffer_line_curposXYZE(3000 / 60);
  4334. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4335. plan_buffer_line_curposXYZE(3000 / 60);
  4336. st_synchronize();
  4337. while (current_temperature_pinda < temp)
  4338. {
  4339. delay_keep_alive(1000);
  4340. serialecho_temperatures();
  4341. }
  4342. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4343. plan_buffer_line_curposXYZE(3000 / 60);
  4344. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4345. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4346. plan_buffer_line_curposXYZE(3000 / 60);
  4347. st_synchronize();
  4348. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4349. if (find_z_result == false) {
  4350. lcd_temp_cal_show_result(find_z_result);
  4351. break;
  4352. }
  4353. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4354. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4355. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4356. }
  4357. lcd_temp_cal_show_result(true);
  4358. homing_flag = false;
  4359. #else //PINDA_THERMISTOR
  4360. setTargetBed(PINDA_MIN_T);
  4361. float zero_z;
  4362. int z_shift = 0; //unit: steps
  4363. int t_c; // temperature
  4364. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4365. // We don't know where we are! HOME!
  4366. // Push the commands to the front of the message queue in the reverse order!
  4367. // There shall be always enough space reserved for these commands.
  4368. repeatcommand_front(); // repeat G76 with all its parameters
  4369. enquecommand_front_P(G28W0);
  4370. break;
  4371. }
  4372. puts_P(_N("PINDA probe calibration start"));
  4373. custom_message_type = CustomMsg::TempCal;
  4374. custom_message_state = 1;
  4375. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4376. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4377. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4378. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4379. plan_buffer_line_curposXYZE(3000 / 60);
  4380. st_synchronize();
  4381. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4382. delay_keep_alive(1000);
  4383. serialecho_temperatures();
  4384. }
  4385. //enquecommand_P(PSTR("M190 S50"));
  4386. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4387. delay_keep_alive(1000);
  4388. serialecho_temperatures();
  4389. }
  4390. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4391. current_position[Z_AXIS] = 5;
  4392. plan_buffer_line_curposXYZE(3000 / 60);
  4393. current_position[X_AXIS] = BED_X0;
  4394. current_position[Y_AXIS] = BED_Y0;
  4395. plan_buffer_line_curposXYZE(3000 / 60);
  4396. st_synchronize();
  4397. find_bed_induction_sensor_point_z(-1.f);
  4398. zero_z = current_position[Z_AXIS];
  4399. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4400. for (int i = 0; i<5; i++) {
  4401. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4402. custom_message_state = i + 2;
  4403. t_c = 60 + i * 10;
  4404. setTargetBed(t_c);
  4405. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4406. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4407. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4408. plan_buffer_line_curposXYZE(3000 / 60);
  4409. st_synchronize();
  4410. while (degBed() < t_c) {
  4411. delay_keep_alive(1000);
  4412. serialecho_temperatures();
  4413. }
  4414. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4415. delay_keep_alive(1000);
  4416. serialecho_temperatures();
  4417. }
  4418. current_position[Z_AXIS] = 5;
  4419. plan_buffer_line_curposXYZE(3000 / 60);
  4420. current_position[X_AXIS] = BED_X0;
  4421. current_position[Y_AXIS] = BED_Y0;
  4422. plan_buffer_line_curposXYZE(3000 / 60);
  4423. st_synchronize();
  4424. find_bed_induction_sensor_point_z(-1.f);
  4425. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4426. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4427. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4428. }
  4429. custom_message_type = CustomMsg::Status;
  4430. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4431. puts_P(_N("Temperature calibration done."));
  4432. disable_x();
  4433. disable_y();
  4434. disable_z();
  4435. disable_e0();
  4436. disable_e1();
  4437. disable_e2();
  4438. setTargetBed(0); //set bed target temperature back to 0
  4439. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4440. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4441. lcd_update_enable(true);
  4442. lcd_update(2);
  4443. #endif //PINDA_THERMISTOR
  4444. }
  4445. break;
  4446. /*!
  4447. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4448. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4449. #### Usage
  4450. G80 [ N | R | V | L | R | F | B ]
  4451. #### Parameters
  4452. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4453. - `R` - Probe retries. Default 3 max. 10
  4454. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4455. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4456. #### Additional Parameters
  4457. - `L` - Left Bed Level correct value in um.
  4458. - `R` - Right Bed Level correct value in um.
  4459. - `F` - Front Bed Level correct value in um.
  4460. - `B` - Back Bed Level correct value in um.
  4461. */
  4462. /*
  4463. * Probes a grid and produces a mesh to compensate for variable bed height
  4464. * The S0 report the points as below
  4465. * +----> X-axis
  4466. * |
  4467. * |
  4468. * v Y-axis
  4469. */
  4470. case 80: {
  4471. gcode_G80();
  4472. }
  4473. break;
  4474. /*!
  4475. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4476. Prints mesh bed leveling status and bed profile if activated.
  4477. */
  4478. case 81:
  4479. if (mbl.active) {
  4480. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4481. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4482. SERIAL_PROTOCOL(',');
  4483. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4484. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4485. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4486. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4487. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4488. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4489. SERIAL_PROTOCOLPGM(" ");
  4490. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4491. }
  4492. SERIAL_PROTOCOLLN();
  4493. }
  4494. }
  4495. else
  4496. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4497. break;
  4498. #if 0
  4499. /*!
  4500. ### 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>
  4501. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4502. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4503. */
  4504. case 82:
  4505. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4506. int l_feedmultiply = setup_for_endstop_move();
  4507. find_bed_induction_sensor_point_z();
  4508. clean_up_after_endstop_move(l_feedmultiply);
  4509. SERIAL_PROTOCOLPGM("Bed found at: ");
  4510. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4511. SERIAL_PROTOCOLPGM("\n");
  4512. break;
  4513. /*!
  4514. ### 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>
  4515. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4516. */
  4517. case 83:
  4518. {
  4519. int babystepz = code_seen('S') ? code_value() : 0;
  4520. int BabyPosition = code_seen('P') ? code_value() : 0;
  4521. if (babystepz != 0) {
  4522. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4523. // Is the axis indexed starting with zero or one?
  4524. if (BabyPosition > 4) {
  4525. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4526. }else{
  4527. // Save it to the eeprom
  4528. babystepLoadZ = babystepz;
  4529. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4530. // adjust the Z
  4531. babystepsTodoZadd(babystepLoadZ);
  4532. }
  4533. }
  4534. }
  4535. break;
  4536. /*!
  4537. ### 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>
  4538. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4539. */
  4540. case 84:
  4541. babystepsTodoZsubtract(babystepLoadZ);
  4542. // babystepLoadZ = 0;
  4543. break;
  4544. /*!
  4545. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4546. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4547. */
  4548. case 85:
  4549. lcd_pick_babystep();
  4550. break;
  4551. #endif
  4552. /*!
  4553. ### 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>
  4554. This G-code will be performed at the start of a calibration script.
  4555. (Prusa3D specific)
  4556. */
  4557. case 86:
  4558. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4559. break;
  4560. /*!
  4561. ### 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>
  4562. This G-code will be performed at the end of a calibration script.
  4563. (Prusa3D specific)
  4564. */
  4565. case 87:
  4566. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4567. break;
  4568. /*!
  4569. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4570. Currently has no effect.
  4571. */
  4572. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4573. case 88:
  4574. break;
  4575. #endif // ENABLE_MESH_BED_LEVELING
  4576. /*!
  4577. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4578. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4579. */
  4580. case 90: {
  4581. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4582. }
  4583. break;
  4584. /*!
  4585. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4586. All coordinates from now on are relative to the last position. E axis is left intact.
  4587. */
  4588. case 91: {
  4589. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4590. }
  4591. break;
  4592. /*!
  4593. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4594. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4595. If a parameter is omitted, that axis will not be affected.
  4596. 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`).
  4597. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4598. #### Usage
  4599. G92 [ X | Y | Z | E ]
  4600. #### Parameters
  4601. - `X` - new X axis position
  4602. - `Y` - new Y axis position
  4603. - `Z` - new Z axis position
  4604. - `E` - new extruder position
  4605. */
  4606. case 92: {
  4607. gcode_G92();
  4608. }
  4609. break;
  4610. #ifdef PRUSA_FARM
  4611. /*!
  4612. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4613. Enable Prusa-specific Farm functions and g-code.
  4614. See Internal Prusa commands.
  4615. */
  4616. case 98:
  4617. farm_gcode_g98();
  4618. break;
  4619. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4620. Disables Prusa-specific Farm functions and g-code.
  4621. */
  4622. case 99:
  4623. farm_gcode_g99();
  4624. break;
  4625. #endif //PRUSA_FARM
  4626. default:
  4627. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4628. }
  4629. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4630. gcode_in_progress = 0;
  4631. } // end if(code_seen('G'))
  4632. /*!
  4633. ### End of G-Codes
  4634. */
  4635. /*!
  4636. ---------------------------------------------------------------------------------
  4637. # M Commands
  4638. */
  4639. else if(code_seen('M'))
  4640. {
  4641. int index;
  4642. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4643. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4644. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4645. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4646. } else
  4647. {
  4648. mcode_in_progress = code_value_short();
  4649. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4650. switch(mcode_in_progress)
  4651. {
  4652. /*!
  4653. ### 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>
  4654. */
  4655. case 17:
  4656. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4657. enable_x();
  4658. enable_y();
  4659. enable_z();
  4660. enable_e0();
  4661. enable_e1();
  4662. enable_e2();
  4663. break;
  4664. #ifdef SDSUPPORT
  4665. /*!
  4666. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4667. #### Usage
  4668. M20 [ L | T ]
  4669. #### Parameters
  4670. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4671. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4672. */
  4673. case 20:
  4674. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4675. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4676. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4677. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4678. break;
  4679. /*!
  4680. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4681. */
  4682. case 21:
  4683. card.initsd();
  4684. break;
  4685. /*!
  4686. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4687. */
  4688. case 22:
  4689. card.release();
  4690. break;
  4691. /*!
  4692. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4693. #### Usage
  4694. M23 [filename]
  4695. */
  4696. case 23:
  4697. starpos = (strchr(strchr_pointer + 4,'*'));
  4698. if(starpos!=NULL)
  4699. *(starpos)='\0';
  4700. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4701. break;
  4702. /*!
  4703. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4704. */
  4705. case 24:
  4706. if (isPrintPaused)
  4707. lcd_resume_print();
  4708. else
  4709. {
  4710. if (!card.get_sdpos())
  4711. {
  4712. // A new print has started from scratch, reset stats
  4713. failstats_reset_print();
  4714. sdpos_atomic = 0;
  4715. #ifndef LA_NOCOMPAT
  4716. la10c_reset();
  4717. #endif
  4718. }
  4719. card.startFileprint();
  4720. starttime=_millis();
  4721. if (MMU2::mmu2.Enabled())
  4722. {
  4723. if (MMU2::mmu2.FindaDetectsFilament() && !fsensor.getFilamentPresent())
  4724. { // Filament only half way into the PTFE. Unload the filament.
  4725. MMU2::mmu2.unload();
  4726. // Tx and Tc gcodes take care of loading the filament to the nozzle.
  4727. }
  4728. }
  4729. }
  4730. break;
  4731. /*!
  4732. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4733. Set position in SD card file to index in bytes.
  4734. This command is expected to be called after M23 and before M24.
  4735. Otherwise effect of this command is undefined.
  4736. #### Usage
  4737. M26 [ S ]
  4738. #### Parameters
  4739. - `S` - Index in bytes
  4740. */
  4741. case 26:
  4742. if(card.cardOK && code_seen('S')) {
  4743. long index = code_value_long();
  4744. card.setIndex(index);
  4745. // We don't disable interrupt during update of sdpos_atomic
  4746. // as we expect, that SD card print is not active in this moment
  4747. sdpos_atomic = index;
  4748. }
  4749. break;
  4750. /*!
  4751. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4752. #### Usage
  4753. M27 [ P ]
  4754. #### Parameters
  4755. - `P` - Show full SFN path instead of LFN only.
  4756. */
  4757. case 27:
  4758. card.getStatus(code_seen('P'));
  4759. break;
  4760. /*!
  4761. ### 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>
  4762. */
  4763. case 28:
  4764. starpos = (strchr(strchr_pointer + 4,'*'));
  4765. if(starpos != NULL){
  4766. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4767. strchr_pointer = strchr(npos,' ') + 1;
  4768. *(starpos) = '\0';
  4769. }
  4770. card.openFileWrite(strchr_pointer+4);
  4771. break;
  4772. /*! ### 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>
  4773. 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.
  4774. */
  4775. case 29:
  4776. //processed in write to file routine above
  4777. //card,saving = false;
  4778. break;
  4779. /*!
  4780. ### 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>
  4781. #### Usage
  4782. M30 [filename]
  4783. */
  4784. case 30:
  4785. if (card.cardOK){
  4786. card.closefile();
  4787. starpos = (strchr(strchr_pointer + 4,'*'));
  4788. if(starpos != NULL){
  4789. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4790. strchr_pointer = strchr(npos,' ') + 1;
  4791. *(starpos) = '\0';
  4792. }
  4793. card.removeFile(strchr_pointer + 4);
  4794. }
  4795. break;
  4796. /*!
  4797. ### 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>
  4798. @todo What are the parameters P and S for in M32?
  4799. */
  4800. case 32:
  4801. {
  4802. if(card.sdprinting) {
  4803. st_synchronize();
  4804. }
  4805. starpos = (strchr(strchr_pointer + 4,'*'));
  4806. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4807. if(namestartpos==NULL)
  4808. {
  4809. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4810. }
  4811. else
  4812. namestartpos++; //to skip the '!'
  4813. if(starpos!=NULL)
  4814. *(starpos)='\0';
  4815. bool call_procedure=(code_seen('P'));
  4816. if(strchr_pointer>namestartpos)
  4817. call_procedure=false; //false alert, 'P' found within filename
  4818. if( card.cardOK )
  4819. {
  4820. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4821. if(code_seen('S'))
  4822. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4823. card.setIndex(code_value_long());
  4824. card.startFileprint();
  4825. if(!call_procedure)
  4826. {
  4827. if(!card.get_sdpos())
  4828. {
  4829. // A new print has started from scratch, reset stats
  4830. failstats_reset_print();
  4831. sdpos_atomic = 0;
  4832. #ifndef LA_NOCOMPAT
  4833. la10c_reset();
  4834. #endif
  4835. }
  4836. starttime=_millis(); // procedure calls count as normal print time.
  4837. }
  4838. }
  4839. } break;
  4840. /*!
  4841. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4842. #### Usage
  4843. M928 [filename]
  4844. */
  4845. case 928:
  4846. starpos = (strchr(strchr_pointer + 5,'*'));
  4847. if(starpos != NULL){
  4848. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4849. strchr_pointer = strchr(npos,' ') + 1;
  4850. *(starpos) = '\0';
  4851. }
  4852. card.openLogFile(strchr_pointer+5);
  4853. break;
  4854. #endif //SDSUPPORT
  4855. /*!
  4856. ### 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>
  4857. */
  4858. case 31: //M31 take time since the start of the SD print or an M109 command
  4859. {
  4860. stoptime=_millis();
  4861. char time[30];
  4862. unsigned long t=(stoptime-starttime)/1000;
  4863. int sec,min;
  4864. min=t/60;
  4865. sec=t%60;
  4866. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4867. SERIAL_ECHO_START;
  4868. SERIAL_ECHOLN(time);
  4869. lcd_setstatus(time);
  4870. autotempShutdown();
  4871. }
  4872. break;
  4873. /*!
  4874. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4875. #### Usage
  4876. M42 [ P | S ]
  4877. #### Parameters
  4878. - `P` - Pin number.
  4879. - `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.
  4880. */
  4881. case 42:
  4882. if (code_seen('S'))
  4883. {
  4884. uint8_t pin_status = code_value_uint8();
  4885. int8_t pin_number = LED_PIN;
  4886. if (code_seen('P'))
  4887. pin_number = code_value_uint8();
  4888. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4889. {
  4890. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4891. {
  4892. pin_number = -1;
  4893. break;
  4894. }
  4895. }
  4896. #if defined(FAN_PIN) && FAN_PIN > -1
  4897. if (pin_number == FAN_PIN)
  4898. fanSpeed = pin_status;
  4899. #endif
  4900. if (pin_number > -1)
  4901. {
  4902. pinMode(pin_number, OUTPUT);
  4903. digitalWrite(pin_number, pin_status);
  4904. analogWrite(pin_number, pin_status);
  4905. }
  4906. }
  4907. break;
  4908. /*!
  4909. ### 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>
  4910. */
  4911. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4912. // Reset the baby step value and the baby step applied flag.
  4913. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4914. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4915. // Reset the skew and offset in both RAM and EEPROM.
  4916. reset_bed_offset_and_skew();
  4917. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4918. // the planner will not perform any adjustments in the XY plane.
  4919. // Wait for the motors to stop and update the current position with the absolute values.
  4920. world2machine_revert_to_uncorrected();
  4921. break;
  4922. /*!
  4923. ### 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>
  4924. #### Usage
  4925. M45 [ V ]
  4926. #### Parameters
  4927. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4928. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4929. */
  4930. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4931. {
  4932. int8_t verbosity_level = 0;
  4933. bool only_Z = code_seen('Z');
  4934. #ifdef SUPPORT_VERBOSITY
  4935. if (code_seen('V'))
  4936. {
  4937. // Just 'V' without a number counts as V1.
  4938. char c = strchr_pointer[1];
  4939. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4940. }
  4941. #endif //SUPPORT_VERBOSITY
  4942. gcode_M45(only_Z, verbosity_level);
  4943. }
  4944. break;
  4945. /*!
  4946. ### 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>
  4947. */
  4948. case 46:
  4949. {
  4950. // M46: Prusa3D: Show the assigned IP address.
  4951. if (card.ToshibaFlashAir_isEnabled()) {
  4952. uint8_t ip[4];
  4953. if (card.ToshibaFlashAir_GetIP(ip)) {
  4954. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  4955. SERIAL_PROTOCOL(uint8_t(ip[0]));
  4956. SERIAL_PROTOCOL('.');
  4957. SERIAL_PROTOCOL(uint8_t(ip[1]));
  4958. SERIAL_PROTOCOL('.');
  4959. SERIAL_PROTOCOL(uint8_t(ip[2]));
  4960. SERIAL_PROTOCOL('.');
  4961. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  4962. } else {
  4963. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  4964. }
  4965. } else {
  4966. SERIAL_PROTOCOLLNPGM("n/a");
  4967. }
  4968. break;
  4969. }
  4970. /*!
  4971. ### 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>
  4972. */
  4973. case 47:
  4974. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4975. lcd_diag_show_end_stops();
  4976. KEEPALIVE_STATE(IN_HANDLER);
  4977. break;
  4978. #if 0
  4979. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4980. {
  4981. // Disable the default update procedure of the display. We will do a modal dialog.
  4982. lcd_update_enable(false);
  4983. // Let the planner use the uncorrected coordinates.
  4984. mbl.reset();
  4985. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4986. // the planner will not perform any adjustments in the XY plane.
  4987. // Wait for the motors to stop and update the current position with the absolute values.
  4988. world2machine_revert_to_uncorrected();
  4989. // Move the print head close to the bed.
  4990. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4991. 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);
  4992. st_synchronize();
  4993. // Home in the XY plane.
  4994. set_destination_to_current();
  4995. int l_feedmultiply = setup_for_endstop_move();
  4996. home_xy();
  4997. int8_t verbosity_level = 0;
  4998. if (code_seen('V')) {
  4999. // Just 'V' without a number counts as V1.
  5000. char c = strchr_pointer[1];
  5001. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5002. }
  5003. bool success = scan_bed_induction_points(verbosity_level);
  5004. clean_up_after_endstop_move(l_feedmultiply);
  5005. // Print head up.
  5006. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5007. 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);
  5008. st_synchronize();
  5009. lcd_update_enable(true);
  5010. break;
  5011. }
  5012. #endif
  5013. #ifdef ENABLE_AUTO_BED_LEVELING
  5014. #ifdef Z_PROBE_REPEATABILITY_TEST
  5015. /*!
  5016. ### 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>
  5017. 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.
  5018. 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.
  5019. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5020. #### Usage
  5021. M48 [ n | X | Y | V | L ]
  5022. #### Parameters
  5023. - `n` - Number of samples. Valid values 4-50
  5024. - `X` - X position for samples
  5025. - `Y` - Y position for samples
  5026. - `V` - Verbose level. Valid values 1-4
  5027. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5028. */
  5029. case 48: // M48 Z-Probe repeatability
  5030. {
  5031. #if Z_MIN_PIN == -1
  5032. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5033. #endif
  5034. double sum=0.0;
  5035. double mean=0.0;
  5036. double sigma=0.0;
  5037. double sample_set[50];
  5038. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5039. double X_current, Y_current, Z_current;
  5040. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5041. if (code_seen('V') || code_seen('v')) {
  5042. verbose_level = code_value();
  5043. if (verbose_level<0 || verbose_level>4 ) {
  5044. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5045. goto Sigma_Exit;
  5046. }
  5047. }
  5048. if (verbose_level > 0) {
  5049. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5050. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5051. }
  5052. if (code_seen('n')) {
  5053. n_samples = code_value();
  5054. if (n_samples<4 || n_samples>50 ) {
  5055. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5056. goto Sigma_Exit;
  5057. }
  5058. }
  5059. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5060. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5061. Z_current = st_get_position_mm(Z_AXIS);
  5062. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5063. ext_position = st_get_position_mm(E_AXIS);
  5064. if (code_seen('X') || code_seen('x') ) {
  5065. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5066. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5067. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5068. goto Sigma_Exit;
  5069. }
  5070. }
  5071. if (code_seen('Y') || code_seen('y') ) {
  5072. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5073. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5074. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5075. goto Sigma_Exit;
  5076. }
  5077. }
  5078. if (code_seen('L') || code_seen('l') ) {
  5079. n_legs = code_value();
  5080. if ( n_legs==1 )
  5081. n_legs = 2;
  5082. if ( n_legs<0 || n_legs>15 ) {
  5083. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5084. goto Sigma_Exit;
  5085. }
  5086. }
  5087. //
  5088. // Do all the preliminary setup work. First raise the probe.
  5089. //
  5090. st_synchronize();
  5091. plan_bed_level_matrix.set_to_identity();
  5092. plan_buffer_line( X_current, Y_current, Z_start_location,
  5093. ext_position,
  5094. homing_feedrate[Z_AXIS]/60,
  5095. active_extruder);
  5096. st_synchronize();
  5097. //
  5098. // Now get everything to the specified probe point So we can safely do a probe to
  5099. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5100. // use that as a starting point for each probe.
  5101. //
  5102. if (verbose_level > 2)
  5103. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5104. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5105. ext_position,
  5106. homing_feedrate[X_AXIS]/60,
  5107. active_extruder);
  5108. st_synchronize();
  5109. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5110. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5111. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5112. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5113. //
  5114. // OK, do the inital probe to get us close to the bed.
  5115. // Then retrace the right amount and use that in subsequent probes
  5116. //
  5117. int l_feedmultiply = setup_for_endstop_move();
  5118. run_z_probe();
  5119. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5120. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5121. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5122. ext_position,
  5123. homing_feedrate[X_AXIS]/60,
  5124. active_extruder);
  5125. st_synchronize();
  5126. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5127. for( n=0; n<n_samples; n++) {
  5128. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5129. if ( n_legs) {
  5130. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5131. int rotational_direction, l;
  5132. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5133. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5134. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5135. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5136. //SERIAL_ECHOPAIR(" theta: ",theta);
  5137. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5138. //SERIAL_PROTOCOLLNPGM("");
  5139. for( l=0; l<n_legs-1; l++) {
  5140. if (rotational_direction==1)
  5141. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5142. else
  5143. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5144. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5145. if ( radius<0.0 )
  5146. radius = -radius;
  5147. X_current = X_probe_location + cos(theta) * radius;
  5148. Y_current = Y_probe_location + sin(theta) * radius;
  5149. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5150. X_current = X_MIN_POS;
  5151. if ( X_current>X_MAX_POS)
  5152. X_current = X_MAX_POS;
  5153. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5154. Y_current = Y_MIN_POS;
  5155. if ( Y_current>Y_MAX_POS)
  5156. Y_current = Y_MAX_POS;
  5157. if (verbose_level>3 ) {
  5158. SERIAL_ECHOPAIR("x: ", X_current);
  5159. SERIAL_ECHOPAIR("y: ", Y_current);
  5160. SERIAL_PROTOCOLLNPGM("");
  5161. }
  5162. do_blocking_move_to( X_current, Y_current, Z_current );
  5163. }
  5164. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5165. }
  5166. int l_feedmultiply = setup_for_endstop_move();
  5167. run_z_probe();
  5168. sample_set[n] = current_position[Z_AXIS];
  5169. //
  5170. // Get the current mean for the data points we have so far
  5171. //
  5172. sum=0.0;
  5173. for( j=0; j<=n; j++) {
  5174. sum = sum + sample_set[j];
  5175. }
  5176. mean = sum / (double (n+1));
  5177. //
  5178. // Now, use that mean to calculate the standard deviation for the
  5179. // data points we have so far
  5180. //
  5181. sum=0.0;
  5182. for( j=0; j<=n; j++) {
  5183. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5184. }
  5185. sigma = sqrt( sum / (double (n+1)) );
  5186. if (verbose_level > 1) {
  5187. SERIAL_PROTOCOL(n+1);
  5188. SERIAL_PROTOCOL(" of ");
  5189. SERIAL_PROTOCOL(n_samples);
  5190. SERIAL_PROTOCOLPGM(" z: ");
  5191. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5192. }
  5193. if (verbose_level > 2) {
  5194. SERIAL_PROTOCOL(" mean: ");
  5195. SERIAL_PROTOCOL_F(mean,6);
  5196. SERIAL_PROTOCOL(" sigma: ");
  5197. SERIAL_PROTOCOL_F(sigma,6);
  5198. }
  5199. if (verbose_level > 0)
  5200. SERIAL_PROTOCOLPGM("\n");
  5201. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5202. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5203. st_synchronize();
  5204. }
  5205. _delay(1000);
  5206. clean_up_after_endstop_move(l_feedmultiply);
  5207. // enable_endstops(true);
  5208. if (verbose_level > 0) {
  5209. SERIAL_PROTOCOLPGM("Mean: ");
  5210. SERIAL_PROTOCOL_F(mean, 6);
  5211. SERIAL_PROTOCOLPGM("\n");
  5212. }
  5213. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5214. SERIAL_PROTOCOL_F(sigma, 6);
  5215. SERIAL_PROTOCOLPGM("\n\n");
  5216. Sigma_Exit:
  5217. break;
  5218. }
  5219. #endif // Z_PROBE_REPEATABILITY_TEST
  5220. #endif // ENABLE_AUTO_BED_LEVELING
  5221. /*!
  5222. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5223. #### Usage
  5224. M73 [ P | R | Q | S | C | D ]
  5225. #### Parameters
  5226. - `P` - Percent in normal mode
  5227. - `R` - Time remaining in normal mode
  5228. - `Q` - Percent in silent mode
  5229. - `S` - Time in silent mode
  5230. - `C` - Time to change/pause/user interaction in normal mode
  5231. - `D` - Time to change/pause/user interaction in silent mode
  5232. */
  5233. case 73: //M73 show percent done, time remaining and time to change/pause
  5234. {
  5235. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5236. if(code_seen('R')) print_time_remaining_normal = code_value();
  5237. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5238. if(code_seen('S')) print_time_remaining_silent = code_value();
  5239. if(code_seen('C')){
  5240. float print_time_to_change_normal_f = code_value_float();
  5241. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5242. }
  5243. if(code_seen('D')){
  5244. float print_time_to_change_silent_f = code_value_float();
  5245. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5246. }
  5247. {
  5248. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5249. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5250. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5251. }
  5252. break;
  5253. }
  5254. /*!
  5255. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5256. #### Usage
  5257. M104 [ S ]
  5258. #### Parameters
  5259. - `S` - Target temperature
  5260. */
  5261. case 104: // M104
  5262. {
  5263. uint8_t extruder;
  5264. if(setTargetedHotend(104,extruder)){
  5265. break;
  5266. }
  5267. if (code_seen('S'))
  5268. {
  5269. setTargetHotendSafe(code_value(), extruder);
  5270. }
  5271. break;
  5272. }
  5273. /*!
  5274. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5275. It is processed much earlier as to bypass the cmdqueue.
  5276. */
  5277. case 112:
  5278. kill(MSG_M112_KILL, 3);
  5279. break;
  5280. /*!
  5281. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5282. #### Usage
  5283. M140 [ S ]
  5284. #### Parameters
  5285. - `S` - Target temperature
  5286. */
  5287. case 140:
  5288. if (code_seen('S')) setTargetBed(code_value());
  5289. break;
  5290. /*!
  5291. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5292. Prints temperatures:
  5293. - `T:` - Hotend (actual / target)
  5294. - `B:` - Bed (actual / target)
  5295. - `Tx:` - x Tool (actual / target)
  5296. - `@:` - Hotend power
  5297. - `B@:` - Bed power
  5298. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5299. - `A:` - Ambient actual (only MK3/s)
  5300. _Example:_
  5301. 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
  5302. */
  5303. case 105:
  5304. {
  5305. uint8_t extruder;
  5306. if(setTargetedHotend(105, extruder)){
  5307. break;
  5308. }
  5309. SERIAL_PROTOCOLPGM("ok ");
  5310. gcode_M105(extruder);
  5311. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5312. cmdbuffer_front_already_processed = true;
  5313. break;
  5314. }
  5315. #if defined(AUTO_REPORT)
  5316. /*!
  5317. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5318. #### Usage
  5319. M155 [ S ] [ C ]
  5320. #### Parameters
  5321. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5322. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5323. bit 0 = Auto-report temperatures
  5324. bit 1 = Auto-report fans
  5325. bit 2 = Auto-report position
  5326. bit 3 = free
  5327. bit 4 = free
  5328. bit 5 = free
  5329. bit 6 = free
  5330. bit 7 = free
  5331. */
  5332. case 155:
  5333. {
  5334. if (code_seen('S')){
  5335. autoReportFeatures.SetPeriod( code_value_uint8() );
  5336. }
  5337. if (code_seen('C')){
  5338. autoReportFeatures.SetMask(code_value_uint8());
  5339. } else{
  5340. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5341. }
  5342. }
  5343. break;
  5344. #endif //AUTO_REPORT
  5345. /*!
  5346. ### 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>
  5347. #### Usage
  5348. M104 [ B | R | S ]
  5349. #### Parameters (not mandatory)
  5350. - `S` - Set extruder temperature
  5351. - `R` - Set extruder temperature
  5352. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5353. Parameters S and R are treated identically.
  5354. Command always waits for both cool down and heat up.
  5355. If no parameters are supplied waits for previously set extruder temperature.
  5356. */
  5357. case 109:
  5358. {
  5359. uint8_t extruder;
  5360. if(setTargetedHotend(109, extruder)){
  5361. break;
  5362. }
  5363. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5364. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5365. prusa_statistics(1);
  5366. #ifdef AUTOTEMP
  5367. autotemp_enabled=false;
  5368. #endif
  5369. if (code_seen('S')) {
  5370. setTargetHotendSafe(code_value(), extruder);
  5371. } else if (code_seen('R')) {
  5372. setTargetHotendSafe(code_value(), extruder);
  5373. }
  5374. #ifdef AUTOTEMP
  5375. if (code_seen('S')) autotemp_min=code_value();
  5376. if (code_seen('B')) autotemp_max=code_value();
  5377. if (code_seen('F'))
  5378. {
  5379. autotemp_factor=code_value();
  5380. autotemp_enabled=true;
  5381. }
  5382. #endif
  5383. codenum = _millis();
  5384. /* See if we are heating up or cooling down */
  5385. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5386. cancel_heatup = false;
  5387. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5388. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5389. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5390. prusa_statistics(2);
  5391. //starttime=_millis();
  5392. previous_millis_cmd.start();
  5393. }
  5394. break;
  5395. /*!
  5396. ### 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>
  5397. #### Usage
  5398. M190 [ R | S ]
  5399. #### Parameters (not mandatory)
  5400. - `S` - Set extruder temperature and wait for heating
  5401. - `R` - Set extruder temperature and wait for heating or cooling
  5402. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5403. */
  5404. case 190:
  5405. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5406. {
  5407. bool CooldownNoWait = false;
  5408. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5409. heating_status = HeatingStatus::BED_HEATING;
  5410. prusa_statistics(1);
  5411. if (code_seen('S'))
  5412. {
  5413. setTargetBed(code_value());
  5414. CooldownNoWait = true;
  5415. }
  5416. else if (code_seen('R'))
  5417. {
  5418. setTargetBed(code_value());
  5419. }
  5420. codenum = _millis();
  5421. cancel_heatup = false;
  5422. target_direction = isHeatingBed(); // true if heating, false if cooling
  5423. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5424. {
  5425. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5426. {
  5427. if (!farm_mode) {
  5428. float tt = degHotend(active_extruder);
  5429. SERIAL_PROTOCOLPGM("T:");
  5430. SERIAL_PROTOCOL(tt);
  5431. SERIAL_PROTOCOLPGM(" E:");
  5432. SERIAL_PROTOCOL((int)active_extruder);
  5433. SERIAL_PROTOCOLPGM(" B:");
  5434. SERIAL_PROTOCOL_F(degBed(), 1);
  5435. SERIAL_PROTOCOLLN();
  5436. }
  5437. codenum = _millis();
  5438. }
  5439. manage_heater();
  5440. manage_inactivity();
  5441. lcd_update(0);
  5442. }
  5443. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5444. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5445. previous_millis_cmd.start();
  5446. }
  5447. #endif
  5448. break;
  5449. #if defined(FAN_PIN) && FAN_PIN > -1
  5450. /*!
  5451. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5452. #### Usage
  5453. M106 [ S ]
  5454. #### Parameters
  5455. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5456. */
  5457. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5458. if (code_seen('S')){
  5459. fanSpeed = code_value_uint8();
  5460. }
  5461. else {
  5462. fanSpeed = 255;
  5463. }
  5464. break;
  5465. /*!
  5466. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5467. */
  5468. case 107:
  5469. fanSpeed = 0;
  5470. break;
  5471. #endif //FAN_PIN
  5472. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5473. /*!
  5474. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5475. Only works if the firmware is compiled with PS_ON_PIN defined.
  5476. */
  5477. case 80:
  5478. SET_OUTPUT(PS_ON_PIN); //GND
  5479. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5480. // If you have a switch on suicide pin, this is useful
  5481. // if you want to start another print with suicide feature after
  5482. // a print without suicide...
  5483. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5484. SET_OUTPUT(SUICIDE_PIN);
  5485. WRITE(SUICIDE_PIN, HIGH);
  5486. #endif
  5487. powersupply = true;
  5488. LCD_MESSAGERPGM(MSG_WELCOME);
  5489. lcd_update(0);
  5490. break;
  5491. /*!
  5492. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5493. Only works if the firmware is compiled with PS_ON_PIN defined.
  5494. */
  5495. case 81:
  5496. disable_heater();
  5497. st_synchronize();
  5498. disable_e0();
  5499. disable_e1();
  5500. disable_e2();
  5501. finishAndDisableSteppers();
  5502. fanSpeed = 0;
  5503. _delay(1000); // Wait a little before to switch off
  5504. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5505. st_synchronize();
  5506. suicide();
  5507. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5508. SET_OUTPUT(PS_ON_PIN);
  5509. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5510. #endif
  5511. powersupply = false;
  5512. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5513. lcd_update(0);
  5514. break;
  5515. #endif
  5516. /*!
  5517. ### 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>
  5518. Makes the extruder interpret extrusion as absolute positions.
  5519. */
  5520. case 82:
  5521. axis_relative_modes &= ~E_AXIS_MASK;
  5522. break;
  5523. /*!
  5524. ### 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>
  5525. Makes the extruder interpret extrusion values as relative positions.
  5526. */
  5527. case 83:
  5528. axis_relative_modes |= E_AXIS_MASK;
  5529. break;
  5530. /*!
  5531. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5532. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5533. This command can be used without any additional parameters. In that case all steppers are disabled.
  5534. 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.
  5535. M84 [ S | X | Y | Z | E ]
  5536. - `S` - Seconds
  5537. - `X` - X axis
  5538. - `Y` - Y axis
  5539. - `Z` - Z axis
  5540. - `E` - Extruder
  5541. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5542. Equal to M84 (compatibility)
  5543. */
  5544. case 18: //compatibility
  5545. case 84: // M84
  5546. if(code_seen('S')){
  5547. stepper_inactive_time = code_value() * 1000;
  5548. }
  5549. else
  5550. {
  5551. 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])));
  5552. if(all_axis)
  5553. {
  5554. st_synchronize();
  5555. disable_e0();
  5556. disable_e1();
  5557. disable_e2();
  5558. finishAndDisableSteppers();
  5559. }
  5560. else
  5561. {
  5562. st_synchronize();
  5563. if (code_seen('X')) disable_x();
  5564. if (code_seen('Y')) disable_y();
  5565. if (code_seen('Z')) disable_z();
  5566. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5567. if (code_seen('E')) {
  5568. disable_e0();
  5569. disable_e1();
  5570. disable_e2();
  5571. }
  5572. #endif
  5573. }
  5574. }
  5575. break;
  5576. /*!
  5577. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5578. #### Usage
  5579. M85 [ S ]
  5580. #### Parameters
  5581. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5582. */
  5583. case 85: // M85
  5584. if(code_seen('S')) {
  5585. max_inactive_time = code_value() * 1000;
  5586. }
  5587. break;
  5588. #ifdef SAFETYTIMER
  5589. /*!
  5590. ### 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>
  5591. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5592. #### Usage
  5593. M86 [ S ]
  5594. #### Parameters
  5595. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5596. */
  5597. case 86:
  5598. if (code_seen('S')) {
  5599. safetytimer_inactive_time = code_value() * 1000;
  5600. safetyTimer.start();
  5601. }
  5602. break;
  5603. #endif
  5604. /*!
  5605. ### 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>
  5606. 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)
  5607. #### Usage
  5608. M92 [ X | Y | Z | E ]
  5609. #### Parameters
  5610. - `X` - Steps per unit for the X drive
  5611. - `Y` - Steps per unit for the Y drive
  5612. - `Z` - Steps per unit for the Z drive
  5613. - `E` - Steps per unit for the extruder drive
  5614. */
  5615. case 92:
  5616. for(int8_t i=0; i < NUM_AXIS; i++)
  5617. {
  5618. if(code_seen(axis_codes[i]))
  5619. {
  5620. if(i == E_AXIS) { // E
  5621. float value = code_value();
  5622. if(value < 20.0) {
  5623. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5624. cs.max_jerk[E_AXIS] *= factor;
  5625. max_feedrate[i] *= factor;
  5626. axis_steps_per_sqr_second[i] *= factor;
  5627. }
  5628. cs.axis_steps_per_unit[i] = value;
  5629. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5630. fsensor.init();
  5631. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5632. }
  5633. else {
  5634. cs.axis_steps_per_unit[i] = code_value();
  5635. }
  5636. }
  5637. }
  5638. reset_acceleration_rates();
  5639. break;
  5640. /*!
  5641. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5642. Sets the line number in G-code
  5643. #### Usage
  5644. M110 [ N ]
  5645. #### Parameters
  5646. - `N` - Line number
  5647. */
  5648. case 110:
  5649. if (code_seen('N'))
  5650. gcode_LastN = code_value_long();
  5651. break;
  5652. /*!
  5653. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5654. 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).
  5655. #### Usage
  5656. M113 [ S ]
  5657. #### Parameters
  5658. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5659. */
  5660. case 113:
  5661. if (code_seen('S')) {
  5662. host_keepalive_interval = code_value_uint8();
  5663. // NOMORE(host_keepalive_interval, 60);
  5664. }
  5665. else {
  5666. SERIAL_ECHO_START;
  5667. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5668. SERIAL_PROTOCOLLN();
  5669. }
  5670. break;
  5671. /*!
  5672. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5673. Print the firmware info and capabilities
  5674. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5675. `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.
  5676. _Examples:_
  5677. `M115` results:
  5678. `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`
  5679. `M115 V` results:
  5680. `3.8.1`
  5681. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5682. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5683. #### Usage
  5684. M115 [ V | U ]
  5685. #### Parameters
  5686. - V - Report current installed firmware version
  5687. - U - Firmware version provided by G-code to be compared to current one.
  5688. */
  5689. case 115: // M115
  5690. if (code_seen('V')) {
  5691. // Report the Prusa version number.
  5692. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5693. } else if (code_seen('U')) {
  5694. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5695. // pause the print for 30s and ask the user to upgrade the firmware.
  5696. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5697. } else {
  5698. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5699. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5700. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5701. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5702. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5703. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5704. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5705. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5706. SERIAL_ECHOPGM(" UUID:");
  5707. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5708. #ifdef EXTENDED_CAPABILITIES_REPORT
  5709. extended_capabilities_report();
  5710. #endif //EXTENDED_CAPABILITIES_REPORT
  5711. }
  5712. break;
  5713. /*!
  5714. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5715. */
  5716. case 114:
  5717. gcode_M114();
  5718. break;
  5719. /*
  5720. M117 moved up to get the high priority
  5721. case 117: // M117 display message
  5722. starpos = (strchr(strchr_pointer + 5,'*'));
  5723. if(starpos!=NULL)
  5724. *(starpos)='\0';
  5725. lcd_setstatus(strchr_pointer + 5);
  5726. break;*/
  5727. #ifdef M120_M121_ENABLED
  5728. /*!
  5729. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5730. */
  5731. case 120:
  5732. enable_endstops(true) ;
  5733. break;
  5734. /*!
  5735. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5736. */
  5737. case 121:
  5738. enable_endstops(false) ;
  5739. break;
  5740. #endif //M120_M121_ENABLED
  5741. /*!
  5742. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5743. 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.
  5744. */
  5745. case 119:
  5746. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5747. SERIAL_PROTOCOLLN();
  5748. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5749. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5750. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5751. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5752. }else{
  5753. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5754. }
  5755. SERIAL_PROTOCOLLN();
  5756. #endif
  5757. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5758. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5759. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5760. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5761. }else{
  5762. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5763. }
  5764. SERIAL_PROTOCOLLN();
  5765. #endif
  5766. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5767. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5768. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5769. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5770. }else{
  5771. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5772. }
  5773. SERIAL_PROTOCOLLN();
  5774. #endif
  5775. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5776. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5777. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5778. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5779. }else{
  5780. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5781. }
  5782. SERIAL_PROTOCOLLN();
  5783. #endif
  5784. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5785. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5786. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5787. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5788. }else{
  5789. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5790. }
  5791. SERIAL_PROTOCOLLN();
  5792. #endif
  5793. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5794. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5795. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5796. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5797. }else{
  5798. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5799. }
  5800. SERIAL_PROTOCOLLN();
  5801. #endif
  5802. break;
  5803. //!@todo update for all axes, use for loop
  5804. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5805. /*!
  5806. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5807. This command is used to report fan speeds and fan pwm values.
  5808. #### Usage
  5809. M123
  5810. - E0: - Hotend fan speed in RPM
  5811. - PRN1: - Part cooling fans speed in RPM
  5812. - E0@: - Hotend fan PWM value
  5813. - PRN1@: -Part cooling fan PWM value
  5814. _Example:_
  5815. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5816. */
  5817. case 123:
  5818. gcode_M123();
  5819. break;
  5820. #endif //FANCHECK and TACH_0 and TACH_1
  5821. #ifdef BLINKM
  5822. /*!
  5823. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5824. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5825. #### Usage
  5826. M150 [ R | U | B ]
  5827. #### Parameters
  5828. - `R` - Red color value
  5829. - `U` - Green color value. It is NOT `G`!
  5830. - `B` - Blue color value
  5831. */
  5832. case 150:
  5833. {
  5834. byte red;
  5835. byte grn;
  5836. byte blu;
  5837. if(code_seen('R')) red = code_value();
  5838. if(code_seen('U')) grn = code_value();
  5839. if(code_seen('B')) blu = code_value();
  5840. SendColors(red,grn,blu);
  5841. }
  5842. break;
  5843. #endif //BLINKM
  5844. /*!
  5845. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5846. #### Usage
  5847. M200 [ D | T ]
  5848. #### Parameters
  5849. - `D` - Diameter in mm
  5850. - `T` - Number of extruder (MMUs)
  5851. */
  5852. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5853. {
  5854. uint8_t extruder = active_extruder;
  5855. if(code_seen('T')) {
  5856. extruder = code_value_uint8();
  5857. if(extruder >= EXTRUDERS) {
  5858. SERIAL_ECHO_START;
  5859. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5860. break;
  5861. }
  5862. }
  5863. if(code_seen('D')) {
  5864. float diameter = code_value();
  5865. if (diameter == 0.0) {
  5866. // setting any extruder filament size disables volumetric on the assumption that
  5867. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5868. // for all extruders
  5869. cs.volumetric_enabled = false;
  5870. } else {
  5871. cs.filament_size[extruder] = code_value();
  5872. // make sure all extruders have some sane value for the filament size
  5873. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5874. #if EXTRUDERS > 1
  5875. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5876. #if EXTRUDERS > 2
  5877. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5878. #endif
  5879. #endif
  5880. cs.volumetric_enabled = true;
  5881. }
  5882. } else {
  5883. //reserved for setting filament diameter via UFID or filament measuring device
  5884. break;
  5885. }
  5886. calculate_extruder_multipliers();
  5887. }
  5888. break;
  5889. /*!
  5890. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5891. For each axis individually.
  5892. ##### Usage
  5893. M201 [ X | Y | Z | E ]
  5894. ##### Parameters
  5895. - `X` - Acceleration for X axis in units/s^2
  5896. - `Y` - Acceleration for Y axis in units/s^2
  5897. - `Z` - Acceleration for Z axis in units/s^2
  5898. - `E` - Acceleration for the active or specified extruder in units/s^2
  5899. */
  5900. case 201:
  5901. for (int8_t i = 0; i < NUM_AXIS; i++)
  5902. {
  5903. if (code_seen(axis_codes[i]))
  5904. {
  5905. unsigned long val = code_value();
  5906. #ifdef TMC2130
  5907. unsigned long val_silent = val;
  5908. if ((i == X_AXIS) || (i == Y_AXIS))
  5909. {
  5910. if (val > NORMAL_MAX_ACCEL_XY)
  5911. val = NORMAL_MAX_ACCEL_XY;
  5912. if (val_silent > SILENT_MAX_ACCEL_XY)
  5913. val_silent = SILENT_MAX_ACCEL_XY;
  5914. }
  5915. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5916. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5917. #else //TMC2130
  5918. max_acceleration_units_per_sq_second[i] = val;
  5919. #endif //TMC2130
  5920. }
  5921. }
  5922. // 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)
  5923. reset_acceleration_rates();
  5924. break;
  5925. #if 0 // Not used for Sprinter/grbl gen6
  5926. case 202: // M202
  5927. for(int8_t i=0; i < NUM_AXIS; i++) {
  5928. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5929. }
  5930. break;
  5931. #endif
  5932. /*!
  5933. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5934. For each axis individually.
  5935. ##### Usage
  5936. M203 [ X | Y | Z | E ]
  5937. ##### Parameters
  5938. - `X` - Maximum feedrate for X axis
  5939. - `Y` - Maximum feedrate for Y axis
  5940. - `Z` - Maximum feedrate for Z axis
  5941. - `E` - Maximum feedrate for extruder drives
  5942. */
  5943. case 203: // M203 max feedrate mm/sec
  5944. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5945. {
  5946. if (code_seen(axis_codes[i]))
  5947. {
  5948. float val = code_value();
  5949. #ifdef TMC2130
  5950. float val_silent = val;
  5951. if ((i == X_AXIS) || (i == Y_AXIS))
  5952. {
  5953. if (val > NORMAL_MAX_FEEDRATE_XY)
  5954. val = NORMAL_MAX_FEEDRATE_XY;
  5955. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5956. val_silent = SILENT_MAX_FEEDRATE_XY;
  5957. }
  5958. cs.max_feedrate_normal[i] = val;
  5959. cs.max_feedrate_silent[i] = val_silent;
  5960. #else //TMC2130
  5961. max_feedrate[i] = val;
  5962. #endif //TMC2130
  5963. }
  5964. }
  5965. break;
  5966. /*!
  5967. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  5968. #### Old format:
  5969. ##### Usage
  5970. M204 [ S | T ]
  5971. ##### Parameters
  5972. - `S` - normal moves
  5973. - `T` - filmanent only moves
  5974. #### New format:
  5975. ##### Usage
  5976. M204 [ P | R | T ]
  5977. ##### Parameters
  5978. - `P` - printing moves
  5979. - `R` - filmanent only moves
  5980. - `T` - travel moves (as of now T is ignored)
  5981. */
  5982. case 204:
  5983. {
  5984. if(code_seen('S')) {
  5985. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5986. // and it is also generated by Slic3r to control acceleration per extrusion type
  5987. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5988. cs.acceleration = cs.travel_acceleration = code_value();
  5989. // Interpret the T value as retract acceleration in the old Marlin format.
  5990. if(code_seen('T'))
  5991. cs.retract_acceleration = code_value();
  5992. } else {
  5993. // New acceleration format, compatible with the upstream Marlin.
  5994. if(code_seen('P'))
  5995. cs.acceleration = code_value();
  5996. if(code_seen('R'))
  5997. cs.retract_acceleration = code_value();
  5998. if(code_seen('T'))
  5999. cs.travel_acceleration = code_value();
  6000. }
  6001. }
  6002. break;
  6003. /*!
  6004. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6005. Set some advanced settings related to movement.
  6006. #### Usage
  6007. M205 [ S | T | B | X | Y | Z | E ]
  6008. #### Parameters
  6009. - `S` - Minimum feedrate for print moves (unit/s)
  6010. - `T` - Minimum feedrate for travel moves (units/s)
  6011. - `B` - Minimum segment time (us)
  6012. - `X` - Maximum X jerk (units/s)
  6013. - `Y` - Maximum Y jerk (units/s)
  6014. - `Z` - Maximum Z jerk (units/s)
  6015. - `E` - Maximum E jerk (units/s)
  6016. */
  6017. case 205:
  6018. {
  6019. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6020. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6021. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6022. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6023. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6024. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6025. if(code_seen('E'))
  6026. {
  6027. float e = code_value();
  6028. #ifndef LA_NOCOMPAT
  6029. e = la10c_jerk(e);
  6030. #endif
  6031. cs.max_jerk[E_AXIS] = e;
  6032. }
  6033. }
  6034. break;
  6035. /*!
  6036. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6037. #### Usage
  6038. M206 [ X | Y | Z ]
  6039. #### Parameters
  6040. - `X` - X axis offset
  6041. - `Y` - Y axis offset
  6042. - `Z` - Z axis offset
  6043. */
  6044. case 206:
  6045. for(uint8_t i=0; i < 3; i++)
  6046. {
  6047. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6048. }
  6049. break;
  6050. #ifdef FWRETRACT
  6051. /*!
  6052. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6053. #### Usage
  6054. M207 [ S | F | Z ]
  6055. #### Parameters
  6056. - `S` - positive length to retract, in mm
  6057. - `F` - retraction feedrate, in mm/min
  6058. - `Z` - additional zlift/hop
  6059. */
  6060. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6061. {
  6062. if(code_seen('S'))
  6063. {
  6064. cs.retract_length = code_value() ;
  6065. }
  6066. if(code_seen('F'))
  6067. {
  6068. cs.retract_feedrate = code_value()/60 ;
  6069. }
  6070. if(code_seen('Z'))
  6071. {
  6072. cs.retract_zlift = code_value() ;
  6073. }
  6074. }break;
  6075. /*!
  6076. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6077. #### Usage
  6078. M208 [ S | F ]
  6079. #### Parameters
  6080. - `S` - positive length surplus to the M207 Snnn, in mm
  6081. - `F` - feedrate, in mm/sec
  6082. */
  6083. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6084. {
  6085. if(code_seen('S'))
  6086. {
  6087. cs.retract_recover_length = code_value() ;
  6088. }
  6089. if(code_seen('F'))
  6090. {
  6091. cs.retract_recover_feedrate = code_value()/60 ;
  6092. }
  6093. }break;
  6094. /*!
  6095. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6096. 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.
  6097. #### Usage
  6098. M209 [ S ]
  6099. #### Parameters
  6100. - `S` - 1=true or 0=false
  6101. */
  6102. 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.
  6103. {
  6104. if(code_seen('S'))
  6105. {
  6106. switch(code_value_uint8())
  6107. {
  6108. case 0:
  6109. {
  6110. cs.autoretract_enabled=false;
  6111. retracted[0]=false;
  6112. #if EXTRUDERS > 1
  6113. retracted[1]=false;
  6114. #endif
  6115. #if EXTRUDERS > 2
  6116. retracted[2]=false;
  6117. #endif
  6118. }break;
  6119. case 1:
  6120. {
  6121. cs.autoretract_enabled=true;
  6122. retracted[0]=false;
  6123. #if EXTRUDERS > 1
  6124. retracted[1]=false;
  6125. #endif
  6126. #if EXTRUDERS > 2
  6127. retracted[2]=false;
  6128. #endif
  6129. }break;
  6130. default:
  6131. SERIAL_ECHO_START;
  6132. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6133. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6134. SERIAL_ECHOLNPGM("\"(1)");
  6135. }
  6136. }
  6137. }break;
  6138. #endif // FWRETRACT
  6139. /*!
  6140. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6141. #### Usage
  6142. M214 [P] [S] [N] [R] [F]
  6143. #### Parameters
  6144. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6145. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6146. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6147. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6148. except when the results in segment lengths greater than or less than the minimum
  6149. and maximum segment length. Set to 0 to disable.
  6150. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6151. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6152. */
  6153. 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>
  6154. {
  6155. // Extract all possible parameters if they appear
  6156. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6157. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6158. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6159. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6160. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6161. // 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
  6162. if (p <=0 || s < 0 || p < s)
  6163. {
  6164. // Should we display some error here?
  6165. break;
  6166. }
  6167. cs.mm_per_arc_segment = p;
  6168. cs.min_mm_per_arc_segment = s;
  6169. cs.n_arc_correction = n;
  6170. cs.min_arc_segments = r;
  6171. cs.arc_segments_per_sec = f;
  6172. }break;
  6173. #if EXTRUDERS > 1
  6174. /*!
  6175. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6176. 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.
  6177. #### Usage
  6178. M218 [ X | Y ]
  6179. #### Parameters
  6180. - `X` - X offset
  6181. - `Y` - Y offset
  6182. */
  6183. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6184. {
  6185. uint8_t extruder;
  6186. if(setTargetedHotend(218, extruder)){
  6187. break;
  6188. }
  6189. if(code_seen('X'))
  6190. {
  6191. extruder_offset[X_AXIS][extruder] = code_value();
  6192. }
  6193. if(code_seen('Y'))
  6194. {
  6195. extruder_offset[Y_AXIS][extruder] = code_value();
  6196. }
  6197. SERIAL_ECHO_START;
  6198. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6199. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6200. {
  6201. SERIAL_ECHO(" ");
  6202. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6203. SERIAL_ECHO(",");
  6204. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6205. }
  6206. SERIAL_ECHOLN("");
  6207. }break;
  6208. #endif
  6209. /*!
  6210. ### 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>
  6211. #### Usage
  6212. M220 [ B | S | R ]
  6213. #### Parameters
  6214. - `B` - Backup current speed factor
  6215. - `S` - Speed factor override percentage (0..100 or higher)
  6216. - `R` - Restore previous speed factor
  6217. */
  6218. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6219. {
  6220. bool codesWereSeen = false;
  6221. if (code_seen('B')) //backup current speed factor
  6222. {
  6223. saved_feedmultiply_mm = feedmultiply;
  6224. codesWereSeen = true;
  6225. }
  6226. if (code_seen('S'))
  6227. {
  6228. feedmultiply = code_value_short();
  6229. codesWereSeen = true;
  6230. }
  6231. if (code_seen('R')) //restore previous feedmultiply
  6232. {
  6233. feedmultiply = saved_feedmultiply_mm;
  6234. codesWereSeen = true;
  6235. }
  6236. if (!codesWereSeen)
  6237. {
  6238. printf_P(PSTR("%i%%\n"), feedmultiply);
  6239. }
  6240. }
  6241. break;
  6242. /*!
  6243. ### 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>
  6244. #### Usage
  6245. M221 [ S | T ]
  6246. #### Parameters
  6247. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6248. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6249. */
  6250. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6251. {
  6252. if (code_seen('S'))
  6253. {
  6254. int tmp_code = code_value_short();
  6255. if (code_seen('T'))
  6256. {
  6257. uint8_t extruder;
  6258. if (setTargetedHotend(221, extruder))
  6259. break;
  6260. extruder_multiply[extruder] = tmp_code;
  6261. }
  6262. else
  6263. {
  6264. extrudemultiply = tmp_code ;
  6265. }
  6266. }
  6267. else
  6268. {
  6269. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6270. }
  6271. calculate_extruder_multipliers();
  6272. }
  6273. break;
  6274. /*!
  6275. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6276. Wait until the specified pin reaches the state required
  6277. #### Usage
  6278. M226 [ P | S ]
  6279. #### Parameters
  6280. - `P` - pin number
  6281. - `S` - pin state
  6282. */
  6283. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6284. {
  6285. if(code_seen('P')){
  6286. int pin_number = code_value_short(); // pin number
  6287. int pin_state = -1; // required pin state - default is inverted
  6288. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6289. if(pin_state >= -1 && pin_state <= 1){
  6290. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6291. {
  6292. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6293. {
  6294. pin_number = -1;
  6295. break;
  6296. }
  6297. }
  6298. if (pin_number > -1)
  6299. {
  6300. int target = LOW;
  6301. st_synchronize();
  6302. pinMode(pin_number, INPUT);
  6303. switch(pin_state){
  6304. case 1:
  6305. target = HIGH;
  6306. break;
  6307. case 0:
  6308. target = LOW;
  6309. break;
  6310. case -1:
  6311. target = !digitalRead(pin_number);
  6312. break;
  6313. }
  6314. while(digitalRead(pin_number) != target){
  6315. manage_heater();
  6316. manage_inactivity();
  6317. lcd_update(0);
  6318. }
  6319. }
  6320. }
  6321. }
  6322. }
  6323. break;
  6324. #if NUM_SERVOS > 0
  6325. /*!
  6326. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6327. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6328. #### Usage
  6329. M280 [ P | S ]
  6330. #### Parameters
  6331. - `P` - Servo index (id)
  6332. - `S` - Target position
  6333. */
  6334. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6335. {
  6336. int servo_index = -1;
  6337. int servo_position = 0;
  6338. if (code_seen('P'))
  6339. servo_index = code_value();
  6340. if (code_seen('S')) {
  6341. servo_position = code_value();
  6342. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6343. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6344. servos[servo_index].attach(0);
  6345. #endif
  6346. servos[servo_index].write(servo_position);
  6347. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6348. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6349. servos[servo_index].detach();
  6350. #endif
  6351. }
  6352. else {
  6353. SERIAL_ECHO_START;
  6354. SERIAL_ECHO("Servo ");
  6355. SERIAL_ECHO(servo_index);
  6356. SERIAL_ECHOLN(" out of range");
  6357. }
  6358. }
  6359. else if (servo_index >= 0) {
  6360. SERIAL_PROTOCOL(MSG_OK);
  6361. SERIAL_PROTOCOL(" Servo ");
  6362. SERIAL_PROTOCOL(servo_index);
  6363. SERIAL_PROTOCOL(": ");
  6364. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6365. }
  6366. }
  6367. break;
  6368. #endif // NUM_SERVOS > 0
  6369. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6370. /*!
  6371. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6372. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6373. #### Usage
  6374. M300 [ S | P ]
  6375. #### Parameters
  6376. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6377. - `P` - duration in milliseconds
  6378. */
  6379. case 300: // M300
  6380. {
  6381. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6382. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6383. #if BEEPER > 0
  6384. if (beepP > 0)
  6385. Sound_MakeCustom(beepP,beepS,false);
  6386. #endif
  6387. }
  6388. break;
  6389. #endif // M300
  6390. #ifdef PIDTEMP
  6391. /*!
  6392. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6393. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6394. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6395. #### Usage
  6396. M301 [ P | I | D ]
  6397. #### Parameters
  6398. - `P` - proportional (Kp)
  6399. - `I` - integral (Ki)
  6400. - `D` - derivative (Kd)
  6401. */
  6402. case 301:
  6403. {
  6404. if(code_seen('P')) cs.Kp = code_value();
  6405. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6406. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6407. updatePID();
  6408. SERIAL_PROTOCOLRPGM(MSG_OK);
  6409. SERIAL_PROTOCOLPGM(" p:");
  6410. SERIAL_PROTOCOL(cs.Kp);
  6411. SERIAL_PROTOCOLPGM(" i:");
  6412. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6413. SERIAL_PROTOCOLPGM(" d:");
  6414. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6415. SERIAL_PROTOCOLLN();
  6416. }
  6417. break;
  6418. #endif //PIDTEMP
  6419. #ifdef PIDTEMPBED
  6420. /*!
  6421. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6422. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6423. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6424. #### Usage
  6425. M304 [ P | I | D ]
  6426. #### Parameters
  6427. - `P` - proportional (Kp)
  6428. - `I` - integral (Ki)
  6429. - `D` - derivative (Kd)
  6430. */
  6431. case 304:
  6432. {
  6433. if(code_seen('P')) cs.bedKp = code_value();
  6434. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6435. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6436. updatePID();
  6437. SERIAL_PROTOCOLRPGM(MSG_OK);
  6438. SERIAL_PROTOCOLPGM(" p:");
  6439. SERIAL_PROTOCOL(cs.bedKp);
  6440. SERIAL_PROTOCOLPGM(" i:");
  6441. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6442. SERIAL_PROTOCOLPGM(" d:");
  6443. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6444. }
  6445. break;
  6446. #endif //PIDTEMP
  6447. /*!
  6448. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6449. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6450. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6451. */
  6452. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6453. {
  6454. #ifdef CHDK
  6455. SET_OUTPUT(CHDK);
  6456. WRITE(CHDK, HIGH);
  6457. chdkHigh = _millis();
  6458. chdkActive = true;
  6459. #else
  6460. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6461. const uint8_t NUM_PULSES=16;
  6462. const float PULSE_LENGTH=0.01524;
  6463. for(int i=0; i < NUM_PULSES; i++) {
  6464. WRITE(PHOTOGRAPH_PIN, HIGH);
  6465. _delay_ms(PULSE_LENGTH);
  6466. WRITE(PHOTOGRAPH_PIN, LOW);
  6467. _delay_ms(PULSE_LENGTH);
  6468. }
  6469. _delay(7.33);
  6470. for(int i=0; i < NUM_PULSES; i++) {
  6471. WRITE(PHOTOGRAPH_PIN, HIGH);
  6472. _delay_ms(PULSE_LENGTH);
  6473. WRITE(PHOTOGRAPH_PIN, LOW);
  6474. _delay_ms(PULSE_LENGTH);
  6475. }
  6476. #endif
  6477. #endif //chdk end if
  6478. }
  6479. break;
  6480. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6481. /*!
  6482. ### 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>
  6483. 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.
  6484. #### Usage
  6485. M302 [ S ]
  6486. #### Parameters
  6487. - `S` - Cold extrude minimum temperature
  6488. */
  6489. case 302:
  6490. {
  6491. int temp = 0;
  6492. if (code_seen('S')) temp=code_value_short();
  6493. set_extrude_min_temp(temp);
  6494. }
  6495. break;
  6496. #endif
  6497. /*!
  6498. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6499. 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.
  6500. #### Usage
  6501. M303 [ E | S | C ]
  6502. #### Parameters
  6503. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6504. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6505. - `C` - Cycles, default `5`
  6506. */
  6507. case 303:
  6508. {
  6509. float temp = 150.0;
  6510. int e = 0;
  6511. int c = 5;
  6512. if (code_seen('E')) e = code_value_short();
  6513. if (e < 0)
  6514. temp = 70;
  6515. if (code_seen('S')) temp = code_value();
  6516. if (code_seen('C')) c = code_value_short();
  6517. PID_autotune(temp, e, c);
  6518. }
  6519. break;
  6520. #ifdef TEMP_MODEL
  6521. /*!
  6522. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6523. #### Usage
  6524. M310 ; report values
  6525. M310 [ A ] [ F ] ; autotune
  6526. M310 [ S ] ; set 0=disable 1=enable
  6527. M310 [ I ] [ R ] ; set resistance at index
  6528. M310 [ P | C ] ; set power, capacitance
  6529. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6530. M310 [ T ] ; set ambient temperature correction
  6531. #### Parameters
  6532. - `I` - resistance index position (0-15)
  6533. - `R` - resistance value at index (K/W; requires `I`)
  6534. - `P` - power (W)
  6535. - `C` - capacitance (J/K)
  6536. - `S` - set 0=disable 1=enable
  6537. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6538. - `E` - error threshold (K/s; default in variant)
  6539. - `W` - warning threshold (K/s; default in variant)
  6540. - `T` - ambient temperature correction (K; default in variant)
  6541. - `A` - autotune C+R values
  6542. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6543. */
  6544. case 310:
  6545. {
  6546. // parse all parameters
  6547. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6548. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6549. if(code_seen('C')) C = code_value();
  6550. if(code_seen('P')) P = code_value();
  6551. if(code_seen('I')) I = code_value_short();
  6552. if(code_seen('R')) R = code_value();
  6553. if(code_seen('S')) S = code_value_short();
  6554. if(code_seen('B')) B = code_value_short();
  6555. if(code_seen('E')) E = code_value();
  6556. if(code_seen('W')) W = code_value();
  6557. if(code_seen('T')) T = code_value();
  6558. if(code_seen('A')) A = code_value_short();
  6559. if(code_seen('F')) F = code_value_short();
  6560. // report values if nothing has been requested
  6561. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6562. temp_model_report_settings();
  6563. break;
  6564. }
  6565. // update all parameters
  6566. if(B >= 0) temp_model_set_warn_beep(B);
  6567. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6568. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6569. // enable the model last, if requested
  6570. if(S >= 0) temp_model_set_enabled(S);
  6571. // run autotune
  6572. if(A >= 0) temp_model_autotune(A, F > 0);
  6573. }
  6574. break;
  6575. #endif
  6576. /*!
  6577. ### 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>
  6578. Finishes all current moves and and thus clears the buffer.
  6579. Equivalent to `G4` with no parameters.
  6580. */
  6581. case 400:
  6582. {
  6583. st_synchronize();
  6584. }
  6585. break;
  6586. /*!
  6587. ### 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>
  6588. Currently three different materials are needed (default, flex and PVA).
  6589. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6590. #### Usage
  6591. M403 [ E | F ]
  6592. #### Parameters
  6593. - `E` - Extruder number. 0-indexed.
  6594. - `F` - Filament type
  6595. */
  6596. case 403:
  6597. {
  6598. // currently three different materials are needed (default, flex and PVA)
  6599. // add storing this information for different load/unload profiles etc. in the future
  6600. if (MMU2::mmu2.Enabled())
  6601. {
  6602. uint8_t extruder = 255;
  6603. uint8_t filament = FILAMENT_UNDEFINED;
  6604. if(code_seen('E')) extruder = code_value_uint8();
  6605. if(code_seen('F')) filament = code_value_uint8();
  6606. MMU2::mmu2.set_filament_type(extruder, filament);
  6607. }
  6608. }
  6609. break;
  6610. /*!
  6611. ### 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>
  6612. Save current parameters to EEPROM.
  6613. */
  6614. case 500:
  6615. {
  6616. Config_StoreSettings();
  6617. }
  6618. break;
  6619. /*!
  6620. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6621. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6622. */
  6623. case 501:
  6624. {
  6625. Config_RetrieveSettings();
  6626. }
  6627. break;
  6628. /*!
  6629. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6630. 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.
  6631. */
  6632. case 502:
  6633. {
  6634. Config_ResetDefault();
  6635. }
  6636. break;
  6637. /*!
  6638. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6639. 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.
  6640. */
  6641. case 503:
  6642. {
  6643. Config_PrintSettings();
  6644. }
  6645. break;
  6646. /*!
  6647. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6648. Resets the language to English.
  6649. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6650. */
  6651. case 509:
  6652. {
  6653. lang_reset();
  6654. SERIAL_ECHO_START;
  6655. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6656. }
  6657. break;
  6658. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6659. /*!
  6660. ### 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>
  6661. 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`.
  6662. #### Usage
  6663. M540 [ S ]
  6664. #### Parameters
  6665. - `S` - disabled=0, enabled=1
  6666. */
  6667. case 540:
  6668. {
  6669. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6670. }
  6671. break;
  6672. #endif
  6673. #ifdef ENABLE_AUTO_BED_LEVELING
  6674. /*!
  6675. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6676. 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.
  6677. 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.)
  6678. #### Usage
  6679. M851 [ Z ]
  6680. #### Parameters
  6681. - `Z` - Z offset probe to nozzle.
  6682. */
  6683. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6684. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6685. {
  6686. float value;
  6687. if (code_seen('Z'))
  6688. {
  6689. value = code_value();
  6690. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6691. {
  6692. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6693. SERIAL_ECHO_START;
  6694. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6695. SERIAL_PROTOCOLLN();
  6696. }
  6697. else
  6698. {
  6699. SERIAL_ECHO_START;
  6700. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6701. SERIAL_ECHORPGM(MSG_Z_MIN);
  6702. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6703. SERIAL_ECHORPGM(MSG_Z_MAX);
  6704. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6705. SERIAL_PROTOCOLLN();
  6706. }
  6707. }
  6708. else
  6709. {
  6710. SERIAL_ECHO_START;
  6711. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6712. SERIAL_ECHO(-cs.zprobe_zoffset);
  6713. SERIAL_PROTOCOLLN();
  6714. }
  6715. break;
  6716. }
  6717. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6718. #endif // ENABLE_AUTO_BED_LEVELING
  6719. /*!
  6720. ### 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>
  6721. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6722. If P is not specified nothing happens.
  6723. 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.
  6724. #### Usage
  6725. M552 [ P<IP_address> ]
  6726. #### Parameters
  6727. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6728. */
  6729. case 552:
  6730. {
  6731. if (code_seen('P'))
  6732. {
  6733. uint8_t valCnt = 0;
  6734. IP_address = 0;
  6735. do
  6736. {
  6737. *strchr_pointer = '*';
  6738. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6739. valCnt++;
  6740. } while ((valCnt < 4) && code_seen('.'));
  6741. if (valCnt != 4)
  6742. IP_address = 0;
  6743. }
  6744. } break;
  6745. #ifdef FILAMENTCHANGEENABLE
  6746. /*!
  6747. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6748. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6749. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6750. #### Usage
  6751. M600 [ X | Y | Z | E | L | AUTO ]
  6752. - `X` - X position, default 211
  6753. - `Y` - Y position, default 0
  6754. - `Z` - relative lift Z, default MIN_Z_FOR_SWAP.
  6755. - `E` - initial retract, default -2
  6756. - `L` - later retract distance for removal, default -80
  6757. - `AUTO` - Automatically (only with MMU)
  6758. */
  6759. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6760. {
  6761. st_synchronize();
  6762. float x_position = current_position[X_AXIS];
  6763. float y_position = current_position[Y_AXIS];
  6764. float z_shift = MIN_Z_FOR_SWAP;
  6765. float e_shift_init = 0;
  6766. float e_shift_late = 0;
  6767. bool automatic = false;
  6768. //Retract extruder
  6769. if(code_seen('E'))
  6770. {
  6771. e_shift_init = code_value();
  6772. }
  6773. else
  6774. {
  6775. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6776. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6777. #endif
  6778. }
  6779. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6780. if (code_seen('L'))
  6781. {
  6782. e_shift_late = code_value();
  6783. }
  6784. else
  6785. {
  6786. #ifdef FILAMENTCHANGE_FINALRETRACT
  6787. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6788. #endif
  6789. }
  6790. // Z lift. For safety only allow positive values
  6791. if (code_seen('Z')) z_shift = fabs(code_value());
  6792. //Move XY to side
  6793. if(code_seen('X'))
  6794. {
  6795. x_position = code_value();
  6796. }
  6797. else
  6798. {
  6799. #ifdef FILAMENTCHANGE_XPOS
  6800. x_position = FILAMENTCHANGE_XPOS;
  6801. #endif
  6802. }
  6803. if(code_seen('Y'))
  6804. {
  6805. y_position = code_value();
  6806. }
  6807. else
  6808. {
  6809. #ifdef FILAMENTCHANGE_YPOS
  6810. y_position = FILAMENTCHANGE_YPOS ;
  6811. #endif
  6812. }
  6813. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6814. automatic = true;
  6815. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6816. }
  6817. break;
  6818. #endif //FILAMENTCHANGEENABLE
  6819. /*!
  6820. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6821. */
  6822. /*!
  6823. ### M125 - Pause print (TODO: not implemented)
  6824. */
  6825. /*!
  6826. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6827. */
  6828. case 25:
  6829. case 601:
  6830. {
  6831. if (!isPrintPaused) {
  6832. st_synchronize();
  6833. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6834. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6835. lcd_pause_print();
  6836. }
  6837. }
  6838. break;
  6839. /*!
  6840. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6841. */
  6842. case 602:
  6843. {
  6844. if (isPrintPaused) lcd_resume_print();
  6845. }
  6846. break;
  6847. /*!
  6848. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6849. */
  6850. case 603: {
  6851. print_stop();
  6852. }
  6853. break;
  6854. #ifdef PINDA_THERMISTOR
  6855. /*!
  6856. ### 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>
  6857. Wait for PINDA thermistor to reach target temperature
  6858. #### Usage
  6859. M860 [ S ]
  6860. #### Parameters
  6861. - `S` - Target temperature
  6862. */
  6863. case 860:
  6864. {
  6865. int set_target_pinda = 0;
  6866. if (code_seen('S')) {
  6867. set_target_pinda = code_value_short();
  6868. }
  6869. else {
  6870. break;
  6871. }
  6872. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6873. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6874. SERIAL_PROTOCOLLN(set_target_pinda);
  6875. codenum = _millis();
  6876. cancel_heatup = false;
  6877. bool is_pinda_cooling = false;
  6878. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6879. is_pinda_cooling = true;
  6880. }
  6881. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6882. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6883. {
  6884. SERIAL_PROTOCOLPGM("P:");
  6885. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6886. SERIAL_PROTOCOL('/');
  6887. SERIAL_PROTOCOLLN(set_target_pinda);
  6888. codenum = _millis();
  6889. }
  6890. manage_heater();
  6891. manage_inactivity();
  6892. lcd_update(0);
  6893. }
  6894. LCD_MESSAGERPGM(MSG_OK);
  6895. break;
  6896. }
  6897. /*!
  6898. ### 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>
  6899. Set compensation ustep value `S` for compensation table index `I`.
  6900. #### Usage
  6901. M861 [ ? | ! | Z | S | I ]
  6902. #### Parameters
  6903. - `?` - Print current EEPROM offset values
  6904. - `!` - Set factory default values
  6905. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6906. - `S` - Microsteps
  6907. - `I` - Table index
  6908. */
  6909. case 861: {
  6910. const char * const _header = PSTR("index, temp, ustep, um");
  6911. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6912. int16_t usteps = 0;
  6913. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6914. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6915. SERIAL_PROTOCOLLNRPGM(_header);
  6916. for (uint8_t i = 0; i < 6; i++)
  6917. {
  6918. if(i > 0) {
  6919. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6920. }
  6921. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6922. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6923. SERIAL_PROTOCOLPGM(", ");
  6924. SERIAL_PROTOCOL(35 + (i * 5));
  6925. SERIAL_PROTOCOLPGM(", ");
  6926. SERIAL_PROTOCOL(usteps);
  6927. SERIAL_PROTOCOLPGM(", ");
  6928. SERIAL_PROTOCOLLN(mm * 1000);
  6929. }
  6930. }
  6931. else if (code_seen('!')) { // ! - Set factory default values
  6932. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6933. int16_t z_shift = 8; //40C - 20um - 8usteps
  6934. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6935. z_shift = 24; //45C - 60um - 24usteps
  6936. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6937. z_shift = 48; //50C - 120um - 48usteps
  6938. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6939. z_shift = 80; //55C - 200um - 80usteps
  6940. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6941. z_shift = 120; //60C - 300um - 120usteps
  6942. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6943. SERIAL_PROTOCOLLNPGM("factory restored");
  6944. }
  6945. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6946. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6947. int16_t z_shift = 0;
  6948. for (uint8_t i = 0; i < 5; i++) {
  6949. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  6950. }
  6951. SERIAL_PROTOCOLLNPGM("zerorized");
  6952. }
  6953. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6954. int16_t usteps = code_value_short();
  6955. if (code_seen('I')) {
  6956. uint8_t index = code_value_uint8();
  6957. if (index < 5) {
  6958. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  6959. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6960. SERIAL_PROTOCOLLNRPGM(_header);
  6961. for (uint8_t i = 0; i < 6; i++)
  6962. {
  6963. usteps = 0;
  6964. if (i > 0) {
  6965. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6966. }
  6967. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6968. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6969. SERIAL_PROTOCOLPGM(", ");
  6970. SERIAL_PROTOCOL(35 + (i * 5));
  6971. SERIAL_PROTOCOLPGM(", ");
  6972. SERIAL_PROTOCOL(usteps);
  6973. SERIAL_PROTOCOLPGM(", ");
  6974. SERIAL_PROTOCOLLN(mm * 1000);
  6975. }
  6976. }
  6977. }
  6978. }
  6979. else {
  6980. SERIAL_PROTOCOLLNPGM("no valid command");
  6981. }
  6982. } break;
  6983. #endif //PINDA_THERMISTOR
  6984. /*!
  6985. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  6986. Checks the parameters of the printer and gcode and performs compatibility check
  6987. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  6988. - M862.2 { P<model_code> | Q }
  6989. - M862.3 { P"<model_name>" | Q }
  6990. - M862.4 { P<fw_version> | Q }
  6991. - M862.5 { P<gcode_level> | Q }
  6992. When run with P<> argument, the check is performed against the input value.
  6993. When run with Q argument, the current value is shown.
  6994. M862.3 accepts text identifiers of printer types too.
  6995. The syntax of M862.3 is (note the quotes around the type):
  6996. M862.3 P "MK3S"
  6997. Accepted printer type identifiers and their numeric counterparts:
  6998. - MK1 (100)
  6999. - MK2 (200)
  7000. - MK2MM (201)
  7001. - MK2S (202)
  7002. - MK2SMM (203)
  7003. - MK2.5 (250)
  7004. - MK2.5MMU2 (20250)
  7005. - MK2.5S (252)
  7006. - MK2.5SMMU2S (20252)
  7007. - MK3 (300)
  7008. - MK3MMU2 (20300)
  7009. - MK3S (302)
  7010. - MK3SMMU2S (20302)
  7011. */
  7012. case 862: // M862: print checking
  7013. float nDummy;
  7014. uint8_t nCommand;
  7015. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7016. switch((ClPrintChecking)nCommand)
  7017. {
  7018. case ClPrintChecking::_Nozzle: // ~ .1
  7019. uint16_t nDiameter;
  7020. if(code_seen('P'))
  7021. {
  7022. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7023. nozzle_diameter_check(nDiameter);
  7024. }
  7025. else if(code_seen('Q'))
  7026. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7027. break;
  7028. case ClPrintChecking::_Model: { // ~ .2
  7029. uint16_t type = nPrinterType(MMU2::mmu2.Enabled());
  7030. if(code_seen('P'))
  7031. {
  7032. uint16_t nPrinterModel;
  7033. nPrinterModel=(uint16_t)code_value_long();
  7034. // based on current state of MMU (active/stopped/connecting) perform a runtime update of the printer type
  7035. printer_model_check(nPrinterModel, type);
  7036. }
  7037. else if(code_seen('Q'))
  7038. SERIAL_PROTOCOLLN(type);
  7039. } break;
  7040. case ClPrintChecking::_Smodel: { // ~ .3
  7041. const char *type = sPrinterType(MMU2::mmu2.Enabled());
  7042. if(code_seen('P'))
  7043. {
  7044. printer_smodel_check(strchr_pointer, type);
  7045. }
  7046. else if(code_seen('Q'))
  7047. SERIAL_PROTOCOLLNRPGM(type);
  7048. } break;
  7049. case ClPrintChecking::_Version: // ~ .4
  7050. if(code_seen('P'))
  7051. fw_version_check(++strchr_pointer);
  7052. else if(code_seen('Q'))
  7053. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7054. break;
  7055. case ClPrintChecking::_Gcode: // ~ .5
  7056. if(code_seen('P'))
  7057. {
  7058. uint16_t nGcodeLevel;
  7059. nGcodeLevel=(uint16_t)code_value_long();
  7060. gcode_level_check(nGcodeLevel);
  7061. }
  7062. else if(code_seen('Q'))
  7063. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7064. break;
  7065. }
  7066. break;
  7067. #ifdef LIN_ADVANCE
  7068. /*!
  7069. ### 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>
  7070. 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.
  7071. #### Usage
  7072. M900 [ K | R | W | H | D]
  7073. #### Parameters
  7074. - `K` - Advance K factor
  7075. - `R` - Set ratio directly (overrides WH/D)
  7076. - `W` - Width
  7077. - `H` - Height
  7078. - `D` - Diameter Set ratio from WH/D
  7079. */
  7080. case 900:
  7081. gcode_M900();
  7082. break;
  7083. #endif
  7084. /*!
  7085. ### 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>
  7086. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7087. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7088. #### Usage
  7089. M907 [ X | Y | Z | E | B | S ]
  7090. #### Parameters
  7091. - `X` - X motor driver
  7092. - `Y` - Y motor driver
  7093. - `Z` - Z motor driver
  7094. - `E` - Extruder motor driver
  7095. - `B` - Second Extruder motor driver
  7096. - `S` - All motors
  7097. */
  7098. case 907:
  7099. {
  7100. #ifdef TMC2130
  7101. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7102. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7103. if(code_seen(axis_codes[i])){
  7104. if( i == E_AXIS && FarmOrUserECool() ){
  7105. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7106. SERIAL_ECHOLNPGM(", M907 E ignored");
  7107. continue;
  7108. }
  7109. long cur_mA = code_value_long();
  7110. uint8_t val = tmc2130_cur2val(cur_mA);
  7111. tmc2130_set_current_h(i, val);
  7112. tmc2130_set_current_r(i, val);
  7113. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7114. }
  7115. }
  7116. #else //TMC2130
  7117. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7118. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7119. if(code_seen('B')) st_current_set(4,code_value());
  7120. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7121. #endif
  7122. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7123. if(code_seen('X')) st_current_set(0, code_value());
  7124. #endif
  7125. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7126. if(code_seen('Z')) st_current_set(1, code_value());
  7127. #endif
  7128. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7129. if(code_seen('E')) st_current_set(2, code_value());
  7130. #endif
  7131. #endif //TMC2130
  7132. }
  7133. break;
  7134. /*!
  7135. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7136. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7137. #### Usage
  7138. M908 [ P | S ]
  7139. #### Parameters
  7140. - `P` - channel
  7141. - `S` - current
  7142. */
  7143. case 908:
  7144. {
  7145. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7146. uint8_t channel,current;
  7147. if(code_seen('P')) channel=code_value();
  7148. if(code_seen('S')) current=code_value();
  7149. digitalPotWrite(channel, current);
  7150. #endif
  7151. }
  7152. break;
  7153. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7154. /*!
  7155. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7156. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7157. */
  7158. case 910:
  7159. {
  7160. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7161. }
  7162. break;
  7163. /*!
  7164. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7165. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7166. #### Usage
  7167. M911 [ X | Y | Z | E ]
  7168. #### Parameters
  7169. - `X` - X stepper driver holding current value
  7170. - `Y` - Y stepper driver holding current value
  7171. - `Z` - Z stepper driver holding current value
  7172. - `E` - Extruder stepper driver holding current value
  7173. */
  7174. case 911:
  7175. {
  7176. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7177. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7178. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7179. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7180. }
  7181. break;
  7182. /*!
  7183. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7184. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7185. #### Usage
  7186. M912 [ X | Y | Z | E ]
  7187. #### Parameters
  7188. - `X` - X stepper driver running current value
  7189. - `Y` - Y stepper driver running current value
  7190. - `Z` - Z stepper driver running current value
  7191. - `E` - Extruder stepper driver running current value
  7192. */
  7193. case 912:
  7194. {
  7195. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7196. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7197. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7198. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7199. }
  7200. break;
  7201. /*!
  7202. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7203. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7204. Shows TMC2130 currents.
  7205. */
  7206. case 913:
  7207. {
  7208. tmc2130_print_currents();
  7209. }
  7210. break;
  7211. /*!
  7212. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7213. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7214. */
  7215. case 914:
  7216. {
  7217. tmc2130_mode = TMC2130_MODE_NORMAL;
  7218. update_mode_profile();
  7219. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7220. }
  7221. break;
  7222. /*!
  7223. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7224. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7225. */
  7226. case 915:
  7227. {
  7228. tmc2130_mode = TMC2130_MODE_SILENT;
  7229. update_mode_profile();
  7230. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7231. }
  7232. break;
  7233. /*!
  7234. ### 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>
  7235. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7236. #### Usage
  7237. M916 [ X | Y | Z | E ]
  7238. #### Parameters
  7239. - `X` - X stepper driver stallguard sensitivity threshold value
  7240. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7241. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7242. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7243. */
  7244. case 916:
  7245. {
  7246. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7247. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7248. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7249. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7250. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7251. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7252. }
  7253. break;
  7254. /*!
  7255. ### 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>
  7256. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7257. #### Usage
  7258. M917 [ X | Y | Z | E ]
  7259. #### Parameters
  7260. - `X` - X stepper driver PWM amplitude offset value
  7261. - `Y` - Y stepper driver PWM amplitude offset value
  7262. - `Z` - Z stepper driver PWM amplitude offset value
  7263. - `E` - Extruder stepper driver PWM amplitude offset value
  7264. */
  7265. case 917:
  7266. {
  7267. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7268. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7269. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7270. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7271. }
  7272. break;
  7273. /*!
  7274. ### 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>
  7275. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7276. #### Usage
  7277. M918 [ X | Y | Z | E ]
  7278. #### Parameters
  7279. - `X` - X stepper driver PWM amplitude gradient value
  7280. - `Y` - Y stepper driver PWM amplitude gradient value
  7281. - `Z` - Z stepper driver PWM amplitude gradient value
  7282. - `E` - Extruder stepper driver PWM amplitude gradient value
  7283. */
  7284. case 918:
  7285. {
  7286. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7287. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7288. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7289. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7290. }
  7291. break;
  7292. #endif //TMC2130_SERVICE_CODES_M910_M918
  7293. /*!
  7294. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7295. 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!
  7296. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7297. #### Usage
  7298. M350 [ X | Y | Z | E | B | S ]
  7299. #### Parameters
  7300. - `X` - X new resolution
  7301. - `Y` - Y new resolution
  7302. - `Z` - Z new resolution
  7303. - `E` - E new resolution
  7304. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7305. - `B` - Second extruder new resolution
  7306. - `S` - All axes new resolution
  7307. */
  7308. case 350:
  7309. {
  7310. #ifdef TMC2130
  7311. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7312. {
  7313. if(code_seen(axis_codes[i]))
  7314. {
  7315. uint16_t res_new = code_value();
  7316. #ifdef ALLOW_ALL_MRES
  7317. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7318. #else
  7319. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7320. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7321. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7322. #endif
  7323. if (res_valid)
  7324. {
  7325. st_synchronize();
  7326. uint16_t res = tmc2130_get_res(i);
  7327. tmc2130_set_res(i, res_new);
  7328. cs.axis_ustep_resolution[i] = res_new;
  7329. if (res_new > res)
  7330. {
  7331. uint16_t fac = (res_new / res);
  7332. cs.axis_steps_per_unit[i] *= fac;
  7333. position[i] *= fac;
  7334. }
  7335. else
  7336. {
  7337. uint16_t fac = (res / res_new);
  7338. cs.axis_steps_per_unit[i] /= fac;
  7339. position[i] /= fac;
  7340. }
  7341. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7342. if (i == E_AXIS)
  7343. fsensor.init();
  7344. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7345. }
  7346. }
  7347. }
  7348. reset_acceleration_rates();
  7349. #else //TMC2130
  7350. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7351. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7352. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7353. if(code_seen('B')) microstep_mode(4,code_value());
  7354. microstep_readings();
  7355. #endif
  7356. #endif //TMC2130
  7357. }
  7358. break;
  7359. /*!
  7360. ### 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>
  7361. Toggle MS1 MS2 pins directly.
  7362. #### Usage
  7363. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7364. #### Parameters
  7365. - `X` - Update X axis
  7366. - `Y` - Update Y axis
  7367. - `Z` - Update Z axis
  7368. - `E` - Update E axis
  7369. - `S` - which MSx pin to toggle
  7370. - `B` - new pin value
  7371. */
  7372. case 351:
  7373. {
  7374. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7375. if(code_seen('S')) switch((int)code_value())
  7376. {
  7377. case 1:
  7378. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7379. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7380. break;
  7381. case 2:
  7382. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7383. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7384. break;
  7385. }
  7386. microstep_readings();
  7387. #endif
  7388. }
  7389. break;
  7390. /*!
  7391. ### M701 - Load filament to extruder <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7392. Load filament into the active extruder.
  7393. #### Usage
  7394. M701 [ P | T | L | Z ]
  7395. #### Parameters
  7396. - `P` - n index of MMU slot (zero based, so 0-4 like T0 and T4)
  7397. - `T` - Alias of `P`. Used for compatibility with Marlin
  7398. - `L` - Extrude distance for insertion (positive value)(manual reload)
  7399. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_LOAD
  7400. */
  7401. case 701:
  7402. {
  7403. uint8_t mmuSlotIndex = 0xffU;
  7404. float fastLoadLength = FILAMENTCHANGE_FIRSTFEED; // Only used without MMU
  7405. float z_target = MIN_Z_FOR_LOAD;
  7406. if( MMU2::mmu2.Enabled() )
  7407. {
  7408. if( code_seen('P') || code_seen('T') ) {
  7409. mmuSlotIndex = code_value_uint8();
  7410. }
  7411. }
  7412. if (code_seen('L')) fastLoadLength = code_value();
  7413. // Z lift. For safety only allow positive values
  7414. if (code_seen('Z')) z_target = fabs(code_value());
  7415. // Raise the Z axis
  7416. float delta = raise_z(z_target);
  7417. // Load filament
  7418. gcode_M701(fastLoadLength, mmuSlotIndex);
  7419. // Restore Z axis
  7420. raise_z(-delta);
  7421. }
  7422. break;
  7423. /*!
  7424. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7425. #### Usage
  7426. M702 [ U | Z ]
  7427. #### Parameters
  7428. - `U` - Retract distance for removal (manual reload). Default value is 0.
  7429. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_UNLOAD.
  7430. */
  7431. case 702:
  7432. {
  7433. float z_target = MIN_Z_FOR_UNLOAD;
  7434. float unloadLength = FILAMENTCHANGE_FINALRETRACT;
  7435. if (code_seen('U')) unloadLength = code_value();
  7436. // For safety only allow positive values
  7437. if (code_seen('Z')) z_target = fabs(code_value());
  7438. // Raise the Z axis
  7439. float delta = raise_z(z_target);
  7440. // Unload filament
  7441. if (MMU2::mmu2.Enabled()) MMU2::mmu2.unload();
  7442. else unload_filament(unloadLength);
  7443. // Restore Z axis
  7444. raise_z(-delta);
  7445. }
  7446. break;
  7447. /*!
  7448. ### M704 - Load to MMU <a href="https://reprap.org/wiki/G-code#M704:_Load_to_MMU">M704: Load to MMU</a>
  7449. #### Usage
  7450. M704 [ P ]
  7451. #### Parameters
  7452. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7453. */
  7454. case 704:
  7455. {
  7456. gcodes_M704_M705_M706(704);
  7457. }
  7458. break;
  7459. /*!
  7460. ### M705 - Eject filament <a href="https://reprap.org/wiki/G-code#M705:_Eject_filament">M705: Eject filament</a>
  7461. #### Usage
  7462. M705 [ P ]
  7463. #### Parameters
  7464. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7465. */
  7466. case 705:
  7467. {
  7468. gcodes_M704_M705_M706(705);
  7469. }
  7470. break;
  7471. /*!
  7472. ### M706 - Cut filament <a href="https://reprap.org/wiki/G-code#M706:_Cut_filament">M706: Cut filament</a>
  7473. #### Usage
  7474. M706 [ P ]
  7475. #### Parameters
  7476. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7477. */
  7478. case 706:
  7479. {
  7480. gcodes_M704_M705_M706(706);
  7481. }
  7482. break;
  7483. /*!
  7484. ### M707 - Read from MMU register <a href="https://reprap.org/wiki/G-code#M707:_Read_from_MMU_register">M707: Read from MMU register</a>
  7485. #### Usage
  7486. M707 [ A ]
  7487. #### Parameters
  7488. - `A` - Address of register in hexidecimal.
  7489. #### Example
  7490. M707 A0x1b - Read a 8bit integer from register 0x1b and prints the result onto the serial line.
  7491. Does nothing if the A parameter is not present or if MMU is not enabled.
  7492. */
  7493. case 707: {
  7494. if ( MMU2::mmu2.Enabled() ) {
  7495. if( code_seen('A') ) {
  7496. MMU2::mmu2.ReadRegister(uint8_t(strtol(strchr_pointer+1, NULL, 16)));
  7497. }
  7498. }
  7499. } break;
  7500. /*!
  7501. ### M708 - Write to MMU register <a href="https://reprap.org/wiki/G-code#M708:_Write_to_MMU_register">M707: Write to MMU register</a>
  7502. #### Usage
  7503. M708 [ A | X ]
  7504. #### Parameters
  7505. - `A` - Address of register in hexidecimal.
  7506. - `X` - Data to write (16-bit integer). Default value 0.
  7507. #### Example
  7508. M708 A0x1b X05 - Write to register 0x1b the value 05.
  7509. Does nothing if A parameter is missing or if MMU is not enabled.
  7510. */
  7511. case 708: {
  7512. if ( MMU2::mmu2.Enabled() ){
  7513. uint8_t addr = 0;
  7514. if( code_seen('A') ) {
  7515. addr = uint8_t(strtol(strchr_pointer+1, NULL, 16));
  7516. }
  7517. uint16_t data = 0;
  7518. if( code_seen('X') ) {
  7519. data = code_value_short();
  7520. }
  7521. if(addr){
  7522. MMU2::mmu2.WriteRegister(addr, data);
  7523. }
  7524. }
  7525. } break;
  7526. /*!
  7527. ### M709 - MMU reset <a href="https://reprap.org/wiki/G-code#M709:_MMU_reset">M709: MMU reset</a>
  7528. The MK3S cannot not power off the MMU, for that reason the functionality is not supported.
  7529. #### Usage
  7530. M709 [ X ]
  7531. #### Parameters
  7532. - `X` - Reset MMU (0:soft reset | 1:hardware reset)
  7533. #### Example
  7534. M709 X0 - issue an X0 command via communication into the MMU (soft reset)
  7535. M709 X1 - toggle the MMU's reset pin (hardware reset)
  7536. */
  7537. case 709:
  7538. {
  7539. if (MMU2::mmu2.Enabled() && code_seen('X'))
  7540. {
  7541. switch (code_value_uint8())
  7542. {
  7543. case 0:
  7544. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  7545. break;
  7546. case 1:
  7547. MMU2::mmu2.Reset(MMU2::MMU2::ResetPin);
  7548. break;
  7549. default:
  7550. break;
  7551. }
  7552. }
  7553. }
  7554. break;
  7555. /*!
  7556. #### End of M-Commands
  7557. */
  7558. default:
  7559. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7560. }
  7561. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7562. mcode_in_progress = 0;
  7563. }
  7564. }
  7565. // end if(code_seen('M')) (end of M codes)
  7566. /*!
  7567. -----------------------------------------------------------------------------------------
  7568. # T Codes
  7569. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7570. #### For MMU_V2:
  7571. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7572. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7573. @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.
  7574. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7575. */
  7576. else if(code_seen('T')){
  7577. TCodes(strchr_pointer, code_value_uint8());
  7578. } // end if(code_seen('T')) (end of T codes)
  7579. /*!
  7580. #### End of T-Codes
  7581. */
  7582. /**
  7583. *---------------------------------------------------------------------------------
  7584. *# D codes
  7585. */
  7586. else if (code_seen('D')) // D codes (debug)
  7587. {
  7588. switch(code_value_short())
  7589. {
  7590. /*!
  7591. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7592. */
  7593. case -1:
  7594. dcode__1(); break;
  7595. #ifdef DEBUG_DCODES
  7596. /*!
  7597. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7598. #### Usage
  7599. D0 [ B ]
  7600. #### Parameters
  7601. - `B` - Bootloader
  7602. */
  7603. case 0:
  7604. dcode_0(); break;
  7605. /*!
  7606. *
  7607. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7608. D1
  7609. *
  7610. */
  7611. case 1:
  7612. dcode_1(); break;
  7613. #endif
  7614. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7615. /*!
  7616. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7617. This command can be used without any additional parameters. It will read the entire RAM.
  7618. #### Usage
  7619. D2 [ A | C | X ]
  7620. #### Parameters
  7621. - `A` - Address (x0000-x1fff)
  7622. - `C` - Count (1-8192)
  7623. - `X` - Data
  7624. #### Notes
  7625. - The hex address needs to be lowercase without the 0 before the x
  7626. - Count is decimal
  7627. - The hex data needs to be lowercase
  7628. */
  7629. case 2:
  7630. dcode_2(); break;
  7631. #endif //DEBUG_DCODES
  7632. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7633. /*!
  7634. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7635. This command can be used without any additional parameters. It will read the entire eeprom.
  7636. #### Usage
  7637. D3 [ A | C | X ]
  7638. #### Parameters
  7639. - `A` - Address (x0000-x0fff)
  7640. - `C` - Count (1-4096)
  7641. - `X` - Data (hex)
  7642. #### Notes
  7643. - The hex address needs to be lowercase without the 0 before the x
  7644. - Count is decimal
  7645. - The hex data needs to be lowercase
  7646. */
  7647. case 3:
  7648. dcode_3(); break;
  7649. #endif //DEBUG_DCODE3
  7650. #ifdef DEBUG_DCODES
  7651. /*!
  7652. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7653. To read the digital value of a pin you need only to define the pin number.
  7654. #### Usage
  7655. D4 [ P | F | V ]
  7656. #### Parameters
  7657. - `P` - Pin (0-255)
  7658. - `F` - Function in/out (0/1)
  7659. - `V` - Value (0/1)
  7660. */
  7661. case 4:
  7662. dcode_4(); break;
  7663. #endif //DEBUG_DCODES
  7664. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7665. /*!
  7666. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7667. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7668. #### Usage
  7669. D5 [ A | C | X | E ]
  7670. #### Parameters
  7671. - `A` - Address (x00000-x3ffff)
  7672. - `C` - Count (1-8192)
  7673. - `X` - Data (hex)
  7674. - `E` - Erase
  7675. #### Notes
  7676. - The hex address needs to be lowercase without the 0 before the x
  7677. - Count is decimal
  7678. - The hex data needs to be lowercase
  7679. */
  7680. case 5:
  7681. dcode_5(); break;
  7682. #endif //DEBUG_DCODE5
  7683. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7684. /*!
  7685. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7686. Reserved
  7687. */
  7688. case 6:
  7689. dcode_6(); break;
  7690. #endif
  7691. #ifdef DEBUG_DCODES
  7692. /*!
  7693. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7694. Reserved
  7695. */
  7696. case 7:
  7697. dcode_7(); break;
  7698. /*!
  7699. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7700. #### Usage
  7701. D8 [ ? | ! | P | Z ]
  7702. #### Parameters
  7703. - `?` - Read PINDA temperature shift values
  7704. - `!` - Reset PINDA temperature shift values to default
  7705. - `P` - Pinda temperature [C]
  7706. - `Z` - Z Offset [mm]
  7707. */
  7708. case 8:
  7709. dcode_8(); break;
  7710. /*!
  7711. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7712. #### Usage
  7713. D9 [ I | V ]
  7714. #### Parameters
  7715. - `I` - ADC channel index
  7716. - `0` - Heater 0 temperature
  7717. - `1` - Heater 1 temperature
  7718. - `2` - Bed temperature
  7719. - `3` - PINDA temperature
  7720. - `4` - PWR voltage
  7721. - `5` - Ambient temperature
  7722. - `6` - BED voltage
  7723. - `V` Value to be written as simulated
  7724. */
  7725. case 9:
  7726. dcode_9(); break;
  7727. /*!
  7728. ### 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>
  7729. */
  7730. case 10:
  7731. dcode_10(); break;
  7732. /*!
  7733. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7734. Writes the current time in the log file.
  7735. */
  7736. #endif //DEBUG_DCODES
  7737. #ifdef XFLASH_DUMP
  7738. /*!
  7739. ### 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>
  7740. Generate a crash dump for later retrival.
  7741. #### Usage
  7742. D20 [E]
  7743. ### Parameters
  7744. - `E` - Perform an emergency crash dump (resets the printer).
  7745. ### Notes
  7746. - A crash dump can be later recovered with D21, or cleared with D22.
  7747. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7748. is completed.
  7749. */
  7750. case 20: {
  7751. dcode_20();
  7752. break;
  7753. };
  7754. /*!
  7755. ### 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>
  7756. Output the complete crash dump (if present) to the serial.
  7757. #### Usage
  7758. D21
  7759. ### Notes
  7760. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7761. */
  7762. case 21: {
  7763. dcode_21();
  7764. break;
  7765. };
  7766. /*!
  7767. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7768. Clear an existing internal crash dump.
  7769. #### Usage
  7770. D22
  7771. */
  7772. case 22: {
  7773. dcode_22();
  7774. break;
  7775. };
  7776. #endif //XFLASH_DUMP
  7777. #ifdef EMERGENCY_SERIAL_DUMP
  7778. /*!
  7779. ### 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>
  7780. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7781. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7782. #### Usage
  7783. D23 [E] [R]
  7784. #### Parameters
  7785. - `E` - Perform an emergency crash dump (resets the printer).
  7786. - `R` - Disable online dumps.
  7787. */
  7788. case 23: {
  7789. dcode_23();
  7790. break;
  7791. };
  7792. #endif
  7793. #ifdef TEMP_MODEL_DEBUG
  7794. /*!
  7795. ## D70 - Enable low-level temperature model logging for offline simulation
  7796. #### Usage
  7797. D70 [ S ]
  7798. #### Parameters
  7799. - `S` - Enable 0-1 (default 0)
  7800. */
  7801. case 70: {
  7802. if(code_seen('S'))
  7803. temp_model_log_enable(code_value_short());
  7804. break;
  7805. }
  7806. #endif
  7807. #ifdef HEATBED_ANALYSIS
  7808. /*!
  7809. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7810. This command will log data to SD card file "mesh.txt".
  7811. #### Usage
  7812. D80 [ E | F | G | H | I | J ]
  7813. #### Parameters
  7814. - `E` - Dimension X (default 40)
  7815. - `F` - Dimention Y (default 40)
  7816. - `G` - Points X (default 40)
  7817. - `H` - Points Y (default 40)
  7818. - `I` - Offset X (default 74)
  7819. - `J` - Offset Y (default 34)
  7820. */
  7821. case 80:
  7822. dcode_80(); break;
  7823. /*!
  7824. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7825. This command will log data to SD card file "wldsd.txt".
  7826. #### Usage
  7827. D81 [ E | F | G | H | I | J ]
  7828. #### Parameters
  7829. - `E` - Dimension X (default 40)
  7830. - `F` - Dimention Y (default 40)
  7831. - `G` - Points X (default 40)
  7832. - `H` - Points Y (default 40)
  7833. - `I` - Offset X (default 74)
  7834. - `J` - Offset Y (default 34)
  7835. */
  7836. case 81:
  7837. dcode_81(); break;
  7838. #endif //HEATBED_ANALYSIS
  7839. #ifdef DEBUG_DCODES
  7840. /*!
  7841. ### 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>
  7842. */
  7843. case 106:
  7844. dcode_106(); break;
  7845. #ifdef TMC2130
  7846. /*!
  7847. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7848. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7849. #### Usage
  7850. D2130 [ Axis | Command | Subcommand | Value ]
  7851. #### Parameters
  7852. - Axis
  7853. - `X` - X stepper driver
  7854. - `Y` - Y stepper driver
  7855. - `Z` - Z stepper driver
  7856. - `E` - Extruder stepper driver
  7857. - Commands
  7858. - `0` - Current off
  7859. - `1` - Current on
  7860. - `+` - Single step
  7861. - `-` - Single step oposite direction
  7862. - `NNN` - Value sereval steps
  7863. - `?` - Read register
  7864. - Subcommands for read register
  7865. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7866. - `step` - Step
  7867. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7868. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7869. - `wave` - Microstep linearity compensation curve
  7870. - `!` - Set register
  7871. - Subcommands for set register
  7872. - `mres` - Micro step resolution
  7873. - `step` - Step
  7874. - `wave` - Microstep linearity compensation curve
  7875. - Values for set register
  7876. - `0, 180 --> 250` - Off
  7877. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7878. - `@` - Home calibrate axis
  7879. Examples:
  7880. D2130E?wave
  7881. Print extruder microstep linearity compensation curve
  7882. D2130E!wave0
  7883. Disable extruder linearity compensation curve, (sine curve is used)
  7884. D2130E!wave220
  7885. (sin(x))^1.1 extruder microstep compensation curve used
  7886. Notes:
  7887. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7888. *
  7889. */
  7890. case 2130:
  7891. dcode_2130(); break;
  7892. #endif //TMC2130
  7893. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7894. /*!
  7895. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7896. #### Usage
  7897. D9125 [ ? | ! | R | X | Y | L ]
  7898. #### Parameters
  7899. - `?` - Print values
  7900. - `!` - Print values
  7901. - `R` - Resolution. Not active in code
  7902. - `X` - X values
  7903. - `Y` - Y values
  7904. - `L` - Activate filament sensor log
  7905. */
  7906. case 9125:
  7907. dcode_9125(); break;
  7908. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7909. #endif //DEBUG_DCODES
  7910. default:
  7911. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7912. }
  7913. }
  7914. else
  7915. {
  7916. SERIAL_ECHO_START;
  7917. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7918. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7919. SERIAL_ECHOLNPGM("\"(2)");
  7920. }
  7921. KEEPALIVE_STATE(NOT_BUSY);
  7922. ClearToSend();
  7923. }
  7924. /*!
  7925. #### End of D-Codes
  7926. */
  7927. /** @defgroup GCodes G-Code List
  7928. */
  7929. // ---------------------------------------------------
  7930. void FlushSerialRequestResend()
  7931. {
  7932. //char cmdbuffer[bufindr][100]="Resend:";
  7933. MYSERIAL.flush();
  7934. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7935. }
  7936. // Confirm the execution of a command, if sent from a serial line.
  7937. // Execution of a command from a SD card will not be confirmed.
  7938. void ClearToSend()
  7939. {
  7940. previous_millis_cmd.start();
  7941. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7942. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7943. }
  7944. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7945. void update_currents() {
  7946. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7947. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7948. float tmp_motor[3];
  7949. //SERIAL_ECHOLNPGM("Currents updated: ");
  7950. if (destination[Z_AXIS] < Z_SILENT) {
  7951. //SERIAL_ECHOLNPGM("LOW");
  7952. for (uint8_t i = 0; i < 3; i++) {
  7953. st_current_set(i, current_low[i]);
  7954. /*MYSERIAL.print(int(i));
  7955. SERIAL_ECHOPGM(": ");
  7956. MYSERIAL.println(current_low[i]);*/
  7957. }
  7958. }
  7959. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7960. //SERIAL_ECHOLNPGM("HIGH");
  7961. for (uint8_t i = 0; i < 3; i++) {
  7962. st_current_set(i, current_high[i]);
  7963. /*MYSERIAL.print(int(i));
  7964. SERIAL_ECHOPGM(": ");
  7965. MYSERIAL.println(current_high[i]);*/
  7966. }
  7967. }
  7968. else {
  7969. for (uint8_t i = 0; i < 3; i++) {
  7970. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7971. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7972. st_current_set(i, tmp_motor[i]);
  7973. /*MYSERIAL.print(int(i));
  7974. SERIAL_ECHOPGM(": ");
  7975. MYSERIAL.println(tmp_motor[i]);*/
  7976. }
  7977. }
  7978. }
  7979. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7980. void get_coordinates() {
  7981. bool seen[4]={false,false,false,false};
  7982. for(int8_t i=0; i < NUM_AXIS; i++) {
  7983. if(code_seen(axis_codes[i]))
  7984. {
  7985. bool relative = axis_relative_modes & (1 << i);
  7986. destination[i] = code_value();
  7987. if (i == E_AXIS) {
  7988. float emult = extruder_multiplier[active_extruder];
  7989. if (emult != 1.) {
  7990. if (! relative) {
  7991. destination[i] -= current_position[i];
  7992. relative = true;
  7993. }
  7994. destination[i] *= emult;
  7995. }
  7996. }
  7997. if (relative)
  7998. destination[i] += current_position[i];
  7999. seen[i]=true;
  8000. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8001. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  8002. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8003. }
  8004. else destination[i] = current_position[i]; //Are these else lines really needed?
  8005. }
  8006. if(code_seen('F')) {
  8007. next_feedrate = code_value();
  8008. if(next_feedrate > 0.0) feedrate = next_feedrate;
  8009. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  8010. {
  8011. // float e_max_speed =
  8012. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  8013. }
  8014. }
  8015. }
  8016. void clamp_to_software_endstops(float target[3])
  8017. {
  8018. #ifdef DEBUG_DISABLE_SWLIMITS
  8019. return;
  8020. #endif //DEBUG_DISABLE_SWLIMITS
  8021. world2machine_clamp(target[0], target[1]);
  8022. // Clamp the Z coordinate.
  8023. if (min_software_endstops) {
  8024. float negative_z_offset = 0;
  8025. #ifdef ENABLE_AUTO_BED_LEVELING
  8026. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8027. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8028. #endif
  8029. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8030. }
  8031. if (max_software_endstops) {
  8032. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8033. }
  8034. }
  8035. uint16_t restore_interrupted_gcode() {
  8036. // When recovering from a previous print move, restore the originally
  8037. // calculated start position on the first USB/SD command. This accounts
  8038. // properly for relative moves
  8039. if (
  8040. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  8041. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  8042. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  8043. )
  8044. ) {
  8045. memcpy(current_position, saved_start_position, sizeof(current_position));
  8046. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  8047. return saved_segment_idx;
  8048. }
  8049. else
  8050. return 1; //begin with the first segment
  8051. }
  8052. #ifdef MESH_BED_LEVELING
  8053. 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) {
  8054. float dx = x - current_position[X_AXIS];
  8055. float dy = y - current_position[Y_AXIS];
  8056. uint16_t n_segments = 0;
  8057. if (mbl.active) {
  8058. float len = fabs(dx) + fabs(dy);
  8059. if (len > 0)
  8060. // Split to 3cm segments or shorter.
  8061. n_segments = uint16_t(ceil(len / 30.f));
  8062. }
  8063. if (n_segments > 1 && start_segment_idx) {
  8064. float dz = z - current_position[Z_AXIS];
  8065. float de = e - current_position[E_AXIS];
  8066. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  8067. float t = float(i) / float(n_segments);
  8068. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8069. current_position[Y_AXIS] + t * dy,
  8070. current_position[Z_AXIS] + t * dz,
  8071. current_position[E_AXIS] + t * de,
  8072. feed_rate, extruder, current_position, i);
  8073. if (planner_aborted)
  8074. return;
  8075. }
  8076. }
  8077. // The rest of the path.
  8078. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  8079. }
  8080. #endif // MESH_BED_LEVELING
  8081. void prepare_move(uint16_t start_segment_idx)
  8082. {
  8083. clamp_to_software_endstops(destination);
  8084. previous_millis_cmd.start();
  8085. // Do not use feedmultiply for E or Z only moves
  8086. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8087. plan_buffer_line_destinationXYZE(feedrate/60);
  8088. }
  8089. else {
  8090. #ifdef MESH_BED_LEVELING
  8091. 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);
  8092. #else
  8093. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8094. #endif
  8095. }
  8096. set_current_to_destination();
  8097. }
  8098. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8099. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8100. // Trace the arc
  8101. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8102. // As far as the parser is concerned, the position is now == target. In reality the
  8103. // motion control system might still be processing the action and the real tool position
  8104. // in any intermediate location.
  8105. set_current_to_destination();
  8106. previous_millis_cmd.start();
  8107. }
  8108. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8109. #if defined(FAN_PIN)
  8110. #if CONTROLLERFAN_PIN == FAN_PIN
  8111. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8112. #endif
  8113. #endif
  8114. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8115. unsigned long lastMotorCheck = 0;
  8116. void controllerFan()
  8117. {
  8118. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8119. {
  8120. lastMotorCheck = _millis();
  8121. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8122. #if EXTRUDERS > 2
  8123. || !READ(E2_ENABLE_PIN)
  8124. #endif
  8125. #if EXTRUDER > 1
  8126. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8127. || !READ(X2_ENABLE_PIN)
  8128. #endif
  8129. || !READ(E1_ENABLE_PIN)
  8130. #endif
  8131. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8132. {
  8133. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8134. }
  8135. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8136. {
  8137. digitalWrite(CONTROLLERFAN_PIN, 0);
  8138. analogWrite(CONTROLLERFAN_PIN, 0);
  8139. }
  8140. else
  8141. {
  8142. // allows digital or PWM fan output to be used (see M42 handling)
  8143. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8144. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8145. }
  8146. }
  8147. }
  8148. #endif
  8149. #ifdef SAFETYTIMER
  8150. /**
  8151. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8152. *
  8153. * Full screen blocking notification message is shown after heater turning off.
  8154. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8155. * damage print.
  8156. *
  8157. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8158. */
  8159. static void handleSafetyTimer()
  8160. {
  8161. #if (EXTRUDERS > 1)
  8162. #error Implemented only for one extruder.
  8163. #endif //(EXTRUDERS > 1)
  8164. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8165. {
  8166. safetyTimer.stop();
  8167. }
  8168. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8169. {
  8170. safetyTimer.start();
  8171. }
  8172. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8173. {
  8174. setTargetBed(0);
  8175. setAllTargetHotends(0);
  8176. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8177. }
  8178. }
  8179. #endif //SAFETYTIMER
  8180. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8181. {
  8182. #ifdef FILAMENT_SENSOR
  8183. if (fsensor.update()) {
  8184. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8185. }
  8186. #endif
  8187. #ifdef SAFETYTIMER
  8188. handleSafetyTimer();
  8189. #endif //SAFETYTIMER
  8190. #if defined(KILL_PIN) && KILL_PIN > -1
  8191. static int killCount = 0; // make the inactivity button a bit less responsive
  8192. const int KILL_DELAY = 10000;
  8193. #endif
  8194. if(buflen < (BUFSIZE-1)){
  8195. get_command();
  8196. }
  8197. if(previous_millis_cmd.expired(max_inactive_time))
  8198. if(max_inactive_time)
  8199. kill(_n("Inactivity Shutdown"), 4);
  8200. if(stepper_inactive_time) {
  8201. if(previous_millis_cmd.expired(stepper_inactive_time))
  8202. {
  8203. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8204. disable_x();
  8205. disable_y();
  8206. disable_z();
  8207. disable_e0();
  8208. disable_e1();
  8209. disable_e2();
  8210. }
  8211. }
  8212. }
  8213. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8214. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8215. {
  8216. chdkActive = false;
  8217. WRITE(CHDK, LOW);
  8218. }
  8219. #endif
  8220. #if defined(KILL_PIN) && KILL_PIN > -1
  8221. // Check if the kill button was pressed and wait just in case it was an accidental
  8222. // key kill key press
  8223. // -------------------------------------------------------------------------------
  8224. if( 0 == READ(KILL_PIN) )
  8225. {
  8226. killCount++;
  8227. }
  8228. else if (killCount > 0)
  8229. {
  8230. killCount--;
  8231. }
  8232. // Exceeded threshold and we can confirm that it was not accidental
  8233. // KILL the machine
  8234. // ----------------------------------------------------------------
  8235. if ( killCount >= KILL_DELAY)
  8236. {
  8237. kill(NULL, 5);
  8238. }
  8239. #endif
  8240. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8241. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8242. #endif
  8243. #ifdef EXTRUDER_RUNOUT_PREVENT
  8244. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8245. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8246. {
  8247. bool oldstatus=READ(E0_ENABLE_PIN);
  8248. enable_e0();
  8249. float oldepos=current_position[E_AXIS];
  8250. float oldedes=destination[E_AXIS];
  8251. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8252. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8253. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8254. current_position[E_AXIS]=oldepos;
  8255. destination[E_AXIS]=oldedes;
  8256. plan_set_e_position(oldepos);
  8257. previous_millis_cmd.start();
  8258. st_synchronize();
  8259. WRITE(E0_ENABLE_PIN,oldstatus);
  8260. }
  8261. #endif
  8262. check_axes_activity();
  8263. MMU2::mmu2.mmu_loop();
  8264. // handle longpress
  8265. if(lcd_longpress_trigger)
  8266. {
  8267. // long press is not possible in modal mode, wait until ready
  8268. if (lcd_longpress_func && lcd_update_enabled)
  8269. {
  8270. lcd_longpress_func();
  8271. lcd_longpress_trigger = 0;
  8272. }
  8273. }
  8274. #if defined(AUTO_REPORT)
  8275. host_autoreport();
  8276. #endif //AUTO_REPORT
  8277. host_keepalive();
  8278. }
  8279. void kill(const char *full_screen_message, unsigned char id)
  8280. {
  8281. printf_P(_N("KILL: %d\n"), id);
  8282. //return;
  8283. cli(); // Stop interrupts
  8284. disable_heater();
  8285. disable_x();
  8286. // SERIAL_ECHOLNPGM("kill - disable Y");
  8287. disable_y();
  8288. poweroff_z();
  8289. disable_e0();
  8290. disable_e1();
  8291. disable_e2();
  8292. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8293. pinMode(PS_ON_PIN,INPUT);
  8294. #endif
  8295. SERIAL_ERROR_START;
  8296. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8297. if (full_screen_message != NULL) {
  8298. SERIAL_ERRORLNRPGM(full_screen_message);
  8299. lcd_display_message_fullscreen_P(full_screen_message);
  8300. } else {
  8301. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8302. }
  8303. // FMC small patch to update the LCD before ending
  8304. sei(); // enable interrupts
  8305. for ( int i=5; i--; lcd_update(0))
  8306. {
  8307. _delay(200);
  8308. }
  8309. cli(); // disable interrupts
  8310. suicide();
  8311. while(1)
  8312. {
  8313. #ifdef WATCHDOG
  8314. wdt_reset();
  8315. #endif //WATCHDOG
  8316. /* Intentionally left empty */
  8317. } // Wait for reset
  8318. }
  8319. void UnconditionalStop()
  8320. {
  8321. CRITICAL_SECTION_START;
  8322. // Disable all heaters and unroll the temperature wait loop stack
  8323. disable_heater();
  8324. cancel_heatup = true;
  8325. heating_status = HeatingStatus::NO_HEATING;
  8326. // Clear any saved printing state
  8327. cancel_saved_printing();
  8328. // Abort the planner
  8329. planner_abort_hard();
  8330. // Reset the queue
  8331. cmdqueue_reset();
  8332. cmdqueue_serial_disabled = false;
  8333. // Reset the sd status
  8334. card.sdprinting = false;
  8335. card.closefile();
  8336. st_reset_timer();
  8337. CRITICAL_SECTION_END;
  8338. }
  8339. // Emergency stop used by overtemp functions which allows recovery
  8340. // WARNING: This function is called *continuously* during a thermal failure.
  8341. //
  8342. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8343. // "allow_recovery". If recovery is allowed, this forces a printer-initiated instantanenous pause
  8344. // (just like an LCD pause) that bypasses the host pausing functionality. In this state the printer
  8345. // is kept in busy state and *must* be recovered from the LCD.
  8346. void ThermalStop(bool allow_recovery)
  8347. {
  8348. if(Stopped == false) {
  8349. Stopped = true;
  8350. if(allow_recovery && (IS_SD_PRINTING || usb_timer.running())) {
  8351. if (!isPrintPaused) {
  8352. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8353. // we cannot make a distinction for the host here, the pause must be instantaneous
  8354. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8355. // disable heaters and save the original temperatures to saved_*, which will get
  8356. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8357. // original values after the pause handler is called.
  8358. float bed_temp = saved_bed_temperature;
  8359. float ext_temp = saved_extruder_temperature;
  8360. int fan_speed = saved_fan_speed;
  8361. lcd_pause_print();
  8362. saved_bed_temperature = bed_temp;
  8363. saved_extruder_temperature = ext_temp;
  8364. saved_fan_speed = fan_speed;
  8365. }
  8366. } else {
  8367. // We got a hard thermal error and/or there is no print going on. Just stop.
  8368. print_stop();
  8369. }
  8370. // Report the status on the serial, switch to a busy state
  8371. SERIAL_ERROR_START;
  8372. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8373. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8374. // higher-priority alert status message)
  8375. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8376. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8377. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8378. WRITE(BEEPER, HIGH);
  8379. // Always return to the status screen to ensure the NEW error is immediately shown.
  8380. lcd_return_to_status();
  8381. if(!allow_recovery) {
  8382. // prevent menu access for all fatal errors
  8383. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8384. }
  8385. }
  8386. }
  8387. bool IsStopped() { return Stopped; };
  8388. void finishAndDisableSteppers()
  8389. {
  8390. st_synchronize();
  8391. disable_x();
  8392. disable_y();
  8393. disable_z();
  8394. disable_e0();
  8395. disable_e1();
  8396. disable_e2();
  8397. #ifndef LA_NOCOMPAT
  8398. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8399. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8400. // state for the next print.
  8401. la10c_reset();
  8402. #endif
  8403. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8404. print_time_remaining_init();
  8405. }
  8406. #ifdef FAST_PWM_FAN
  8407. void setPwmFrequency(uint8_t pin, int val)
  8408. {
  8409. val &= 0x07;
  8410. switch(digitalPinToTimer(pin))
  8411. {
  8412. #if defined(TCCR0A)
  8413. case TIMER0A:
  8414. case TIMER0B:
  8415. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8416. // TCCR0B |= val;
  8417. break;
  8418. #endif
  8419. #if defined(TCCR1A)
  8420. case TIMER1A:
  8421. case TIMER1B:
  8422. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8423. // TCCR1B |= val;
  8424. break;
  8425. #endif
  8426. #if defined(TCCR2)
  8427. case TIMER2:
  8428. case TIMER2:
  8429. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8430. TCCR2 |= val;
  8431. break;
  8432. #endif
  8433. #if defined(TCCR2A)
  8434. case TIMER2A:
  8435. case TIMER2B:
  8436. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8437. TCCR2B |= val;
  8438. break;
  8439. #endif
  8440. #if defined(TCCR3A)
  8441. case TIMER3A:
  8442. case TIMER3B:
  8443. case TIMER3C:
  8444. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8445. TCCR3B |= val;
  8446. break;
  8447. #endif
  8448. #if defined(TCCR4A)
  8449. case TIMER4A:
  8450. case TIMER4B:
  8451. case TIMER4C:
  8452. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8453. TCCR4B |= val;
  8454. break;
  8455. #endif
  8456. #if defined(TCCR5A)
  8457. case TIMER5A:
  8458. case TIMER5B:
  8459. case TIMER5C:
  8460. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8461. TCCR5B |= val;
  8462. break;
  8463. #endif
  8464. }
  8465. }
  8466. #endif //FAST_PWM_FAN
  8467. //! @brief Get and validate extruder number
  8468. //!
  8469. //! If it is not specified, active_extruder is returned in parameter extruder.
  8470. //! @param [in] code M code number
  8471. //! @param [out] extruder
  8472. //! @return error
  8473. //! @retval true Invalid extruder specified in T code
  8474. //! @retval false Valid extruder specified in T code, or not specifiead
  8475. bool setTargetedHotend(int code, uint8_t &extruder)
  8476. {
  8477. extruder = active_extruder;
  8478. if(code_seen('T')) {
  8479. extruder = code_value_uint8();
  8480. if(extruder >= EXTRUDERS) {
  8481. SERIAL_ECHO_START;
  8482. serialprintPGM(PSTR("M"));
  8483. SERIAL_ECHO(code);
  8484. SERIAL_ECHOPGM(" Invalid extruder ");
  8485. SERIAL_PROTOCOLLN((int)extruder);
  8486. return true;
  8487. }
  8488. }
  8489. return false;
  8490. }
  8491. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) { //_total_filament_used unit: mm/100; print time in s
  8492. uint32_t _previous_filament = eeprom_init_default_dword((uint32_t *)EEPROM_FILAMENTUSED, 0); //_previous_filament unit: cm
  8493. uint32_t _previous_time = eeprom_init_default_dword((uint32_t *)EEPROM_TOTALTIME, 0); //_previous_time unit: min
  8494. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time / 60)); // EEPROM_TOTALTIME unit: min
  8495. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8496. total_filament_used = 0;
  8497. if (MMU2::mmu2.Enabled()) {
  8498. eeprom_add_dword((uint32_t *)EEPROM_TOTAL_TOOLCHANGE_COUNT, MMU2::mmu2.ToolChangeCounter());
  8499. // @@TODO why were EEPROM_MMU_FAIL_TOT and EEPROM_MMU_LOAD_FAIL_TOT behaving differently - i.e. updated with every change?
  8500. MMU2::mmu2.ClearToolChangeCounter();
  8501. MMU2::mmu2.ClearTMCFailures(); // not stored into EEPROM
  8502. }
  8503. }
  8504. float calculate_extruder_multiplier(float diameter) {
  8505. float out = 1.f;
  8506. if (cs.volumetric_enabled && diameter > 0.f) {
  8507. float area = M_PI * diameter * diameter * 0.25;
  8508. out = 1.f / area;
  8509. }
  8510. if (extrudemultiply != 100)
  8511. out *= float(extrudemultiply) * 0.01f;
  8512. return out;
  8513. }
  8514. void calculate_extruder_multipliers() {
  8515. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8516. #if EXTRUDERS > 1
  8517. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8518. #if EXTRUDERS > 2
  8519. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8520. #endif
  8521. #endif
  8522. }
  8523. void delay_keep_alive(unsigned int ms)
  8524. {
  8525. for (;;) {
  8526. manage_heater();
  8527. // Manage inactivity, but don't disable steppers on timeout.
  8528. manage_inactivity(true);
  8529. lcd_update(0);
  8530. if (ms == 0)
  8531. break;
  8532. else if (ms >= 50) {
  8533. _delay(50);
  8534. ms -= 50;
  8535. } else {
  8536. _delay(ms);
  8537. ms = 0;
  8538. }
  8539. }
  8540. }
  8541. static void wait_for_heater(long codenum, uint8_t extruder) {
  8542. if (!degTargetHotend(extruder))
  8543. return;
  8544. #ifdef TEMP_RESIDENCY_TIME
  8545. long residencyStart;
  8546. residencyStart = -1;
  8547. /* continue to loop until we have reached the target temp
  8548. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8549. cancel_heatup = false;
  8550. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8551. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8552. #else
  8553. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8554. #endif //TEMP_RESIDENCY_TIME
  8555. if ((_millis() - codenum) > 1000UL)
  8556. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8557. if (!farm_mode) {
  8558. SERIAL_PROTOCOLPGM("T:");
  8559. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8560. SERIAL_PROTOCOLPGM(" E:");
  8561. SERIAL_PROTOCOL((int)extruder);
  8562. #ifdef TEMP_RESIDENCY_TIME
  8563. SERIAL_PROTOCOLPGM(" W:");
  8564. if (residencyStart > -1)
  8565. {
  8566. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8567. SERIAL_PROTOCOLLN(codenum);
  8568. }
  8569. else
  8570. {
  8571. SERIAL_PROTOCOLLN('?');
  8572. }
  8573. }
  8574. #else
  8575. SERIAL_PROTOCOLLN();
  8576. #endif
  8577. codenum = _millis();
  8578. }
  8579. manage_heater();
  8580. manage_inactivity(true); //do not disable steppers
  8581. lcd_update(0);
  8582. #ifdef TEMP_RESIDENCY_TIME
  8583. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8584. or when current temp falls outside the hysteresis after target temp was reached */
  8585. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8586. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8587. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8588. {
  8589. residencyStart = _millis();
  8590. }
  8591. #endif //TEMP_RESIDENCY_TIME
  8592. }
  8593. }
  8594. void check_babystep()
  8595. {
  8596. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8597. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8598. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8599. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8600. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8601. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8602. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8603. babystep_z);
  8604. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8605. lcd_update_enable(true);
  8606. }
  8607. }
  8608. #ifdef HEATBED_ANALYSIS
  8609. void d_setup()
  8610. {
  8611. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8612. pinMode(D_DATA, INPUT_PULLUP);
  8613. pinMode(D_REQUIRE, OUTPUT);
  8614. digitalWrite(D_REQUIRE, HIGH);
  8615. }
  8616. float d_ReadData()
  8617. {
  8618. int digit[13];
  8619. String mergeOutput;
  8620. float output;
  8621. digitalWrite(D_REQUIRE, HIGH);
  8622. for (int i = 0; i<13; i++)
  8623. {
  8624. for (int j = 0; j < 4; j++)
  8625. {
  8626. while (digitalRead(D_DATACLOCK) == LOW) {}
  8627. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8628. bitWrite(digit[i], j, digitalRead(D_DATA));
  8629. }
  8630. }
  8631. digitalWrite(D_REQUIRE, LOW);
  8632. mergeOutput = "";
  8633. output = 0;
  8634. for (int r = 5; r <= 10; r++) //Merge digits
  8635. {
  8636. mergeOutput += digit[r];
  8637. }
  8638. output = mergeOutput.toFloat();
  8639. if (digit[4] == 8) //Handle sign
  8640. {
  8641. output *= -1;
  8642. }
  8643. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8644. {
  8645. output /= 10;
  8646. }
  8647. return output;
  8648. }
  8649. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8650. int t1 = 0;
  8651. int t_delay = 0;
  8652. int digit[13];
  8653. int m;
  8654. char str[3];
  8655. //String mergeOutput;
  8656. char mergeOutput[15];
  8657. float output;
  8658. int mesh_point = 0; //index number of calibration point
  8659. 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
  8660. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8661. float mesh_home_z_search = 4;
  8662. float measure_z_height = 0.2f;
  8663. float row[x_points_num];
  8664. int ix = 0;
  8665. int iy = 0;
  8666. const char* filename_wldsd = "mesh.txt";
  8667. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8668. char numb_wldsd[8]; // (" -A.BCD" + null)
  8669. #ifdef MICROMETER_LOGGING
  8670. d_setup();
  8671. #endif //MICROMETER_LOGGING
  8672. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8673. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8674. unsigned int custom_message_type_old = custom_message_type;
  8675. unsigned int custom_message_state_old = custom_message_state;
  8676. custom_message_type = CustomMsg::MeshBedLeveling;
  8677. custom_message_state = (x_points_num * y_points_num) + 10;
  8678. lcd_update(1);
  8679. //mbl.reset();
  8680. babystep_undo();
  8681. card.openFile(filename_wldsd, false);
  8682. /*destination[Z_AXIS] = mesh_home_z_search;
  8683. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8684. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8685. for(int8_t i=0; i < NUM_AXIS; i++) {
  8686. current_position[i] = destination[i];
  8687. }
  8688. st_synchronize();
  8689. */
  8690. destination[Z_AXIS] = measure_z_height;
  8691. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8692. for(int8_t i=0; i < NUM_AXIS; i++) {
  8693. current_position[i] = destination[i];
  8694. }
  8695. st_synchronize();
  8696. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8697. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8698. SERIAL_PROTOCOL(x_points_num);
  8699. SERIAL_PROTOCOLPGM(",");
  8700. SERIAL_PROTOCOL(y_points_num);
  8701. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8702. SERIAL_PROTOCOL(mesh_home_z_search);
  8703. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8704. SERIAL_PROTOCOL(x_dimension);
  8705. SERIAL_PROTOCOLPGM(",");
  8706. SERIAL_PROTOCOL(y_dimension);
  8707. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8708. while (mesh_point != x_points_num * y_points_num) {
  8709. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8710. iy = mesh_point / x_points_num;
  8711. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8712. float z0 = 0.f;
  8713. /*destination[Z_AXIS] = mesh_home_z_search;
  8714. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8715. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8716. for(int8_t i=0; i < NUM_AXIS; i++) {
  8717. current_position[i] = destination[i];
  8718. }
  8719. st_synchronize();*/
  8720. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8721. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8722. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8723. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8724. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8725. set_current_to_destination();
  8726. st_synchronize();
  8727. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8728. delay_keep_alive(1000);
  8729. #ifdef MICROMETER_LOGGING
  8730. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8731. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8732. //strcat(data_wldsd, numb_wldsd);
  8733. //MYSERIAL.println(data_wldsd);
  8734. //delay(1000);
  8735. //delay(3000);
  8736. //t1 = millis();
  8737. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8738. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8739. memset(digit, 0, sizeof(digit));
  8740. //cli();
  8741. digitalWrite(D_REQUIRE, LOW);
  8742. for (int i = 0; i<13; i++)
  8743. {
  8744. //t1 = millis();
  8745. for (int j = 0; j < 4; j++)
  8746. {
  8747. while (digitalRead(D_DATACLOCK) == LOW) {}
  8748. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8749. //printf_P(PSTR("Done %d\n"), j);
  8750. bitWrite(digit[i], j, digitalRead(D_DATA));
  8751. }
  8752. //t_delay = (millis() - t1);
  8753. //SERIAL_PROTOCOLPGM(" ");
  8754. //SERIAL_PROTOCOL_F(t_delay, 5);
  8755. //SERIAL_PROTOCOLPGM(" ");
  8756. }
  8757. //sei();
  8758. digitalWrite(D_REQUIRE, HIGH);
  8759. mergeOutput[0] = '\0';
  8760. output = 0;
  8761. for (int r = 5; r <= 10; r++) //Merge digits
  8762. {
  8763. sprintf(str, "%d", digit[r]);
  8764. strcat(mergeOutput, str);
  8765. }
  8766. output = atof(mergeOutput);
  8767. if (digit[4] == 8) //Handle sign
  8768. {
  8769. output *= -1;
  8770. }
  8771. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8772. {
  8773. output *= 0.1;
  8774. }
  8775. //output = d_ReadData();
  8776. //row[ix] = current_position[Z_AXIS];
  8777. //row[ix] = d_ReadData();
  8778. row[ix] = output;
  8779. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8780. memset(data_wldsd, 0, sizeof(data_wldsd));
  8781. for (int i = 0; i < x_points_num; i++) {
  8782. SERIAL_PROTOCOLPGM(" ");
  8783. SERIAL_PROTOCOL_F(row[i], 5);
  8784. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8785. dtostrf(row[i], 7, 3, numb_wldsd);
  8786. strcat(data_wldsd, numb_wldsd);
  8787. }
  8788. card.write_command(data_wldsd);
  8789. SERIAL_PROTOCOLPGM("\n");
  8790. }
  8791. custom_message_state--;
  8792. mesh_point++;
  8793. lcd_update(1);
  8794. }
  8795. #endif //MICROMETER_LOGGING
  8796. card.closefile();
  8797. //clean_up_after_endstop_move(l_feedmultiply);
  8798. }
  8799. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8800. int t1 = 0;
  8801. int t_delay = 0;
  8802. int digit[13];
  8803. int m;
  8804. char str[3];
  8805. //String mergeOutput;
  8806. char mergeOutput[15];
  8807. float output;
  8808. int mesh_point = 0; //index number of calibration point
  8809. 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
  8810. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8811. float mesh_home_z_search = 4;
  8812. float row[x_points_num];
  8813. int ix = 0;
  8814. int iy = 0;
  8815. const char* filename_wldsd = "wldsd.txt";
  8816. char data_wldsd[70];
  8817. char numb_wldsd[10];
  8818. d_setup();
  8819. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8820. // We don't know where we are! HOME!
  8821. // Push the commands to the front of the message queue in the reverse order!
  8822. // There shall be always enough space reserved for these commands.
  8823. repeatcommand_front(); // repeat G80 with all its parameters
  8824. enquecommand_front_P(G28W0);
  8825. enquecommand_front_P((PSTR("G1 Z5")));
  8826. return;
  8827. }
  8828. unsigned int custom_message_type_old = custom_message_type;
  8829. unsigned int custom_message_state_old = custom_message_state;
  8830. custom_message_type = CustomMsg::MeshBedLeveling;
  8831. custom_message_state = (x_points_num * y_points_num) + 10;
  8832. lcd_update(1);
  8833. mbl.reset();
  8834. babystep_undo();
  8835. card.openFile(filename_wldsd, false);
  8836. current_position[Z_AXIS] = mesh_home_z_search;
  8837. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8838. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8839. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8840. int l_feedmultiply = setup_for_endstop_move(false);
  8841. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8842. SERIAL_PROTOCOL(x_points_num);
  8843. SERIAL_PROTOCOLPGM(",");
  8844. SERIAL_PROTOCOL(y_points_num);
  8845. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8846. SERIAL_PROTOCOL(mesh_home_z_search);
  8847. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8848. SERIAL_PROTOCOL(x_dimension);
  8849. SERIAL_PROTOCOLPGM(",");
  8850. SERIAL_PROTOCOL(y_dimension);
  8851. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8852. while (mesh_point != x_points_num * y_points_num) {
  8853. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8854. iy = mesh_point / x_points_num;
  8855. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8856. float z0 = 0.f;
  8857. current_position[Z_AXIS] = mesh_home_z_search;
  8858. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8859. st_synchronize();
  8860. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8861. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8862. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8863. st_synchronize();
  8864. 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
  8865. break;
  8866. card.closefile();
  8867. }
  8868. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8869. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8870. //strcat(data_wldsd, numb_wldsd);
  8871. //MYSERIAL.println(data_wldsd);
  8872. //_delay(1000);
  8873. //_delay(3000);
  8874. //t1 = _millis();
  8875. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8876. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8877. memset(digit, 0, sizeof(digit));
  8878. //cli();
  8879. digitalWrite(D_REQUIRE, LOW);
  8880. for (int i = 0; i<13; i++)
  8881. {
  8882. //t1 = _millis();
  8883. for (int j = 0; j < 4; j++)
  8884. {
  8885. while (digitalRead(D_DATACLOCK) == LOW) {}
  8886. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8887. bitWrite(digit[i], j, digitalRead(D_DATA));
  8888. }
  8889. //t_delay = (_millis() - t1);
  8890. //SERIAL_PROTOCOLPGM(" ");
  8891. //SERIAL_PROTOCOL_F(t_delay, 5);
  8892. //SERIAL_PROTOCOLPGM(" ");
  8893. }
  8894. //sei();
  8895. digitalWrite(D_REQUIRE, HIGH);
  8896. mergeOutput[0] = '\0';
  8897. output = 0;
  8898. for (int r = 5; r <= 10; r++) //Merge digits
  8899. {
  8900. sprintf(str, "%d", digit[r]);
  8901. strcat(mergeOutput, str);
  8902. }
  8903. output = atof(mergeOutput);
  8904. if (digit[4] == 8) //Handle sign
  8905. {
  8906. output *= -1;
  8907. }
  8908. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8909. {
  8910. output *= 0.1;
  8911. }
  8912. //output = d_ReadData();
  8913. //row[ix] = current_position[Z_AXIS];
  8914. memset(data_wldsd, 0, sizeof(data_wldsd));
  8915. for (int i = 0; i <3; i++) {
  8916. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8917. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8918. strcat(data_wldsd, numb_wldsd);
  8919. strcat(data_wldsd, ";");
  8920. }
  8921. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8922. dtostrf(output, 8, 5, numb_wldsd);
  8923. strcat(data_wldsd, numb_wldsd);
  8924. //strcat(data_wldsd, ";");
  8925. card.write_command(data_wldsd);
  8926. //row[ix] = d_ReadData();
  8927. row[ix] = output; // current_position[Z_AXIS];
  8928. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8929. for (int i = 0; i < x_points_num; i++) {
  8930. SERIAL_PROTOCOLPGM(" ");
  8931. SERIAL_PROTOCOL_F(row[i], 5);
  8932. }
  8933. SERIAL_PROTOCOLPGM("\n");
  8934. }
  8935. custom_message_state--;
  8936. mesh_point++;
  8937. lcd_update(1);
  8938. }
  8939. card.closefile();
  8940. clean_up_after_endstop_move(l_feedmultiply);
  8941. }
  8942. #endif //HEATBED_ANALYSIS
  8943. #ifndef PINDA_THERMISTOR
  8944. static void temp_compensation_start() {
  8945. custom_message_type = CustomMsg::TempCompPreheat;
  8946. custom_message_state = PINDA_HEAT_T + 1;
  8947. lcd_update(2);
  8948. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8949. current_position[E_AXIS] -= default_retraction;
  8950. }
  8951. plan_buffer_line_curposXYZE(400, active_extruder);
  8952. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8953. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8954. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8955. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8956. st_synchronize();
  8957. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8958. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8959. delay_keep_alive(1000);
  8960. custom_message_state = PINDA_HEAT_T - i;
  8961. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8962. else lcd_update(1);
  8963. }
  8964. custom_message_type = CustomMsg::Status;
  8965. custom_message_state = 0;
  8966. }
  8967. static void temp_compensation_apply() {
  8968. int i_add;
  8969. int z_shift = 0;
  8970. float z_shift_mm;
  8971. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8972. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8973. i_add = (target_temperature_bed - 60) / 10;
  8974. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  8975. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8976. }else {
  8977. //interpolation
  8978. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8979. }
  8980. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8981. 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);
  8982. st_synchronize();
  8983. plan_set_z_position(current_position[Z_AXIS]);
  8984. }
  8985. else {
  8986. //we have no temp compensation data
  8987. }
  8988. }
  8989. #endif //ndef PINDA_THERMISTOR
  8990. float temp_comp_interpolation(float inp_temperature) {
  8991. //cubic spline interpolation
  8992. int n, i, j;
  8993. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8994. int shift[10];
  8995. int temp_C[10];
  8996. n = 6; //number of measured points
  8997. shift[0] = 0;
  8998. for (i = 0; i < n; i++) {
  8999. if (i > 0) {
  9000. //read shift in steps from EEPROM
  9001. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  9002. }
  9003. temp_C[i] = 50 + i * 10; //temperature in C
  9004. #ifdef PINDA_THERMISTOR
  9005. constexpr int start_compensating_temp = 35;
  9006. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  9007. #ifdef SUPERPINDA_SUPPORT
  9008. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  9009. #endif //SUPERPINDA_SUPPORT
  9010. #else
  9011. temp_C[i] = 50 + i * 10; //temperature in C
  9012. #endif
  9013. x[i] = (float)temp_C[i];
  9014. f[i] = (float)shift[i];
  9015. }
  9016. if (inp_temperature < x[0]) return 0;
  9017. for (i = n - 1; i>0; i--) {
  9018. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9019. h[i - 1] = x[i] - x[i - 1];
  9020. }
  9021. //*********** formation of h, s , f matrix **************
  9022. for (i = 1; i<n - 1; i++) {
  9023. m[i][i] = 2 * (h[i - 1] + h[i]);
  9024. if (i != 1) {
  9025. m[i][i - 1] = h[i - 1];
  9026. m[i - 1][i] = h[i - 1];
  9027. }
  9028. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9029. }
  9030. //*********** forward elimination **************
  9031. for (i = 1; i<n - 2; i++) {
  9032. temp = (m[i + 1][i] / m[i][i]);
  9033. for (j = 1; j <= n - 1; j++)
  9034. m[i + 1][j] -= temp*m[i][j];
  9035. }
  9036. //*********** backward substitution *********
  9037. for (i = n - 2; i>0; i--) {
  9038. sum = 0;
  9039. for (j = i; j <= n - 2; j++)
  9040. sum += m[i][j] * s[j];
  9041. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9042. }
  9043. for (i = 0; i<n - 1; i++)
  9044. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9045. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9046. b = s[i] / 2;
  9047. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9048. d = f[i];
  9049. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9050. }
  9051. return sum;
  9052. }
  9053. #ifdef PINDA_THERMISTOR
  9054. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9055. {
  9056. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9057. if (!calibration_status_pinda()) return 0;
  9058. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9059. }
  9060. #endif //PINDA_THERMISTOR
  9061. void long_pause() //long pause print
  9062. {
  9063. st_synchronize();
  9064. start_pause_print = _millis();
  9065. // Stop heaters
  9066. heating_status = HeatingStatus::NO_HEATING;
  9067. setAllTargetHotends(0);
  9068. // Lift z
  9069. raise_z(Z_PAUSE_LIFT);
  9070. // Move XY to side
  9071. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9072. current_position[X_AXIS] = X_PAUSE_POS;
  9073. current_position[Y_AXIS] = Y_PAUSE_POS;
  9074. plan_buffer_line_curposXYZE(50);
  9075. }
  9076. // did we come here from a thermal error?
  9077. if(get_temp_error()) {
  9078. // time to stop the error beep
  9079. WRITE(BEEPER, LOW);
  9080. } else {
  9081. // Turn off the print fan
  9082. fanSpeed = 0;
  9083. }
  9084. }
  9085. void serialecho_temperatures() {
  9086. float tt = degHotend(active_extruder);
  9087. SERIAL_PROTOCOLPGM("T:");
  9088. SERIAL_PROTOCOL(tt);
  9089. SERIAL_PROTOCOLPGM(" E:");
  9090. SERIAL_PROTOCOL((int)active_extruder);
  9091. SERIAL_PROTOCOLPGM(" B:");
  9092. SERIAL_PROTOCOL_F(degBed(), 1);
  9093. SERIAL_PROTOCOLLN();
  9094. }
  9095. #ifdef UVLO_SUPPORT
  9096. void uvlo_drain_reset()
  9097. {
  9098. // burn all that residual power
  9099. wdt_enable(WDTO_1S);
  9100. WRITE(BEEPER,HIGH);
  9101. lcd_clear();
  9102. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9103. while(1);
  9104. }
  9105. void uvlo_()
  9106. {
  9107. unsigned long time_start = _millis();
  9108. bool sd_print = card.sdprinting;
  9109. // Conserve power as soon as possible.
  9110. #ifdef LCD_BL_PIN
  9111. backlightMode = BACKLIGHT_MODE_DIM;
  9112. backlightLevel_LOW = 0;
  9113. backlight_update();
  9114. #endif //LCD_BL_PIN
  9115. disable_x();
  9116. disable_y();
  9117. #ifdef TMC2130
  9118. tmc2130_set_current_h(Z_AXIS, 20);
  9119. tmc2130_set_current_r(Z_AXIS, 20);
  9120. tmc2130_set_current_h(E_AXIS, 20);
  9121. tmc2130_set_current_r(E_AXIS, 20);
  9122. #endif //TMC2130
  9123. // Stop all heaters
  9124. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9125. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9126. setAllTargetHotends(0);
  9127. setTargetBed(0);
  9128. // Calculate the file position, from which to resume this print.
  9129. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9130. {
  9131. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9132. sd_position -= sdlen_planner;
  9133. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9134. sd_position -= sdlen_cmdqueue;
  9135. if (sd_position < 0) sd_position = 0;
  9136. }
  9137. // save the global state at planning time
  9138. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9139. uint16_t feedrate_bckp;
  9140. if (current_block && !pos_invalid)
  9141. {
  9142. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9143. feedrate_bckp = current_block->gcode_feedrate;
  9144. saved_segment_idx = current_block->segment_idx;
  9145. }
  9146. else
  9147. {
  9148. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9149. feedrate_bckp = feedrate;
  9150. saved_segment_idx = 0;
  9151. }
  9152. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9153. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9154. // get the physical Z for further manipulation.
  9155. bool mbl_was_active = mbl.active;
  9156. mbl.active = false;
  9157. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9158. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9159. // are in action.
  9160. planner_abort_hard();
  9161. // Store the print logical Z position, which we need to recover (a slight error here would be
  9162. // recovered on the next Gcode instruction, while a physical location error would not)
  9163. float logical_z = current_position[Z_AXIS];
  9164. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9165. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9166. // Store the print E position before we lose track
  9167. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9168. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9169. // Clean the input command queue, inhibit serial processing using saved_printing
  9170. cmdqueue_reset();
  9171. card.sdprinting = false;
  9172. saved_printing = true;
  9173. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9174. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9175. planner_aborted = false;
  9176. sei();
  9177. // Retract
  9178. current_position[E_AXIS] -= default_retraction;
  9179. plan_buffer_line_curposXYZE(95);
  9180. st_synchronize();
  9181. disable_e0();
  9182. // Read out the current Z motor microstep counter to move the axis up towards
  9183. // a full step before powering off. NOTE: we need to ensure to schedule more
  9184. // than "dropsegments" steps in order to move (this is always the case here
  9185. // due to UVLO_Z_AXIS_SHIFT being used)
  9186. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9187. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9188. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9189. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9190. + UVLO_Z_AXIS_SHIFT;
  9191. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9192. st_synchronize();
  9193. poweroff_z();
  9194. // Write the file position.
  9195. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9196. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9197. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9198. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9199. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9200. // Scale the z value to 1u resolution.
  9201. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9202. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9203. }
  9204. // Write the _final_ Z position and motor microstep counter (unused).
  9205. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9206. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9207. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9208. // Store the current position.
  9209. if (pos_invalid)
  9210. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9211. else
  9212. {
  9213. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9214. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9215. }
  9216. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9217. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9218. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9219. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9220. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9221. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9222. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9223. #if EXTRUDERS > 1
  9224. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9225. #if EXTRUDERS > 2
  9226. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9227. #endif
  9228. #endif
  9229. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9230. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9231. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9232. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9233. // Store the saved target
  9234. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9235. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9236. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9237. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9238. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9239. #ifdef LIN_ADVANCE
  9240. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9241. #endif
  9242. // Finaly store the "power outage" flag.
  9243. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9244. // Increment power failure counter
  9245. eeprom_increment_byte((uint8_t*)EEPROM_POWER_COUNT);
  9246. eeprom_increment_word((uint16_t*)EEPROM_POWER_COUNT_TOT);
  9247. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9248. WRITE(BEEPER,HIGH);
  9249. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9250. poweron_z();
  9251. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9252. plan_buffer_line_curposXYZE(500);
  9253. st_synchronize();
  9254. wdt_enable(WDTO_1S);
  9255. while(1);
  9256. }
  9257. void uvlo_tiny()
  9258. {
  9259. unsigned long time_start = _millis();
  9260. // Conserve power as soon as possible.
  9261. disable_x();
  9262. disable_y();
  9263. disable_e0();
  9264. #ifdef TMC2130
  9265. tmc2130_set_current_h(Z_AXIS, 20);
  9266. tmc2130_set_current_r(Z_AXIS, 20);
  9267. #endif //TMC2130
  9268. // Stop all heaters
  9269. setAllTargetHotends(0);
  9270. setTargetBed(0);
  9271. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9272. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9273. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9274. // Disable MBL (if not already) to work with physical coordinates.
  9275. mbl.active = false;
  9276. planner_abort_hard();
  9277. // Allow for small roundoffs to be ignored
  9278. 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])
  9279. {
  9280. // Clean the input command queue, inhibit serial processing using saved_printing
  9281. cmdqueue_reset();
  9282. card.sdprinting = false;
  9283. saved_printing = true;
  9284. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9285. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9286. planner_aborted = false;
  9287. sei();
  9288. // The axis was moved: adjust Z as done on a regular UVLO.
  9289. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9290. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9291. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9292. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9293. + UVLO_TINY_Z_AXIS_SHIFT;
  9294. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9295. st_synchronize();
  9296. poweroff_z();
  9297. // Update Z position
  9298. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9299. // Update the _final_ Z motor microstep counter (unused).
  9300. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9301. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9302. }
  9303. // Update the the "power outage" flag.
  9304. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9305. // Increment power failure counter
  9306. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9307. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9308. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9309. uvlo_drain_reset();
  9310. }
  9311. #endif //UVLO_SUPPORT
  9312. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9313. void setup_fan_interrupt() {
  9314. //INT7
  9315. DDRE &= ~(1 << 7); //input pin
  9316. PORTE &= ~(1 << 7); //no internal pull-up
  9317. //start with sensing rising edge
  9318. EICRB &= ~(1 << 6);
  9319. EICRB |= (1 << 7);
  9320. //enable INT7 interrupt
  9321. EIMSK |= (1 << 7);
  9322. }
  9323. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9324. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9325. ISR(INT7_vect) {
  9326. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9327. #ifdef FAN_SOFT_PWM
  9328. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9329. #else //FAN_SOFT_PWM
  9330. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9331. #endif //FAN_SOFT_PWM
  9332. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9333. t_fan_rising_edge = millis_nc();
  9334. }
  9335. else { //interrupt was triggered by falling edge
  9336. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9337. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9338. }
  9339. }
  9340. EICRB ^= (1 << 6); //change edge
  9341. }
  9342. #endif
  9343. #ifdef UVLO_SUPPORT
  9344. void setup_uvlo_interrupt() {
  9345. DDRE &= ~(1 << 4); //input pin
  9346. PORTE &= ~(1 << 4); //no internal pull-up
  9347. // sensing falling edge
  9348. EICRB |= (1 << 0);
  9349. EICRB &= ~(1 << 1);
  9350. // enable INT4 interrupt
  9351. EIMSK |= (1 << 4);
  9352. // check if power was lost before we armed the interrupt
  9353. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9354. {
  9355. SERIAL_ECHOLNPGM("INT4");
  9356. uvlo_drain_reset();
  9357. }
  9358. }
  9359. ISR(INT4_vect) {
  9360. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9361. SERIAL_ECHOLNPGM("INT4");
  9362. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9363. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9364. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9365. }
  9366. void recover_print(uint8_t automatic) {
  9367. char cmd[30];
  9368. lcd_update_enable(true);
  9369. lcd_update(2);
  9370. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9371. // Recover position, temperatures and extrude_multipliers
  9372. bool mbl_was_active = recover_machine_state_after_power_panic();
  9373. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9374. // and second also so one may remove the excess priming material.
  9375. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9376. {
  9377. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9378. enquecommand(cmd);
  9379. }
  9380. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9381. // transformation status. G28 will not touch Z when MBL is off.
  9382. enquecommand_P(PSTR("G28 X Y"));
  9383. // Set the target bed and nozzle temperatures and wait.
  9384. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9385. enquecommand(cmd);
  9386. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9387. enquecommand(cmd);
  9388. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9389. enquecommand(cmd);
  9390. enquecommand_P(PSTR("M83")); //E axis relative mode
  9391. // If not automatically recoreverd (long power loss)
  9392. if(automatic == 0){
  9393. //Extrude some filament to stabilize the pressure
  9394. enquecommand_P(PSTR("G1 E5 F120"));
  9395. // Retract to be consistent with a short pause
  9396. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9397. enquecommand(cmd);
  9398. }
  9399. 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]);
  9400. // Restart the print.
  9401. restore_print_from_eeprom(mbl_was_active);
  9402. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9403. }
  9404. bool recover_machine_state_after_power_panic()
  9405. {
  9406. // 1) Preset some dummy values for the XY axes
  9407. current_position[X_AXIS] = 0;
  9408. current_position[Y_AXIS] = 0;
  9409. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9410. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9411. bool mbl_was_active = false;
  9412. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9413. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9414. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9415. // Scale the z value to 10u resolution.
  9416. int16_t v;
  9417. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9418. if (v != 0)
  9419. mbl_was_active = true;
  9420. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9421. }
  9422. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9423. // The current position after power panic is moved to the next closest 0th full step.
  9424. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9425. // Recover last E axis position
  9426. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9427. // 3) Initialize the logical to physical coordinate system transformation.
  9428. world2machine_initialize();
  9429. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9430. // print_mesh_bed_leveling_table();
  9431. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9432. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9433. babystep_load();
  9434. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9435. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9436. clamp_to_software_endstops(current_position);
  9437. set_destination_to_current();
  9438. plan_set_position_curposXYZE();
  9439. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9440. print_world_coordinates();
  9441. // 6) Power up the Z motors, mark their positions as known.
  9442. axis_known_position[Z_AXIS] = true;
  9443. enable_z();
  9444. // 7) Recover the target temperatures.
  9445. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9446. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9447. // 8) Recover extruder multipilers
  9448. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9449. #if EXTRUDERS > 1
  9450. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9451. #if EXTRUDERS > 2
  9452. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9453. #endif
  9454. #endif
  9455. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9456. // 9) Recover the saved target
  9457. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9458. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9459. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9460. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9461. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9462. #ifdef LIN_ADVANCE
  9463. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9464. #endif
  9465. return mbl_was_active;
  9466. }
  9467. void restore_print_from_eeprom(bool mbl_was_active) {
  9468. int feedrate_rec;
  9469. int feedmultiply_rec;
  9470. uint8_t fan_speed_rec;
  9471. char cmd[48];
  9472. char filename[FILENAME_LENGTH];
  9473. uint8_t depth = 0;
  9474. char dir_name[9];
  9475. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9476. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9477. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9478. SERIAL_ECHOPGM("Feedrate:");
  9479. MYSERIAL.print(feedrate_rec);
  9480. SERIAL_ECHOPGM(", feedmultiply:");
  9481. MYSERIAL.println(feedmultiply_rec);
  9482. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9483. MYSERIAL.println(int(depth));
  9484. for (uint8_t i = 0; i < depth; i++) {
  9485. for (uint8_t j = 0; j < 8; j++) {
  9486. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9487. }
  9488. dir_name[8] = '\0';
  9489. MYSERIAL.println(dir_name);
  9490. // strcpy(card.dir_names[i], dir_name);
  9491. card.chdir(dir_name, false);
  9492. }
  9493. for (uint8_t i = 0; i < 8; i++) {
  9494. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9495. }
  9496. filename[8] = '\0';
  9497. MYSERIAL.print(filename);
  9498. strcat_P(filename, PSTR(".gco"));
  9499. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9500. enquecommand(cmd);
  9501. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9502. SERIAL_ECHOPGM("Position read from eeprom:");
  9503. MYSERIAL.println(position);
  9504. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9505. // without shifting Z along the way. This requires performing the move without mbl.
  9506. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9507. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9508. if (pos_x != X_COORD_INVALID)
  9509. {
  9510. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9511. enquecommand(cmd);
  9512. }
  9513. // Enable MBL and switch to logical positioning
  9514. if (mbl_was_active)
  9515. enquecommand_P(PSTR("PRUSA MBL V1"));
  9516. // Move the Z axis down to the print, in logical coordinates.
  9517. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9518. enquecommand(cmd);
  9519. // Restore acceleration settings
  9520. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9521. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9522. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9523. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9524. enquecommand(cmd);
  9525. // Unretract.
  9526. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9527. enquecommand(cmd);
  9528. // Recover final E axis position and mode
  9529. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9530. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9531. enquecommand(cmd);
  9532. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9533. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9534. // Set the feedrates saved at the power panic.
  9535. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9536. enquecommand(cmd);
  9537. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9538. enquecommand(cmd);
  9539. // Set the fan speed saved at the power panic.
  9540. sprintf_P(cmd, PSTR("M106 S%u"), fan_speed_rec);
  9541. enquecommand(cmd);
  9542. // Set a position in the file.
  9543. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9544. enquecommand(cmd);
  9545. enquecommand_P(PSTR("G4 S0"));
  9546. enquecommand_P(PSTR("PRUSA uvlo"));
  9547. }
  9548. #endif //UVLO_SUPPORT
  9549. //! @brief Immediately stop print moves
  9550. //!
  9551. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9552. //! If printing from sd card, position in file is saved.
  9553. //! If printing from USB, line number is saved.
  9554. //!
  9555. //! @param z_move
  9556. //! @param e_move
  9557. void stop_and_save_print_to_ram(float z_move, float e_move)
  9558. {
  9559. if (saved_printing) return;
  9560. #if 0
  9561. unsigned char nplanner_blocks;
  9562. #endif
  9563. unsigned char nlines;
  9564. uint16_t sdlen_planner;
  9565. uint16_t sdlen_cmdqueue;
  9566. cli();
  9567. if (card.sdprinting) {
  9568. #if 0
  9569. nplanner_blocks = number_of_blocks();
  9570. #endif
  9571. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9572. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9573. saved_sdpos -= sdlen_planner;
  9574. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9575. saved_sdpos -= sdlen_cmdqueue;
  9576. saved_printing_type = PRINTING_TYPE_SD;
  9577. }
  9578. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9579. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9580. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9581. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9582. saved_sdpos -= nlines;
  9583. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9584. saved_printing_type = PRINTING_TYPE_USB;
  9585. }
  9586. else {
  9587. saved_printing_type = PRINTING_TYPE_NONE;
  9588. //not sd printing nor usb printing
  9589. }
  9590. #if 0
  9591. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9592. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9593. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9594. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9595. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9596. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9597. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9598. {
  9599. card.setIndex(saved_sdpos);
  9600. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9601. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9602. MYSERIAL.print(char(card.get()));
  9603. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9604. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9605. MYSERIAL.print(char(card.get()));
  9606. SERIAL_ECHOLNPGM("End of command buffer");
  9607. }
  9608. {
  9609. // Print the content of the planner buffer, line by line:
  9610. card.setIndex(saved_sdpos);
  9611. int8_t iline = 0;
  9612. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9613. SERIAL_ECHOPGM("Planner line (from file): ");
  9614. MYSERIAL.print(int(iline), DEC);
  9615. SERIAL_ECHOPGM(", length: ");
  9616. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9617. SERIAL_ECHOPGM(", steps: (");
  9618. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9619. SERIAL_ECHOPGM(",");
  9620. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9621. SERIAL_ECHOPGM(",");
  9622. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9623. SERIAL_ECHOPGM(",");
  9624. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9625. SERIAL_ECHOPGM("), events: ");
  9626. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9627. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9628. MYSERIAL.print(char(card.get()));
  9629. }
  9630. }
  9631. {
  9632. // Print the content of the command buffer, line by line:
  9633. int8_t iline = 0;
  9634. union {
  9635. struct {
  9636. char lo;
  9637. char hi;
  9638. } lohi;
  9639. uint16_t value;
  9640. } sdlen_single;
  9641. int _bufindr = bufindr;
  9642. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9643. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9644. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9645. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9646. }
  9647. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9648. MYSERIAL.print(int(iline), DEC);
  9649. SERIAL_ECHOPGM(", type: ");
  9650. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9651. SERIAL_ECHOPGM(", len: ");
  9652. MYSERIAL.println(sdlen_single.value, DEC);
  9653. // Print the content of the buffer line.
  9654. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9655. SERIAL_ECHOPGM("Buffer line (from file): ");
  9656. MYSERIAL.println(int(iline), DEC);
  9657. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9658. MYSERIAL.print(char(card.get()));
  9659. if (-- _buflen == 0)
  9660. break;
  9661. // First skip the current command ID and iterate up to the end of the string.
  9662. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9663. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9664. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9665. // If the end of the buffer was empty,
  9666. if (_bufindr == sizeof(cmdbuffer)) {
  9667. // skip to the start and find the nonzero command.
  9668. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9669. }
  9670. }
  9671. }
  9672. #endif
  9673. // save the global state at planning time
  9674. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9675. if (current_block && !pos_invalid)
  9676. {
  9677. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9678. saved_feedrate2 = current_block->gcode_feedrate;
  9679. saved_segment_idx = current_block->segment_idx;
  9680. // 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);
  9681. }
  9682. else
  9683. {
  9684. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9685. saved_feedrate2 = feedrate;
  9686. saved_segment_idx = 0;
  9687. }
  9688. planner_abort_hard(); //abort printing
  9689. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9690. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9691. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9692. saved_extruder_temperature = degTargetHotend(active_extruder);
  9693. saved_bed_temperature = degTargetBed();
  9694. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9695. saved_fan_speed = fanSpeed;
  9696. cmdqueue_reset(); //empty cmdqueue
  9697. card.sdprinting = false;
  9698. // card.closefile();
  9699. saved_printing = true;
  9700. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9701. st_reset_timer();
  9702. sei();
  9703. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9704. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9705. // the caller can continue processing. This is used during powerpanic to save the state as we
  9706. // move away from the print.
  9707. char buf[48];
  9708. if(e_move)
  9709. {
  9710. // First unretract (relative extrusion)
  9711. if(!saved_extruder_relative_mode){
  9712. enquecommand(PSTR("M83"), true);
  9713. }
  9714. //retract 45mm/s
  9715. // A single sprintf may not be faster, but is definitely 20B shorter
  9716. // than a sequence of commands building the string piece by piece
  9717. // A snprintf would have been a safer call, but since it is not used
  9718. // in the whole program, its implementation would bring more bytes to the total size
  9719. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9720. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9721. enquecommand(buf, false);
  9722. }
  9723. if(z_move)
  9724. {
  9725. // Then lift Z axis
  9726. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9727. enquecommand(buf, false);
  9728. }
  9729. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9730. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9731. repeatcommand_front();
  9732. }
  9733. }
  9734. void restore_extruder_temperature_from_ram() {
  9735. if (degTargetHotend(active_extruder) != saved_extruder_temperature)
  9736. {
  9737. setTargetHotendSafe(saved_extruder_temperature, active_extruder);
  9738. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9739. wait_for_heater(_millis(), active_extruder);
  9740. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9741. }
  9742. }
  9743. //! @brief Restore print from ram
  9744. //!
  9745. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9746. //! print fan speed, waits for extruder temperature restore, then restores
  9747. //! position and continues print moves.
  9748. //!
  9749. //! Internally lcd_update() is called by wait_for_heater().
  9750. //!
  9751. //! @param e_move
  9752. void restore_print_from_ram_and_continue(float e_move)
  9753. {
  9754. if (!saved_printing) return;
  9755. #ifdef FANCHECK
  9756. // Do not allow resume printing if fans are still not ok
  9757. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9758. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9759. #endif
  9760. // Make sure fan is turned off
  9761. fanSpeed = 0;
  9762. // restore bed temperature (bed can be disabled during a thermal warning)
  9763. if (degBed() != saved_bed_temperature)
  9764. setTargetBed(saved_bed_temperature);
  9765. restore_extruder_temperature_from_ram();
  9766. // Restore saved fan speed
  9767. fanSpeed = saved_fan_speed;
  9768. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9769. float e = saved_pos[E_AXIS] - e_move;
  9770. plan_set_e_position(e);
  9771. #ifdef FANCHECK
  9772. fans_check_enabled = false;
  9773. #endif
  9774. // do not restore XY for commands that do not require that
  9775. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9776. {
  9777. saved_pos[X_AXIS] = current_position[X_AXIS];
  9778. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9779. }
  9780. //first move print head in XY to the saved position:
  9781. 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);
  9782. //then move Z
  9783. 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);
  9784. //and finaly unretract (35mm/s)
  9785. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9786. st_synchronize();
  9787. #ifdef FANCHECK
  9788. fans_check_enabled = true;
  9789. #endif
  9790. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9791. feedrate = saved_feedrate2;
  9792. feedmultiply = saved_feedmultiply2;
  9793. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9794. set_destination_to_current();
  9795. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9796. card.setIndex(saved_sdpos);
  9797. sdpos_atomic = saved_sdpos;
  9798. card.sdprinting = true;
  9799. }
  9800. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9801. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9802. serial_count = 0;
  9803. FlushSerialRequestResend();
  9804. }
  9805. else {
  9806. //not sd printing nor usb printing
  9807. }
  9808. lcd_setstatuspgm(MSG_WELCOME);
  9809. saved_printing_type = PRINTING_TYPE_NONE;
  9810. saved_printing = false;
  9811. planner_aborted = true; // unroll the stack
  9812. }
  9813. // Cancel the state related to a currently saved print
  9814. void cancel_saved_printing()
  9815. {
  9816. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9817. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9818. saved_printing_type = PRINTING_TYPE_NONE;
  9819. saved_printing = false;
  9820. }
  9821. void print_world_coordinates()
  9822. {
  9823. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9824. }
  9825. void print_physical_coordinates()
  9826. {
  9827. 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));
  9828. }
  9829. void print_mesh_bed_leveling_table()
  9830. {
  9831. SERIAL_ECHOPGM("mesh bed leveling: ");
  9832. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9833. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9834. MYSERIAL.print(mbl.z_values[y][x], 3);
  9835. SERIAL_ECHO(' ');
  9836. }
  9837. SERIAL_ECHOLN();
  9838. }
  9839. uint8_t calc_percent_done()
  9840. {
  9841. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9842. uint8_t percent_done = 0;
  9843. #ifdef TMC2130
  9844. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9845. {
  9846. percent_done = print_percent_done_normal;
  9847. }
  9848. else if (print_percent_done_silent <= 100)
  9849. {
  9850. percent_done = print_percent_done_silent;
  9851. }
  9852. #else
  9853. if (print_percent_done_normal <= 100)
  9854. {
  9855. percent_done = print_percent_done_normal;
  9856. }
  9857. #endif //TMC2130
  9858. else
  9859. {
  9860. percent_done = card.percentDone();
  9861. }
  9862. return percent_done;
  9863. }
  9864. static void print_time_remaining_init()
  9865. {
  9866. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9867. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9868. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9869. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9870. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9871. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9872. }
  9873. void load_filament_final_feed()
  9874. {
  9875. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9876. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9877. }
  9878. //! @brief Wait for user to check the state
  9879. //! @par nozzle_temp nozzle temperature to load filament
  9880. void M600_check_state(float nozzle_temp)
  9881. {
  9882. uint8_t lcd_change_filament_state = 0;
  9883. while (lcd_change_filament_state != 1)
  9884. {
  9885. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9886. lcd_change_filament_state = lcd_alright();
  9887. KEEPALIVE_STATE(IN_HANDLER);
  9888. switch(lcd_change_filament_state)
  9889. {
  9890. // Filament failed to load so load it again
  9891. case 2:
  9892. if (MMU2::mmu2.Enabled()){
  9893. // Unload filament
  9894. mmu_M600_unload_filament();
  9895. // Ask to remove any old filament and load new
  9896. mmu_M600_wait_and_beep();
  9897. // After user clicks knob, MMU will load the filament
  9898. mmu_M600_load_filament(false, nozzle_temp);
  9899. } else {
  9900. M600_load_filament_movements();
  9901. }
  9902. break;
  9903. // Filament loaded properly but color is not clear
  9904. case 3:
  9905. st_synchronize();
  9906. load_filament_final_feed();
  9907. lcd_loading_color();
  9908. st_synchronize();
  9909. break;
  9910. // Everything good
  9911. default:
  9912. lcd_change_success();
  9913. break;
  9914. }
  9915. }
  9916. }
  9917. //! @brief Wait for user action
  9918. //!
  9919. //! Beep, manage nozzle heater and wait for user to start unload filament
  9920. //! If times out, active extruder temperature is set to 0.
  9921. //!
  9922. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9923. void M600_wait_for_user(float HotendTempBckp) {
  9924. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9925. int counterBeep = 0;
  9926. unsigned long waiting_start_time = _millis();
  9927. uint8_t wait_for_user_state = 0;
  9928. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9929. bool bFirst=true;
  9930. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9931. manage_heater();
  9932. manage_inactivity(true);
  9933. #if BEEPER > 0
  9934. if (counterBeep == 500) {
  9935. counterBeep = 0;
  9936. }
  9937. SET_OUTPUT(BEEPER);
  9938. if (counterBeep == 0) {
  9939. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9940. {
  9941. bFirst=false;
  9942. WRITE(BEEPER, HIGH);
  9943. }
  9944. }
  9945. if (counterBeep == 20) {
  9946. WRITE(BEEPER, LOW);
  9947. }
  9948. counterBeep++;
  9949. #endif //BEEPER > 0
  9950. switch (wait_for_user_state) {
  9951. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9952. delay_keep_alive(4);
  9953. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9954. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9955. wait_for_user_state = 1;
  9956. setAllTargetHotends(0);
  9957. st_synchronize();
  9958. disable_e0();
  9959. disable_e1();
  9960. disable_e2();
  9961. }
  9962. break;
  9963. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9964. delay_keep_alive(4);
  9965. if (lcd_clicked()) {
  9966. setTargetHotend(HotendTempBckp, active_extruder);
  9967. lcd_wait_for_heater();
  9968. wait_for_user_state = 2;
  9969. }
  9970. break;
  9971. case 2: //waiting for nozzle to reach target temperature
  9972. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9973. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9974. waiting_start_time = _millis();
  9975. wait_for_user_state = 0;
  9976. }
  9977. else {
  9978. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9979. lcd_set_cursor(1, 4);
  9980. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  9981. }
  9982. break;
  9983. }
  9984. }
  9985. WRITE(BEEPER, LOW);
  9986. }
  9987. void M600_load_filament_movements()
  9988. {
  9989. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  9990. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  9991. load_filament_final_feed();
  9992. lcd_loading_filament();
  9993. st_synchronize();
  9994. }
  9995. void M600_load_filament() {
  9996. //load filament for single material and MMU
  9997. lcd_wait_interact();
  9998. //load_filament_time = _millis();
  9999. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10000. while(!lcd_clicked())
  10001. {
  10002. manage_heater();
  10003. manage_inactivity(true);
  10004. #ifdef FILAMENT_SENSOR
  10005. if (fsensor.getFilamentLoadEvent()) {
  10006. Sound_MakeCustom(50,1000,false);
  10007. break;
  10008. }
  10009. #endif //FILAMENT_SENSOR
  10010. }
  10011. KEEPALIVE_STATE(IN_HANDLER);
  10012. M600_load_filament_movements();
  10013. Sound_MakeCustom(50,1000,false);
  10014. lcd_update_enable(false);
  10015. }
  10016. //! @brief Wait for click
  10017. //!
  10018. //! Set
  10019. void marlin_wait_for_click()
  10020. {
  10021. int8_t busy_state_backup = busy_state;
  10022. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10023. lcd_consume_click();
  10024. while(!lcd_clicked())
  10025. {
  10026. manage_heater();
  10027. manage_inactivity(true);
  10028. lcd_update(0);
  10029. }
  10030. KEEPALIVE_STATE(busy_state_backup);
  10031. }
  10032. #ifdef PSU_Delta
  10033. bool bEnableForce_z;
  10034. void init_force_z()
  10035. {
  10036. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10037. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10038. disable_force_z();
  10039. }
  10040. void check_force_z()
  10041. {
  10042. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10043. init_force_z(); // causes enforced switching into disable-state
  10044. }
  10045. void disable_force_z()
  10046. {
  10047. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10048. bEnableForce_z=false;
  10049. // switching to silent mode
  10050. #ifdef TMC2130
  10051. tmc2130_mode=TMC2130_MODE_SILENT;
  10052. update_mode_profile();
  10053. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10054. #endif // TMC2130
  10055. }
  10056. void enable_force_z()
  10057. {
  10058. if(bEnableForce_z)
  10059. return; // motor already enabled (may be ;-p )
  10060. bEnableForce_z=true;
  10061. // mode recovering
  10062. #ifdef TMC2130
  10063. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10064. update_mode_profile();
  10065. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10066. #endif // TMC2130
  10067. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10068. }
  10069. #endif // PSU_Delta