Marlin_main.cpp 386 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519
  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 "conv2str.h"
  63. #include "backlight.h"
  64. #include "planner.h"
  65. #include "stepper.h"
  66. #include "temperature.h"
  67. #include "fancheck.h"
  68. #include "motion_control.h"
  69. #include "cardreader.h"
  70. #include "ConfigurationStore.h"
  71. #include "language.h"
  72. #include "pins_arduino.h"
  73. #include "math.h"
  74. #include "util.h"
  75. #include "Timer.h"
  76. #include "Prusa_farm.h"
  77. #include <avr/wdt.h>
  78. #include <avr/pgmspace.h>
  79. #include "Tcodes.h"
  80. #include "Dcodes.h"
  81. #include "AutoDeplete.h"
  82. #ifndef LA_NOCOMPAT
  83. #include "la10compat.h"
  84. #endif
  85. #include "spi.h"
  86. #include "Filament_sensor.h"
  87. #ifdef TMC2130
  88. #include "tmc2130.h"
  89. #endif //TMC2130
  90. #ifdef XFLASH
  91. #include "xflash.h"
  92. #include "optiboot_xflash.h"
  93. #endif //XFLASH
  94. #include "xflash_dump.h"
  95. #ifdef BLINKM
  96. #include "BlinkM.h"
  97. #include "Wire.h"
  98. #endif
  99. #ifdef ULTRALCD
  100. #include "ultralcd.h"
  101. #endif
  102. #if NUM_SERVOS > 0
  103. #include "Servo.h"
  104. #endif
  105. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  106. #include <SPI.h>
  107. #endif
  108. #include "mmu2.h"
  109. #define VERSION_STRING "1.0.2"
  110. #include "ultralcd.h"
  111. #include "sound.h"
  112. #include "cmdqueue.h"
  113. //Macro for print fan speed
  114. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  115. //filament types
  116. #define FILAMENT_DEFAULT 0
  117. #define FILAMENT_FLEX 1
  118. #define FILAMENT_PVA 2
  119. #define FILAMENT_UNDEFINED 255
  120. //Stepper Movement Variables
  121. //===========================================================================
  122. //=============================imported variables============================
  123. //===========================================================================
  124. //===========================================================================
  125. //=============================public variables=============================
  126. //===========================================================================
  127. #ifdef SDSUPPORT
  128. CardReader card;
  129. #endif
  130. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  131. //used for PINDA temp calibration and pause print
  132. #define DEFAULT_RETRACTION 1
  133. #define DEFAULT_RETRACTION_MM 4 //MM
  134. float default_retraction = DEFAULT_RETRACTION;
  135. float homing_feedrate[] = HOMING_FEEDRATE;
  136. //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
  137. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  138. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  139. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  140. uint8_t axis_relative_modes = 0;
  141. int feedmultiply=100; //100->1 200->2
  142. int extrudemultiply=100; //100->1 200->2
  143. int extruder_multiply[EXTRUDERS] = {100
  144. #if EXTRUDERS > 1
  145. , 100
  146. #if EXTRUDERS > 2
  147. , 100
  148. #endif
  149. #endif
  150. };
  151. bool homing_flag = false;
  152. int8_t lcd_change_fil_state = 0;
  153. unsigned long pause_time = 0;
  154. unsigned long start_pause_print = _millis();
  155. unsigned long t_fan_rising_edge = _millis();
  156. LongTimer safetyTimer;
  157. static LongTimer crashDetTimer;
  158. //unsigned long load_filament_time;
  159. bool mesh_bed_leveling_flag = false;
  160. unsigned long total_filament_used;
  161. HeatingStatus heating_status;
  162. uint8_t heating_status_counter;
  163. bool loading_flag = false;
  164. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  165. bool fan_state[2];
  166. int fan_edge_counter[2];
  167. int fan_speed[2];
  168. float extruder_multiplier[EXTRUDERS] = {1.0
  169. #if EXTRUDERS > 1
  170. , 1.0
  171. #if EXTRUDERS > 2
  172. , 1.0
  173. #endif
  174. #endif
  175. };
  176. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  177. //shortcuts for more readable code
  178. #define _x current_position[X_AXIS]
  179. #define _y current_position[Y_AXIS]
  180. #define _z current_position[Z_AXIS]
  181. #define _e current_position[E_AXIS]
  182. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  183. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  184. bool axis_known_position[3] = {false, false, false};
  185. // Extruder offset
  186. #if EXTRUDERS > 1
  187. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  188. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  189. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  190. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  191. #endif
  192. };
  193. #endif
  194. uint8_t active_extruder = 0;
  195. int fanSpeed=0;
  196. uint8_t newFanSpeed = 0;
  197. #ifdef FWRETRACT
  198. bool retracted[EXTRUDERS]={false
  199. #if EXTRUDERS > 1
  200. , false
  201. #if EXTRUDERS > 2
  202. , false
  203. #endif
  204. #endif
  205. };
  206. bool retracted_swap[EXTRUDERS]={false
  207. #if EXTRUDERS > 1
  208. , false
  209. #if EXTRUDERS > 2
  210. , false
  211. #endif
  212. #endif
  213. };
  214. float retract_length_swap = RETRACT_LENGTH_SWAP;
  215. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  216. #endif
  217. #ifdef PS_DEFAULT_OFF
  218. bool powersupply = false;
  219. #else
  220. bool powersupply = true;
  221. #endif
  222. bool cancel_heatup = false;
  223. int8_t busy_state = NOT_BUSY;
  224. static long prev_busy_signal_ms = -1;
  225. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  226. const char errormagic[] PROGMEM = "Error:";
  227. const char echomagic[] PROGMEM = "echo:";
  228. const char G28W0[] PROGMEM = "G28 W0";
  229. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  230. // that they can be used later for various logical checks
  231. #define X_COORD_INVALID (X_MIN_POS-1)
  232. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  233. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  234. uint16_t saved_segment_idx = 0;
  235. // storing estimated time to end of print counted by slicer
  236. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  237. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  238. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  239. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  240. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  241. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  242. uint32_t IP_address = 0;
  243. //===========================================================================
  244. //=============================Private Variables=============================
  245. //===========================================================================
  246. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  247. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  248. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  249. // For tracing an arc
  250. static float offset[3] = {0.0, 0.0, 0.0};
  251. // Current feedrate
  252. float feedrate = 1500.0;
  253. // Feedrate for the next move
  254. static float next_feedrate;
  255. // Original feedrate saved during homing moves
  256. static float saved_feedrate;
  257. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  258. //static float tt = 0;
  259. //static float bt = 0;
  260. //Inactivity shutdown variables
  261. static LongTimer previous_millis_cmd;
  262. unsigned long max_inactive_time = 0;
  263. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  264. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  265. unsigned long starttime=0;
  266. unsigned long stoptime=0;
  267. ShortTimer usb_timer;
  268. bool Stopped=false;
  269. #if NUM_SERVOS > 0
  270. Servo servos[NUM_SERVOS];
  271. #endif
  272. bool target_direction;
  273. //Insert variables if CHDK is defined
  274. #ifdef CHDK
  275. unsigned long chdkHigh = 0;
  276. bool chdkActive = false;
  277. #endif
  278. //! @name RAM save/restore printing
  279. //! @{
  280. bool saved_printing = false; //!< Print is paused and saved in RAM
  281. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  282. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  283. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  284. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  285. static int saved_feedmultiply2 = 0;
  286. static uint8_t saved_active_extruder = 0;
  287. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  288. float saved_bed_temperature = 0.0; //!< Bed temperature
  289. static bool saved_extruder_relative_mode = false;
  290. int saved_fan_speed = 0; //!< Print fan speed
  291. //! @}
  292. static int saved_feedmultiply_mm = 100;
  293. class AutoReportFeatures {
  294. union {
  295. struct {
  296. uint8_t temp : 1; //Temperature flag
  297. uint8_t fans : 1; //Fans flag
  298. uint8_t pos: 1; //Position flag
  299. uint8_t ar4 : 1; //Unused
  300. uint8_t ar5 : 1; //Unused
  301. uint8_t ar6 : 1; //Unused
  302. uint8_t ar7 : 1; //Unused
  303. } __attribute__((packed)) bits;
  304. uint8_t byte;
  305. } arFunctionsActive;
  306. uint8_t auto_report_period;
  307. public:
  308. LongTimer auto_report_timer;
  309. AutoReportFeatures():auto_report_period(0){
  310. #if defined(AUTO_REPORT)
  311. arFunctionsActive.byte = 0xff;
  312. #else
  313. arFunctionsActive.byte = 0;
  314. #endif //AUTO_REPORT
  315. }
  316. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  317. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  318. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  319. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  320. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  321. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  322. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  323. /// sets the autoreporting timer's period
  324. /// setting it to zero stops the timer
  325. void SetPeriod(uint8_t p){
  326. auto_report_period = p;
  327. if (auto_report_period != 0){
  328. auto_report_timer.start();
  329. } else{
  330. auto_report_timer.stop();
  331. }
  332. }
  333. inline void TimerStart() { auto_report_timer.start(); }
  334. inline bool TimerRunning()const { return auto_report_timer.running(); }
  335. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  336. };
  337. AutoReportFeatures autoReportFeatures;
  338. //===========================================================================
  339. //=============================Routines======================================
  340. //===========================================================================
  341. static bool setTargetedHotend(int code, uint8_t &extruder);
  342. static void print_time_remaining_init();
  343. static void wait_for_heater(long codenum, uint8_t extruder);
  344. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  345. static void gcode_M105(uint8_t extruder);
  346. #ifndef PINDA_THERMISTOR
  347. static void temp_compensation_start();
  348. static void temp_compensation_apply();
  349. #endif
  350. #ifdef PRUSA_SN_SUPPORT
  351. static uint8_t get_PRUSA_SN(char* SN);
  352. #endif //PRUSA_SN_SUPPORT
  353. uint16_t gcode_in_progress = 0;
  354. uint16_t mcode_in_progress = 0;
  355. void serial_echopair_P(const char *s_P, float v)
  356. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  357. void serial_echopair_P(const char *s_P, double v)
  358. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  359. void serial_echopair_P(const char *s_P, unsigned long v)
  360. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  361. void serialprintPGM(const char *str) {
  362. while(uint8_t ch = pgm_read_byte(str)) {
  363. MYSERIAL.write((char)ch);
  364. ++str;
  365. }
  366. }
  367. void serialprintlnPGM(const char *str) {
  368. serialprintPGM(str);
  369. MYSERIAL.println();
  370. }
  371. #ifdef SDSUPPORT
  372. #include "SdFatUtil.h"
  373. int freeMemory() { return SdFatUtil::FreeRam(); }
  374. #else
  375. extern "C" {
  376. extern unsigned int __bss_end;
  377. extern unsigned int __heap_start;
  378. extern void *__brkval;
  379. int freeMemory() {
  380. int free_memory;
  381. if ((int)__brkval == 0)
  382. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  383. else
  384. free_memory = ((int)&free_memory) - ((int)__brkval);
  385. return free_memory;
  386. }
  387. }
  388. #endif //!SDSUPPORT
  389. void setup_killpin()
  390. {
  391. #if defined(KILL_PIN) && KILL_PIN > -1
  392. SET_INPUT(KILL_PIN);
  393. WRITE(KILL_PIN,HIGH);
  394. #endif
  395. }
  396. // Set home pin
  397. void setup_homepin(void)
  398. {
  399. #if defined(HOME_PIN) && HOME_PIN > -1
  400. SET_INPUT(HOME_PIN);
  401. WRITE(HOME_PIN,HIGH);
  402. #endif
  403. }
  404. void setup_photpin()
  405. {
  406. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  407. SET_OUTPUT(PHOTOGRAPH_PIN);
  408. WRITE(PHOTOGRAPH_PIN, LOW);
  409. #endif
  410. }
  411. void setup_powerhold()
  412. {
  413. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  414. SET_OUTPUT(SUICIDE_PIN);
  415. WRITE(SUICIDE_PIN, HIGH);
  416. #endif
  417. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  418. SET_OUTPUT(PS_ON_PIN);
  419. #if defined(PS_DEFAULT_OFF)
  420. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  421. #else
  422. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  423. #endif
  424. #endif
  425. }
  426. void suicide()
  427. {
  428. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  429. SET_OUTPUT(SUICIDE_PIN);
  430. WRITE(SUICIDE_PIN, LOW);
  431. #endif
  432. }
  433. void servo_init()
  434. {
  435. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  436. servos[0].attach(SERVO0_PIN);
  437. #endif
  438. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  439. servos[1].attach(SERVO1_PIN);
  440. #endif
  441. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  442. servos[2].attach(SERVO2_PIN);
  443. #endif
  444. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  445. servos[3].attach(SERVO3_PIN);
  446. #endif
  447. #if (NUM_SERVOS >= 5)
  448. #error "TODO: enter initalisation code for more servos"
  449. #endif
  450. }
  451. bool __attribute__((noinline)) printer_active() {
  452. return IS_SD_PRINTING
  453. || usb_timer.running()
  454. || isPrintPaused
  455. || (custom_message_type == CustomMsg::TempCal)
  456. || saved_printing
  457. || (lcd_commands_type == LcdCommands::Layer1Cal)
  458. || mmu_print_saved
  459. || homing_flag
  460. || mesh_bed_leveling_flag;
  461. }
  462. bool fans_check_enabled = true;
  463. #ifdef TMC2130
  464. void crashdet_stop_and_save_print()
  465. {
  466. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  467. }
  468. void crashdet_restore_print_and_continue()
  469. {
  470. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  471. // babystep_apply();
  472. }
  473. void crashdet_fmt_error(char* buf, uint8_t mask)
  474. {
  475. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  476. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  477. *buf++ = ' ';
  478. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  479. }
  480. void crashdet_detected(uint8_t mask)
  481. {
  482. st_synchronize();
  483. static uint8_t crashDet_counter = 0;
  484. static uint8_t crashDet_axes = 0;
  485. bool automatic_recovery_after_crash = true;
  486. char msg[LCD_WIDTH+1] = "";
  487. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  488. crashDet_counter = 0;
  489. }
  490. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  491. automatic_recovery_after_crash = false;
  492. }
  493. crashDetTimer.start();
  494. crashDet_axes |= mask;
  495. lcd_update_enable(true);
  496. lcd_clear();
  497. lcd_update(2);
  498. if (mask & X_AXIS_MASK)
  499. {
  500. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  501. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  502. }
  503. if (mask & Y_AXIS_MASK)
  504. {
  505. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  506. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  507. }
  508. lcd_update_enable(true);
  509. lcd_update(2);
  510. // prepare the status message with the _current_ axes status
  511. crashdet_fmt_error(msg, mask);
  512. lcd_setstatus(msg);
  513. gcode_G28(true, true, false); //home X and Y
  514. if (automatic_recovery_after_crash) {
  515. enquecommand_P(PSTR("CRASH_RECOVER"));
  516. }else{
  517. setTargetHotend(0, active_extruder);
  518. // notify the user of *all* the axes previously affected, not just the last one
  519. lcd_update_enable(false);
  520. lcd_clear();
  521. crashdet_fmt_error(msg, crashDet_axes);
  522. crashDet_axes = 0;
  523. lcd_print(msg);
  524. // ask whether to resume printing
  525. lcd_set_cursor(0, 1);
  526. lcd_puts_P(_T(MSG_RESUME_PRINT));
  527. lcd_putc('?');
  528. bool yesno = lcd_show_yes_no_and_wait(false);
  529. if (yesno == LCD_LEFT_BUTTON_CHOICE)
  530. {
  531. enquecommand_P(PSTR("CRASH_RECOVER"));
  532. }
  533. else // MIDDLE_BUTTON_CHOICE
  534. {
  535. enquecommand_P(PSTR("CRASH_CANCEL"));
  536. }
  537. }
  538. }
  539. void crashdet_recover()
  540. {
  541. crashdet_restore_print_and_continue();
  542. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  543. }
  544. void crashdet_cancel()
  545. {
  546. saved_printing = false;
  547. tmc2130_sg_stop_on_crash = true;
  548. if (saved_printing_type == PRINTING_TYPE_SD) {
  549. lcd_print_stop();
  550. }else if(saved_printing_type == PRINTING_TYPE_USB){
  551. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  552. cmdqueue_reset();
  553. }
  554. }
  555. #endif //TMC2130
  556. void failstats_reset_print()
  557. {
  558. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  559. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  560. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  561. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  562. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  563. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  564. }
  565. void softReset()
  566. {
  567. cli();
  568. wdt_enable(WDTO_15MS);
  569. while(1);
  570. }
  571. #ifdef MESH_BED_LEVELING
  572. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  573. #endif
  574. static void factory_reset_stats(){
  575. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  576. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  577. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  578. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  579. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  580. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  581. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  582. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  583. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  584. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  585. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  586. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  587. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  588. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  589. }
  590. // Factory reset function
  591. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  592. // Level input parameter sets depth of reset
  593. static void factory_reset(char level)
  594. {
  595. lcd_clear();
  596. Sound_MakeCustom(100,0,false);
  597. switch (level) {
  598. case 0: // Level 0: Language reset
  599. lang_reset();
  600. break;
  601. case 1: //Level 1: Reset statistics
  602. factory_reset_stats();
  603. lcd_menu_statistics();
  604. break;
  605. case 2: // Level 2: Prepare for shipping
  606. factory_reset_stats();
  607. // FALLTHRU
  608. case 3: // Level 3: Preparation after being serviced
  609. // Force language selection at the next boot up.
  610. lang_reset();
  611. // Force the "Follow calibration flow" message at the next boot up.
  612. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  613. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  614. farm_disable();
  615. #ifdef FILAMENT_SENSOR
  616. fsensor.setEnabled(true);
  617. fsensor.setAutoLoadEnabled(true, true);
  618. fsensor.setRunoutEnabled(true, true);
  619. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  620. fsensor.setJamDetectionEnabled(true, true);
  621. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  622. #endif //FILAMENT_SENSOR
  623. break;
  624. case 4:
  625. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  626. // Erase EEPROM
  627. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  628. eeprom_update_byte((uint8_t*)i, 0xFF);
  629. menu_progressbar_update(i);
  630. }
  631. menu_progressbar_finish();
  632. softReset();
  633. break;
  634. default:
  635. break;
  636. }
  637. }
  638. extern "C" {
  639. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  640. }
  641. int uart_putchar(char c, FILE *)
  642. {
  643. MYSERIAL.write(c);
  644. return 0;
  645. }
  646. void lcd_splash()
  647. {
  648. lcd_clear(); // clears display and homes screen
  649. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  650. }
  651. void factory_reset()
  652. {
  653. KEEPALIVE_STATE(PAUSED_FOR_USER);
  654. if (!READ(BTN_ENC))
  655. {
  656. _delay_ms(1000);
  657. if (!READ(BTN_ENC))
  658. {
  659. lcd_clear();
  660. lcd_puts_P(PSTR("Factory RESET"));
  661. SET_OUTPUT(BEEPER);
  662. if(eSoundMode!=e_SOUND_MODE_SILENT)
  663. WRITE(BEEPER, HIGH);
  664. while (!READ(BTN_ENC));
  665. WRITE(BEEPER, LOW);
  666. _delay_ms(2000);
  667. char level = reset_menu();
  668. factory_reset(level);
  669. switch (level) {
  670. case 0:
  671. case 1:
  672. case 2:
  673. case 3:
  674. case 4: _delay_ms(0); break;
  675. }
  676. }
  677. }
  678. KEEPALIVE_STATE(IN_HANDLER);
  679. }
  680. void show_fw_version_warnings() {
  681. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  682. switch (FW_DEV_VERSION) {
  683. case(FW_VERSION_ALPHA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware alpha version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_ALPHA c=20 r=8
  684. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware beta version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_BETA c=20 r=8
  685. case(FW_VERSION_DEVEL):
  686. case(FW_VERSION_DEBUG):
  687. lcd_update_enable(false);
  688. lcd_clear();
  689. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  690. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  691. #else
  692. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  693. #endif
  694. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  695. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  696. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  697. lcd_wait_for_click();
  698. break;
  699. // 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
  700. }
  701. lcd_update_enable(true);
  702. }
  703. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  704. //! @brief try to check if firmware is on right type of printer
  705. static void check_if_fw_is_on_right_printer() {
  706. if (fsensor.probeOtherType()) {
  707. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  708. }
  709. }
  710. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  711. uint8_t check_printer_version()
  712. {
  713. uint8_t version_changed = 0;
  714. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  715. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  716. if (printer_type != PRINTER_TYPE) {
  717. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  718. else version_changed |= 0b10;
  719. }
  720. if (motherboard != MOTHERBOARD) {
  721. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  722. else version_changed |= 0b01;
  723. }
  724. return version_changed;
  725. }
  726. #ifdef BOOTAPP
  727. #include "bootapp.h" //bootloader support
  728. #endif //BOOTAPP
  729. #if (LANG_MODE != 0) //secondary language support
  730. #ifdef XFLASH
  731. // language update from external flash
  732. #define LANGBOOT_BLOCKSIZE 0x1000u
  733. #define LANGBOOT_RAMBUFFER 0x0800
  734. void update_sec_lang_from_external_flash()
  735. {
  736. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  737. {
  738. uint8_t lang = boot_reserved >> 3;
  739. uint8_t state = boot_reserved & 0x07;
  740. lang_table_header_t header;
  741. uint32_t src_addr;
  742. if (lang_get_header(lang, &header, &src_addr))
  743. {
  744. lcd_puts_at_P(1,3,PSTR("Language update."));
  745. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  746. _delay(100);
  747. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  748. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  749. {
  750. cli();
  751. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  752. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  753. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  754. if (state == 0)
  755. {
  756. //TODO - check header integrity
  757. }
  758. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  759. }
  760. else
  761. {
  762. //TODO - check sec lang data integrity
  763. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  764. }
  765. }
  766. }
  767. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  768. }
  769. #ifdef DEBUG_XFLASH
  770. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  771. {
  772. lang_table_header_t header;
  773. uint8_t count = 0;
  774. uint32_t addr = 0x00000;
  775. while (1)
  776. {
  777. printf_P(_n("LANGTABLE%d:"), count);
  778. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  779. if (header.magic != LANG_MAGIC)
  780. {
  781. puts_P(_n("NG!"));
  782. break;
  783. }
  784. puts_P(_n("OK"));
  785. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  786. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  787. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  788. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  789. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  790. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  791. addr += header.size;
  792. codes[count] = header.code;
  793. count ++;
  794. }
  795. return count;
  796. }
  797. void list_sec_lang_from_external_flash()
  798. {
  799. uint16_t codes[8];
  800. uint8_t count = lang_xflash_enum_codes(codes);
  801. printf_P(_n("XFlash lang count = %hhd\n"), count);
  802. }
  803. #endif //DEBUG_XFLASH
  804. #endif //XFLASH
  805. #endif //(LANG_MODE != 0)
  806. static void fw_crash_init()
  807. {
  808. #ifdef XFLASH_DUMP
  809. dump_crash_reason crash_reason;
  810. if(xfdump_check_state(&crash_reason))
  811. {
  812. // always signal to the host that a dump is available for retrieval
  813. puts_P(_N("// action:dump_available"));
  814. #ifdef EMERGENCY_DUMP
  815. if(crash_reason != dump_crash_reason::manual &&
  816. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  817. {
  818. lcd_show_fullscreen_message_and_wait_P(
  819. _n("FW crash detected! "
  820. "You can continue printing. "
  821. "Debug data available for analysis. "
  822. "Contact support to submit details."));
  823. }
  824. #endif
  825. }
  826. #else //XFLASH_DUMP
  827. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  828. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  829. {
  830. lcd_beeper_quick_feedback();
  831. lcd_clear();
  832. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  833. switch(crash_reason)
  834. {
  835. case dump_crash_reason::stack_error:
  836. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  837. break;
  838. case dump_crash_reason::watchdog:
  839. lcd_puts_P(_n("Watchdog timeout"));
  840. break;
  841. case dump_crash_reason::bad_isr:
  842. lcd_puts_P(_n("Bad interrupt"));
  843. break;
  844. default:
  845. lcd_print((uint8_t)crash_reason);
  846. break;
  847. }
  848. lcd_wait_for_click();
  849. }
  850. #endif //XFLASH_DUMP
  851. // prevent crash prompts to reappear once acknowledged
  852. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  853. }
  854. static void xflash_err_msg()
  855. {
  856. puts_P(_n("XFLASH not responding."));
  857. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  858. }
  859. // "Setup" function is called by the Arduino framework on startup.
  860. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  861. // are initialized by the main() routine provided by the Arduino framework.
  862. void setup()
  863. {
  864. timer2_init(); // enables functional millis
  865. MMU2::mmu2.Start();
  866. ultralcd_init();
  867. spi_init();
  868. lcd_splash();
  869. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  870. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  871. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  872. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  873. MYSERIAL.begin(BAUDRATE);
  874. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  875. stdout = uartout;
  876. #ifdef XFLASH
  877. bool xflash_success = xflash_init();
  878. uint8_t optiboot_status = 1;
  879. if (xflash_success)
  880. {
  881. optiboot_status = optiboot_xflash_enter();
  882. #if (LANG_MODE != 0) //secondary language support
  883. update_sec_lang_from_external_flash();
  884. #endif //(LANG_MODE != 0)
  885. }
  886. #else
  887. const bool xflash_success = true;
  888. #endif //XFLASH
  889. setup_killpin();
  890. setup_powerhold();
  891. farm_mode_init();
  892. #ifdef TMC2130
  893. if( FarmOrUserECool() ){
  894. //increased extruder current (PFW363)
  895. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  896. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  897. }
  898. #endif //TMC2130
  899. #ifdef PRUSA_SN_SUPPORT
  900. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  901. //SN is valid only if it is NULL terminated and starts with "CZPX".
  902. {
  903. char SN[20];
  904. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  905. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  906. {
  907. if (!get_PRUSA_SN(SN))
  908. {
  909. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  910. puts_P(PSTR("SN updated"));
  911. }
  912. else
  913. puts_P(PSTR("SN update failed"));
  914. }
  915. }
  916. #endif //PRUSA_SN_SUPPORT
  917. #ifndef XFLASH
  918. SERIAL_PROTOCOLLNPGM("start");
  919. #else
  920. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  921. SERIAL_PROTOCOLLNPGM("start");
  922. #endif
  923. SERIAL_ECHO_START;
  924. puts_P(PSTR(" " FW_VERSION_FULL));
  925. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  926. #ifdef DEBUG_SEC_LANG
  927. lang_table_header_t header;
  928. uint32_t src_addr = 0x00000;
  929. if (lang_get_header(1, &header, &src_addr))
  930. {
  931. printf_P(
  932. _n(
  933. " _src_addr = 0x%08lx\n"
  934. " _lt_magic = 0x%08lx %S\n"
  935. " _lt_size = 0x%04x (%d)\n"
  936. " _lt_count = 0x%04x (%d)\n"
  937. " _lt_chsum = 0x%04x\n"
  938. " _lt_code = 0x%04x (%c%c)\n"
  939. " _lt_resv1 = 0x%08lx\n"
  940. ),
  941. src_addr,
  942. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  943. header.size, header.size,
  944. header.count, header.count,
  945. header.checksum,
  946. header.code, header.code >> 8, header.code & 0xff,
  947. header.signature
  948. );
  949. #if 0
  950. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  951. for (uint16_t i = 0; i < 1024; i++)
  952. {
  953. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  954. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  955. if ((i % 16) == 15) putchar('\n');
  956. }
  957. #endif
  958. uint16_t sum = 0;
  959. for (uint16_t i = 0; i < header.size; i++)
  960. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  961. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  962. sum -= header.checksum; //subtract checksum
  963. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  964. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  965. if (sum == header.checksum)
  966. puts_P(_n("Checksum OK"));
  967. else
  968. puts_P(_n("Checksum NG"));
  969. }
  970. else
  971. puts_P(_n("lang_get_header failed!"));
  972. #if 0
  973. for (uint16_t i = 0; i < 1024*10; i++)
  974. {
  975. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  976. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  977. if ((i % 16) == 15) putchar('\n');
  978. }
  979. #endif
  980. #if 0
  981. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  982. for (int i = 0; i < 4096; ++i) {
  983. int b = eeprom_read_byte((unsigned char*)i);
  984. if (b != 255) {
  985. SERIAL_ECHO(i);
  986. SERIAL_ECHO(":");
  987. SERIAL_ECHO(b);
  988. SERIAL_ECHOLN("");
  989. }
  990. }
  991. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  992. #endif
  993. #endif //DEBUG_SEC_LANG
  994. // Check startup - does nothing if bootloader sets MCUSR to 0
  995. byte mcu = MCUSR;
  996. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  997. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  998. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  999. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1000. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1001. if (mcu & 1) puts_P(MSG_POWERUP);
  1002. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1003. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1004. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1005. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1006. MCUSR = 0;
  1007. //SERIAL_ECHORPGM(MSG_MARLIN);
  1008. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1009. #ifdef STRING_VERSION_CONFIG_H
  1010. #ifdef STRING_CONFIG_H_AUTHOR
  1011. SERIAL_ECHO_START;
  1012. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1013. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1014. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1015. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1016. SERIAL_ECHOPGM("Compiled: ");
  1017. SERIAL_ECHOLNPGM(__DATE__);
  1018. #endif
  1019. #endif
  1020. SERIAL_ECHO_START;
  1021. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1022. SERIAL_ECHO(freeMemory());
  1023. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1024. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1025. //lcd_update_enable(false); // why do we need this?? - andre
  1026. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1027. bool previous_settings_retrieved = false;
  1028. uint8_t hw_changed = check_printer_version();
  1029. 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
  1030. previous_settings_retrieved = Config_RetrieveSettings();
  1031. }
  1032. else { //printer version was changed so use default settings
  1033. Config_ResetDefault();
  1034. }
  1035. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1036. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1037. // performed inside the soft_pwm_isr)
  1038. SdFatUtil::set_stack_guard();
  1039. // Initialize pwm/temperature loops
  1040. soft_pwm_init();
  1041. temp_mgr_init();
  1042. #ifdef EXTRUDER_ALTFAN_DETECT
  1043. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1044. if (extruder_altfan_detect())
  1045. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1046. else
  1047. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1048. #endif //EXTRUDER_ALTFAN_DETECT
  1049. plan_init(); // Initialize planner;
  1050. factory_reset();
  1051. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1052. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1053. {
  1054. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1055. // where all the EEPROM entries are set to 0x0ff.
  1056. // Once a firmware boots up, it forces at least a language selection, which changes
  1057. // EEPROM_LANG to number lower than 0x0ff.
  1058. // 1) Set a high power mode.
  1059. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1060. #ifdef TMC2130
  1061. tmc2130_mode = TMC2130_MODE_NORMAL;
  1062. #endif //TMC2130
  1063. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1064. }
  1065. lcd_encoder_diff=0;
  1066. #ifdef TMC2130
  1067. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1068. if (silentMode == 0xff) silentMode = 0;
  1069. tmc2130_mode = TMC2130_MODE_NORMAL;
  1070. if (lcd_crash_detect_enabled() && !farm_mode)
  1071. {
  1072. lcd_crash_detect_enable();
  1073. puts_P(_N("CrashDetect ENABLED!"));
  1074. }
  1075. else
  1076. {
  1077. lcd_crash_detect_disable();
  1078. puts_P(_N("CrashDetect DISABLED"));
  1079. }
  1080. #ifdef TMC2130_LINEARITY_CORRECTION
  1081. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1082. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1083. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1084. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1085. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1086. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1087. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1088. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1089. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1090. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1091. #endif //TMC2130_LINEARITY_CORRECTION
  1092. #ifdef TMC2130_VARIABLE_RESOLUTION
  1093. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1094. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1095. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1096. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1097. #else //TMC2130_VARIABLE_RESOLUTION
  1098. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1099. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1100. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1101. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1102. #endif //TMC2130_VARIABLE_RESOLUTION
  1103. #endif //TMC2130
  1104. st_init(); // Initialize stepper, this enables interrupts!
  1105. #ifdef TMC2130
  1106. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1107. update_mode_profile();
  1108. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1109. #endif //TMC2130
  1110. #ifdef PSU_Delta
  1111. init_force_z(); // ! important for correct Z-axis initialization
  1112. #endif // PSU_Delta
  1113. setup_photpin();
  1114. #if 0
  1115. servo_init();
  1116. #endif
  1117. // Reset the machine correction matrix.
  1118. // It does not make sense to load the correction matrix until the machine is homed.
  1119. world2machine_reset();
  1120. // Initialize current_position accounting for software endstops to
  1121. // avoid unexpected initial shifts on the first move
  1122. clamp_to_software_endstops(current_position);
  1123. plan_set_position_curposXYZE();
  1124. // Show the xflash error message now that serial, lcd and encoder are available
  1125. if (!xflash_success)
  1126. xflash_err_msg();
  1127. #ifdef FILAMENT_SENSOR
  1128. fsensor.init();
  1129. #endif //FILAMENT_SENSOR
  1130. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1131. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1132. #endif
  1133. setup_homepin();
  1134. #if defined(Z_AXIS_ALWAYS_ON)
  1135. enable_z();
  1136. #endif
  1137. // The farm monitoring SW may accidentally expect
  1138. // 2 messages of "printer started" to consider a printer working.
  1139. prusa_statistics(8);
  1140. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1141. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1142. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1143. // but this times out if a blocking dialog is shown in setup().
  1144. card.initsd();
  1145. #ifdef DEBUG_SD_SPEED_TEST
  1146. if (card.cardOK)
  1147. {
  1148. uint8_t* buff = (uint8_t*)block_buffer;
  1149. uint32_t block = 0;
  1150. uint32_t sumr = 0;
  1151. uint32_t sumw = 0;
  1152. for (int i = 0; i < 1024; i++)
  1153. {
  1154. uint32_t u = _micros();
  1155. bool res = card.card.readBlock(i, buff);
  1156. u = _micros() - u;
  1157. if (res)
  1158. {
  1159. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1160. sumr += u;
  1161. u = _micros();
  1162. res = card.card.writeBlock(i, buff);
  1163. u = _micros() - u;
  1164. if (res)
  1165. {
  1166. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1167. sumw += u;
  1168. }
  1169. else
  1170. {
  1171. printf_P(PSTR("writeBlock %4d error\n"), i);
  1172. break;
  1173. }
  1174. }
  1175. else
  1176. {
  1177. printf_P(PSTR("readBlock %4d error\n"), i);
  1178. break;
  1179. }
  1180. }
  1181. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1182. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1183. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1184. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1185. }
  1186. else
  1187. printf_P(PSTR("Card NG!\n"));
  1188. #endif //DEBUG_SD_SPEED_TEST
  1189. eeprom_init();
  1190. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1191. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1192. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1193. #if (LANG_MODE != 0) //secondary language support
  1194. #ifdef DEBUG_XFLASH
  1195. XFLASH_SPI_ENTER();
  1196. uint8_t uid[8]; // 64bit unique id
  1197. xflash_rd_uid(uid);
  1198. puts_P(_n("XFLASH UID="));
  1199. for (uint8_t i = 0; i < 8; i ++)
  1200. printf_P(PSTR("%02x"), uid[i]);
  1201. putchar('\n');
  1202. list_sec_lang_from_external_flash();
  1203. #endif //DEBUG_XFLASH
  1204. // lang_reset();
  1205. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1206. lcd_language();
  1207. #ifdef DEBUG_SEC_LANG
  1208. uint16_t sec_lang_code = lang_get_code(1);
  1209. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1210. 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);
  1211. lang_print_sec_lang(uartout);
  1212. #endif //DEBUG_SEC_LANG
  1213. #endif //(LANG_MODE != 0)
  1214. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1215. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1216. }
  1217. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1218. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1219. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1220. int16_t z_shift = 0;
  1221. for (uint8_t i = 0; i < 5; i++) {
  1222. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1223. }
  1224. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1225. }
  1226. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1227. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1228. }
  1229. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1230. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1231. }
  1232. //mbl_mode_init();
  1233. mbl_settings_init();
  1234. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1235. if (SilentModeMenu_MMU == 255) {
  1236. SilentModeMenu_MMU = 1;
  1237. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1238. }
  1239. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1240. setup_fan_interrupt();
  1241. #endif //DEBUG_DISABLE_FANCHECK
  1242. #ifndef DEBUG_DISABLE_STARTMSGS
  1243. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1244. if (!farm_mode) {
  1245. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1246. check_if_fw_is_on_right_printer();
  1247. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1248. show_fw_version_warnings();
  1249. }
  1250. switch (hw_changed) {
  1251. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1252. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1253. case(0b01):
  1254. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1255. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1256. break;
  1257. case(0b10):
  1258. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1259. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1260. break;
  1261. case(0b11):
  1262. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1263. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1264. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1265. break;
  1266. default: break; //no change, show no message
  1267. }
  1268. if (!previous_settings_retrieved) {
  1269. 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
  1270. Config_StoreSettings();
  1271. }
  1272. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1273. lcd_wizard(WizState::Run);
  1274. }
  1275. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1276. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1277. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1278. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1279. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1280. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1281. // Show the message.
  1282. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1283. }
  1284. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1285. // Show the message.
  1286. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1287. lcd_update_enable(true);
  1288. }
  1289. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1290. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1291. lcd_update_enable(true);
  1292. }
  1293. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1294. // Show the message.
  1295. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1296. }
  1297. }
  1298. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1299. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1300. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1301. update_current_firmware_version_to_eeprom();
  1302. lcd_selftest();
  1303. }
  1304. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1305. KEEPALIVE_STATE(IN_PROCESS);
  1306. #endif //DEBUG_DISABLE_STARTMSGS
  1307. lcd_update_enable(true);
  1308. lcd_clear();
  1309. lcd_update(2);
  1310. // Store the currently running firmware into an eeprom,
  1311. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1312. update_current_firmware_version_to_eeprom();
  1313. #ifdef TMC2130
  1314. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1315. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1316. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1317. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1318. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1319. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1320. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1321. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1322. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1323. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1324. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1325. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1326. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1327. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1328. #endif //TMC2130
  1329. // report crash failures
  1330. fw_crash_init();
  1331. #ifdef UVLO_SUPPORT
  1332. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1333. /*
  1334. if (!lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1335. else {
  1336. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1337. lcd_update_enable(true);
  1338. lcd_update(2);
  1339. lcd_setstatuspgm(MSG_WELCOME);
  1340. }
  1341. */
  1342. manage_heater(); // Update temperatures
  1343. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1344. 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));
  1345. #endif
  1346. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1347. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1348. puts_P(_N("Automatic recovery!"));
  1349. #endif
  1350. recover_print(1);
  1351. }
  1352. else{
  1353. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1354. puts_P(_N("Normal recovery!"));
  1355. #endif
  1356. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) == LCD_LEFT_BUTTON_CHOICE) {
  1357. recover_print(0);
  1358. } else {
  1359. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1360. lcd_update_enable(true);
  1361. lcd_update(2);
  1362. lcd_setstatuspgm(MSG_WELCOME);
  1363. }
  1364. }
  1365. }
  1366. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1367. // the entire state machine initialized.
  1368. setup_uvlo_interrupt();
  1369. #endif //UVLO_SUPPORT
  1370. fCheckModeInit();
  1371. KEEPALIVE_STATE(NOT_BUSY);
  1372. #ifdef WATCHDOG
  1373. wdt_enable(WDTO_4S);
  1374. #ifdef EMERGENCY_HANDLERS
  1375. WDTCSR |= (1 << WDIE);
  1376. #endif //EMERGENCY_HANDLERS
  1377. #endif //WATCHDOG
  1378. }
  1379. static inline void crash_and_burn(dump_crash_reason reason)
  1380. {
  1381. WRITE(BEEPER, HIGH);
  1382. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1383. #ifdef EMERGENCY_DUMP
  1384. xfdump_full_dump_and_reset(reason);
  1385. #elif defined(EMERGENCY_SERIAL_DUMP)
  1386. if(emergency_serial_dump)
  1387. serial_dump_and_reset(reason);
  1388. #endif
  1389. softReset();
  1390. }
  1391. #ifdef EMERGENCY_HANDLERS
  1392. #ifdef WATCHDOG
  1393. ISR(WDT_vect)
  1394. {
  1395. crash_and_burn(dump_crash_reason::watchdog);
  1396. }
  1397. #endif
  1398. ISR(BADISR_vect)
  1399. {
  1400. crash_and_burn(dump_crash_reason::bad_isr);
  1401. }
  1402. #endif //EMERGENCY_HANDLERS
  1403. void stack_error() {
  1404. crash_and_burn(dump_crash_reason::stack_error);
  1405. }
  1406. /**
  1407. * Output autoreport values according to features requested in M155
  1408. */
  1409. #if defined(AUTO_REPORT)
  1410. void host_autoreport()
  1411. {
  1412. if (autoReportFeatures.TimerExpired())
  1413. {
  1414. if(autoReportFeatures.Temp()){
  1415. gcode_M105(active_extruder);
  1416. }
  1417. if(autoReportFeatures.Pos()){
  1418. gcode_M114();
  1419. }
  1420. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1421. if(autoReportFeatures.Fans()){
  1422. gcode_M123();
  1423. }
  1424. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1425. autoReportFeatures.TimerStart();
  1426. }
  1427. }
  1428. #endif //AUTO_REPORT
  1429. /**
  1430. * Output a "busy" message at regular intervals
  1431. * while the machine is not accepting commands.
  1432. */
  1433. void host_keepalive() {
  1434. #ifndef HOST_KEEPALIVE_FEATURE
  1435. return;
  1436. #endif //HOST_KEEPALIVE_FEATURE
  1437. if (farm_mode) return;
  1438. long ms = _millis();
  1439. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1440. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1441. switch (busy_state) {
  1442. case IN_HANDLER:
  1443. case IN_PROCESS:
  1444. SERIAL_ECHO_START;
  1445. SERIAL_ECHOLNPGM("busy: processing");
  1446. break;
  1447. case PAUSED_FOR_USER:
  1448. SERIAL_ECHO_START;
  1449. SERIAL_ECHOLNPGM("busy: paused for user");
  1450. break;
  1451. case PAUSED_FOR_INPUT:
  1452. SERIAL_ECHO_START;
  1453. SERIAL_ECHOLNPGM("busy: paused for input");
  1454. break;
  1455. default:
  1456. break;
  1457. }
  1458. }
  1459. prev_busy_signal_ms = ms;
  1460. }
  1461. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1462. // Before loop(), the setup() function is called by the main() routine.
  1463. void loop()
  1464. {
  1465. // Reset a previously aborted command, we can now start processing motion again
  1466. planner_aborted = false;
  1467. if(Stopped) {
  1468. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1469. // Signal to the host that we're currently busy waiting for supervision.
  1470. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1471. } else {
  1472. // Printer is available for processing, reset state
  1473. KEEPALIVE_STATE(NOT_BUSY);
  1474. }
  1475. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1476. usb_timer.start();
  1477. }
  1478. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1479. ;
  1480. }
  1481. #ifdef PRUSA_M28
  1482. if (prusa_sd_card_upload)
  1483. {
  1484. //we read byte-by byte
  1485. serial_read_stream();
  1486. }
  1487. else
  1488. #endif
  1489. {
  1490. get_command();
  1491. #ifdef SDSUPPORT
  1492. card.checkautostart(false);
  1493. #endif
  1494. if(buflen)
  1495. {
  1496. cmdbuffer_front_already_processed = false;
  1497. #ifdef SDSUPPORT
  1498. if(card.saving)
  1499. {
  1500. // Saving a G-code file onto an SD-card is in progress.
  1501. // Saving starts with M28, saving until M29 is seen.
  1502. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1503. card.write_command(CMDBUFFER_CURRENT_STRING);
  1504. if(card.logging)
  1505. process_commands();
  1506. else
  1507. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1508. } else {
  1509. card.closefile();
  1510. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1511. }
  1512. } else {
  1513. process_commands();
  1514. }
  1515. #else
  1516. process_commands();
  1517. #endif //SDSUPPORT
  1518. if (! cmdbuffer_front_already_processed && buflen)
  1519. {
  1520. // ptr points to the start of the block currently being processed.
  1521. // The first character in the block is the block type.
  1522. char *ptr = cmdbuffer + bufindr;
  1523. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1524. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1525. union {
  1526. struct {
  1527. char lo;
  1528. char hi;
  1529. } lohi;
  1530. uint16_t value;
  1531. } sdlen;
  1532. sdlen.value = 0;
  1533. {
  1534. // This block locks the interrupts globally for 3.25 us,
  1535. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1536. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1537. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1538. cli();
  1539. // Reset the command to something, which will be ignored by the power panic routine,
  1540. // so this buffer length will not be counted twice.
  1541. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1542. // Extract the current buffer length.
  1543. sdlen.lohi.lo = *ptr ++;
  1544. sdlen.lohi.hi = *ptr;
  1545. // and pass it to the planner queue.
  1546. planner_add_sd_length(sdlen.value);
  1547. sei();
  1548. }
  1549. }
  1550. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1551. cli();
  1552. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1553. // and one for each command to previous block in the planner queue.
  1554. planner_add_sd_length(1);
  1555. sei();
  1556. }
  1557. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1558. // this block's SD card length will not be counted twice as its command type has been replaced
  1559. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1560. cmdqueue_pop_front();
  1561. }
  1562. host_keepalive();
  1563. }
  1564. }
  1565. //check heater every n milliseconds
  1566. manage_heater();
  1567. manage_inactivity(isPrintPaused);
  1568. checkHitEndstops();
  1569. lcd_update(0);
  1570. #ifdef TMC2130
  1571. tmc2130_check_overtemp();
  1572. if (tmc2130_sg_crash)
  1573. {
  1574. uint8_t crash = tmc2130_sg_crash;
  1575. tmc2130_sg_crash = 0;
  1576. // crashdet_stop_and_save_print();
  1577. switch (crash)
  1578. {
  1579. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1580. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1581. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1582. }
  1583. }
  1584. #endif //TMC2130
  1585. MMU2::mmu2.mmu_loop();
  1586. }
  1587. #define DEFINE_PGM_READ_ANY(type, reader) \
  1588. static inline type pgm_read_any(const type *p) \
  1589. { return pgm_read_##reader##_near(p); }
  1590. DEFINE_PGM_READ_ANY(float, float);
  1591. DEFINE_PGM_READ_ANY(signed char, byte);
  1592. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1593. static const PROGMEM type array##_P[3] = \
  1594. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1595. static inline type array(uint8_t axis) \
  1596. { return pgm_read_any(&array##_P[axis]); } \
  1597. type array##_ext(uint8_t axis) \
  1598. { return pgm_read_any(&array##_P[axis]); }
  1599. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1600. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1601. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1602. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1603. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1604. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1605. static void axis_is_at_home(uint8_t axis) {
  1606. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1607. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1608. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1609. }
  1610. //! @return original feedmultiply
  1611. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1612. saved_feedrate = feedrate;
  1613. int l_feedmultiply = feedmultiply;
  1614. feedmultiply = 100;
  1615. previous_millis_cmd.start();
  1616. enable_endstops(enable_endstops_now);
  1617. return l_feedmultiply;
  1618. }
  1619. //! @param original_feedmultiply feedmultiply to restore
  1620. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1621. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1622. enable_endstops(false);
  1623. #endif
  1624. feedrate = saved_feedrate;
  1625. feedmultiply = original_feedmultiply;
  1626. previous_millis_cmd.start();
  1627. }
  1628. #ifdef ENABLE_AUTO_BED_LEVELING
  1629. #ifdef AUTO_BED_LEVELING_GRID
  1630. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1631. {
  1632. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1633. planeNormal.debug("planeNormal");
  1634. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1635. //bedLevel.debug("bedLevel");
  1636. //plan_bed_level_matrix.debug("bed level before");
  1637. //vector_3 uncorrected_position = plan_get_position_mm();
  1638. //uncorrected_position.debug("position before");
  1639. vector_3 corrected_position = plan_get_position();
  1640. // corrected_position.debug("position after");
  1641. current_position[X_AXIS] = corrected_position.x;
  1642. current_position[Y_AXIS] = corrected_position.y;
  1643. current_position[Z_AXIS] = corrected_position.z;
  1644. // put the bed at 0 so we don't go below it.
  1645. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1646. plan_set_position_curposXYZE();
  1647. }
  1648. #else // not AUTO_BED_LEVELING_GRID
  1649. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1650. plan_bed_level_matrix.set_to_identity();
  1651. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1652. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1653. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1654. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1655. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1656. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1657. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1658. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1659. vector_3 corrected_position = plan_get_position();
  1660. current_position[X_AXIS] = corrected_position.x;
  1661. current_position[Y_AXIS] = corrected_position.y;
  1662. current_position[Z_AXIS] = corrected_position.z;
  1663. // put the bed at 0 so we don't go below it.
  1664. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1665. plan_set_position_curposXYZE();
  1666. }
  1667. #endif // AUTO_BED_LEVELING_GRID
  1668. static void run_z_probe() {
  1669. plan_bed_level_matrix.set_to_identity();
  1670. feedrate = homing_feedrate[Z_AXIS];
  1671. // move down until you find the bed
  1672. float zPosition = -10;
  1673. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1674. st_synchronize();
  1675. // we have to let the planner know where we are right now as it is not where we said to go.
  1676. zPosition = st_get_position_mm(Z_AXIS);
  1677. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1678. // move up the retract distance
  1679. zPosition += home_retract_mm(Z_AXIS);
  1680. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1681. st_synchronize();
  1682. // move back down slowly to find bed
  1683. feedrate = homing_feedrate[Z_AXIS]/4;
  1684. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1685. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1686. st_synchronize();
  1687. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1688. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1689. plan_set_position_curposXYZE();
  1690. }
  1691. static void do_blocking_move_to(float x, float y, float z) {
  1692. float oldFeedRate = feedrate;
  1693. feedrate = homing_feedrate[Z_AXIS];
  1694. current_position[Z_AXIS] = z;
  1695. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1696. st_synchronize();
  1697. feedrate = XY_TRAVEL_SPEED;
  1698. current_position[X_AXIS] = x;
  1699. current_position[Y_AXIS] = y;
  1700. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1701. st_synchronize();
  1702. feedrate = oldFeedRate;
  1703. }
  1704. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1705. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1706. }
  1707. /// Probe bed height at position (x,y), returns the measured z value
  1708. static float probe_pt(float x, float y, float z_before) {
  1709. // move to right place
  1710. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1711. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1712. run_z_probe();
  1713. float measured_z = current_position[Z_AXIS];
  1714. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1715. SERIAL_PROTOCOLPGM(" x: ");
  1716. SERIAL_PROTOCOL(x);
  1717. SERIAL_PROTOCOLPGM(" y: ");
  1718. SERIAL_PROTOCOL(y);
  1719. SERIAL_PROTOCOLPGM(" z: ");
  1720. SERIAL_PROTOCOL(measured_z);
  1721. SERIAL_PROTOCOLPGM("\n");
  1722. return measured_z;
  1723. }
  1724. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1725. #ifdef LIN_ADVANCE
  1726. /**
  1727. * M900: Set and/or Get advance K factor
  1728. *
  1729. * K<factor> Set advance K factor
  1730. */
  1731. inline void gcode_M900() {
  1732. float newK = code_seen('K') ? code_value_float() : -2;
  1733. #ifdef LA_NOCOMPAT
  1734. if (newK >= 0 && newK < LA_K_MAX)
  1735. extruder_advance_K = newK;
  1736. else
  1737. SERIAL_ECHOLNPGM("K out of allowed range!");
  1738. #else
  1739. if (newK == 0)
  1740. {
  1741. extruder_advance_K = 0;
  1742. la10c_reset();
  1743. }
  1744. else
  1745. {
  1746. newK = la10c_value(newK);
  1747. if (newK < 0)
  1748. SERIAL_ECHOLNPGM("K out of allowed range!");
  1749. else
  1750. extruder_advance_K = newK;
  1751. }
  1752. #endif
  1753. SERIAL_ECHO_START;
  1754. SERIAL_ECHOPGM("Advance K=");
  1755. SERIAL_ECHOLN(extruder_advance_K);
  1756. }
  1757. #endif // LIN_ADVANCE
  1758. bool check_commands() {
  1759. bool end_command_found = false;
  1760. while (buflen)
  1761. {
  1762. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1763. if (!cmdbuffer_front_already_processed)
  1764. cmdqueue_pop_front();
  1765. cmdbuffer_front_already_processed = false;
  1766. }
  1767. return end_command_found;
  1768. }
  1769. // raise_z_above: slowly raise Z to the requested height
  1770. //
  1771. // contrarily to a simple move, this function will carefully plan a move
  1772. // when the current Z position is unknown. In such cases, stallguard is
  1773. // enabled and will prevent prolonged pushing against the Z tops
  1774. void raise_z_above(float target, bool plan)
  1775. {
  1776. if (current_position[Z_AXIS] >= target)
  1777. return;
  1778. // Z needs raising
  1779. current_position[Z_AXIS] = target;
  1780. clamp_to_software_endstops(current_position);
  1781. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1782. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1783. #else
  1784. bool z_min_endstop = false;
  1785. #endif
  1786. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1787. {
  1788. // current position is known or very low, it's safe to raise Z
  1789. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1790. return;
  1791. }
  1792. // ensure Z is powered in normal mode to overcome initial load
  1793. enable_z();
  1794. st_synchronize();
  1795. // rely on crashguard to limit damage
  1796. bool z_endstop_enabled = enable_z_endstop(true);
  1797. #ifdef TMC2130
  1798. tmc2130_home_enter(Z_AXIS_MASK);
  1799. #endif //TMC2130
  1800. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1801. st_synchronize();
  1802. #ifdef TMC2130
  1803. if (endstop_z_hit_on_purpose())
  1804. {
  1805. // not necessarily exact, but will avoid further vertical moves
  1806. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1807. plan_set_position_curposXYZE();
  1808. }
  1809. tmc2130_home_exit();
  1810. #endif //TMC2130
  1811. enable_z_endstop(z_endstop_enabled);
  1812. }
  1813. #ifdef TMC2130
  1814. bool calibrate_z_auto()
  1815. {
  1816. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1817. lcd_clear();
  1818. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1819. bool endstops_enabled = enable_endstops(true);
  1820. int axis_up_dir = -home_dir(Z_AXIS);
  1821. tmc2130_home_enter(Z_AXIS_MASK);
  1822. current_position[Z_AXIS] = 0;
  1823. plan_set_position_curposXYZE();
  1824. set_destination_to_current();
  1825. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1826. feedrate = homing_feedrate[Z_AXIS];
  1827. plan_buffer_line_destinationXYZE(feedrate / 60);
  1828. st_synchronize();
  1829. // current_position[axis] = 0;
  1830. // plan_set_position_curposXYZE();
  1831. tmc2130_home_exit();
  1832. enable_endstops(false);
  1833. current_position[Z_AXIS] = 0;
  1834. plan_set_position_curposXYZE();
  1835. set_destination_to_current();
  1836. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1837. feedrate = homing_feedrate[Z_AXIS] / 2;
  1838. plan_buffer_line_destinationXYZE(feedrate / 60);
  1839. st_synchronize();
  1840. enable_endstops(endstops_enabled);
  1841. if (PRINTER_TYPE == PRINTER_MK3) {
  1842. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1843. }
  1844. else {
  1845. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1846. }
  1847. plan_set_position_curposXYZE();
  1848. return true;
  1849. }
  1850. #endif //TMC2130
  1851. #ifdef TMC2130
  1852. static void check_Z_crash(void)
  1853. {
  1854. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1855. FORCE_HIGH_POWER_END;
  1856. current_position[Z_AXIS] = 0;
  1857. plan_set_position_curposXYZE();
  1858. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1859. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1860. st_synchronize();
  1861. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1862. }
  1863. }
  1864. #endif //TMC2130
  1865. #ifdef TMC2130
  1866. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1867. #else
  1868. void homeaxis(uint8_t axis, uint8_t cnt)
  1869. #endif //TMC2130
  1870. {
  1871. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1872. #define HOMEAXIS_DO(LETTER) \
  1873. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1874. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1875. {
  1876. int axis_home_dir = home_dir(axis);
  1877. feedrate = homing_feedrate[axis];
  1878. #ifdef TMC2130
  1879. tmc2130_home_enter(X_AXIS_MASK << axis);
  1880. #endif //TMC2130
  1881. // Move away a bit, so that the print head does not touch the end position,
  1882. // and the following movement to endstop has a chance to achieve the required velocity
  1883. // for the stall guard to work.
  1884. current_position[axis] = 0;
  1885. plan_set_position_curposXYZE();
  1886. set_destination_to_current();
  1887. // destination[axis] = 11.f;
  1888. destination[axis] = -3.f * axis_home_dir;
  1889. plan_buffer_line_destinationXYZE(feedrate/60);
  1890. st_synchronize();
  1891. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1892. endstops_hit_on_purpose();
  1893. enable_endstops(false);
  1894. current_position[axis] = 0;
  1895. plan_set_position_curposXYZE();
  1896. destination[axis] = 1. * axis_home_dir;
  1897. plan_buffer_line_destinationXYZE(feedrate/60);
  1898. st_synchronize();
  1899. // Now continue to move up to the left end stop with the collision detection enabled.
  1900. enable_endstops(true);
  1901. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1902. plan_buffer_line_destinationXYZE(feedrate/60);
  1903. st_synchronize();
  1904. for (uint8_t i = 0; i < cnt; i++)
  1905. {
  1906. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1907. endstops_hit_on_purpose();
  1908. enable_endstops(false);
  1909. current_position[axis] = 0;
  1910. plan_set_position_curposXYZE();
  1911. destination[axis] = -10.f * axis_home_dir;
  1912. plan_buffer_line_destinationXYZE(feedrate/60);
  1913. st_synchronize();
  1914. endstops_hit_on_purpose();
  1915. // Now move left up to the collision, this time with a repeatable velocity.
  1916. enable_endstops(true);
  1917. destination[axis] = 11.f * axis_home_dir;
  1918. #ifdef TMC2130
  1919. feedrate = homing_feedrate[axis];
  1920. #else //TMC2130
  1921. feedrate = homing_feedrate[axis] / 2;
  1922. #endif //TMC2130
  1923. plan_buffer_line_destinationXYZE(feedrate/60);
  1924. st_synchronize();
  1925. #ifdef TMC2130
  1926. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1927. if (pstep) pstep[i] = mscnt >> 4;
  1928. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1929. #endif //TMC2130
  1930. }
  1931. endstops_hit_on_purpose();
  1932. enable_endstops(false);
  1933. #ifdef TMC2130
  1934. uint8_t orig = tmc2130_home_origin[axis];
  1935. uint8_t back = tmc2130_home_bsteps[axis];
  1936. if (tmc2130_home_enabled && (orig <= 63))
  1937. {
  1938. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1939. if (back > 0)
  1940. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1941. }
  1942. else
  1943. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1944. tmc2130_home_exit();
  1945. #endif //TMC2130
  1946. axis_is_at_home(axis);
  1947. axis_known_position[axis] = true;
  1948. // Move from minimum
  1949. #ifdef TMC2130
  1950. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1951. #else //TMC2130
  1952. float dist = - axis_home_dir * 0.01f * 64;
  1953. #endif //TMC2130
  1954. current_position[axis] -= dist;
  1955. plan_set_position_curposXYZE();
  1956. current_position[axis] += dist;
  1957. destination[axis] = current_position[axis];
  1958. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1959. st_synchronize();
  1960. feedrate = 0.0;
  1961. }
  1962. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1963. {
  1964. #ifdef TMC2130
  1965. FORCE_HIGH_POWER_START;
  1966. #endif
  1967. int axis_home_dir = home_dir(axis);
  1968. current_position[axis] = 0;
  1969. plan_set_position_curposXYZE();
  1970. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1971. feedrate = homing_feedrate[axis];
  1972. plan_buffer_line_destinationXYZE(feedrate/60);
  1973. st_synchronize();
  1974. #ifdef TMC2130
  1975. check_Z_crash();
  1976. #endif //TMC2130
  1977. current_position[axis] = 0;
  1978. plan_set_position_curposXYZE();
  1979. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1980. plan_buffer_line_destinationXYZE(feedrate/60);
  1981. st_synchronize();
  1982. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1983. feedrate = homing_feedrate[axis]/2 ;
  1984. plan_buffer_line_destinationXYZE(feedrate/60);
  1985. st_synchronize();
  1986. #ifdef TMC2130
  1987. check_Z_crash();
  1988. #endif //TMC2130
  1989. axis_is_at_home(axis);
  1990. destination[axis] = current_position[axis];
  1991. feedrate = 0.0;
  1992. endstops_hit_on_purpose();
  1993. axis_known_position[axis] = true;
  1994. #ifdef TMC2130
  1995. FORCE_HIGH_POWER_END;
  1996. #endif
  1997. }
  1998. enable_endstops(endstops_enabled);
  1999. }
  2000. /**/
  2001. void home_xy()
  2002. {
  2003. set_destination_to_current();
  2004. homeaxis(X_AXIS);
  2005. homeaxis(Y_AXIS);
  2006. plan_set_position_curposXYZE();
  2007. endstops_hit_on_purpose();
  2008. }
  2009. void refresh_cmd_timeout(void)
  2010. {
  2011. previous_millis_cmd.start();
  2012. }
  2013. #ifdef FWRETRACT
  2014. void retract(bool retracting, bool swapretract = false) {
  2015. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2016. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2017. // position, which requires a sync
  2018. if(retracting && !retracted[active_extruder]) {
  2019. st_synchronize();
  2020. set_destination_to_current();
  2021. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2022. plan_set_e_position(current_position[E_AXIS]);
  2023. float oldFeedrate = feedrate;
  2024. feedrate=cs.retract_feedrate*60;
  2025. retracted[active_extruder]=true;
  2026. prepare_move();
  2027. if(cs.retract_zlift) {
  2028. st_synchronize();
  2029. current_position[Z_AXIS]-=cs.retract_zlift;
  2030. plan_set_position_curposXYZE();
  2031. prepare_move();
  2032. }
  2033. feedrate = oldFeedrate;
  2034. } else if(!retracting && retracted[active_extruder]) {
  2035. st_synchronize();
  2036. set_destination_to_current();
  2037. float oldFeedrate = feedrate;
  2038. feedrate=cs.retract_recover_feedrate*60;
  2039. if(cs.retract_zlift) {
  2040. current_position[Z_AXIS]+=cs.retract_zlift;
  2041. plan_set_position_curposXYZE();
  2042. prepare_move();
  2043. st_synchronize();
  2044. }
  2045. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2046. plan_set_e_position(current_position[E_AXIS]);
  2047. retracted[active_extruder]=false;
  2048. prepare_move();
  2049. feedrate = oldFeedrate;
  2050. }
  2051. } //retract
  2052. #endif //FWRETRACT
  2053. #ifdef TMC2130
  2054. void force_high_power_mode(bool start_high_power_section) {
  2055. #ifdef PSU_Delta
  2056. if (start_high_power_section == true) enable_force_z();
  2057. #endif //PSU_Delta
  2058. uint8_t silent;
  2059. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2060. if (silent == 1) {
  2061. //we are in silent mode, set to normal mode to enable crash detection
  2062. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2063. st_synchronize();
  2064. cli();
  2065. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2066. update_mode_profile();
  2067. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2068. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2069. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2070. st_reset_timer();
  2071. sei();
  2072. }
  2073. }
  2074. #endif //TMC2130
  2075. void gcode_M105(uint8_t extruder)
  2076. {
  2077. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2078. SERIAL_PROTOCOLPGM("T:");
  2079. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2080. SERIAL_PROTOCOLPGM(" /");
  2081. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2082. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2083. SERIAL_PROTOCOLPGM(" B:");
  2084. SERIAL_PROTOCOL_F(degBed(),1);
  2085. SERIAL_PROTOCOLPGM(" /");
  2086. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2087. #endif //TEMP_BED_PIN
  2088. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2089. SERIAL_PROTOCOLPGM(" T");
  2090. SERIAL_PROTOCOL(cur_extruder);
  2091. SERIAL_PROTOCOL(':');
  2092. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2093. SERIAL_PROTOCOLPGM(" /");
  2094. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2095. }
  2096. #else
  2097. SERIAL_ERROR_START;
  2098. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2099. #endif
  2100. SERIAL_PROTOCOLPGM(" @:");
  2101. #ifdef EXTRUDER_WATTS
  2102. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2103. SERIAL_PROTOCOLPGM("W");
  2104. #else
  2105. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2106. #endif
  2107. SERIAL_PROTOCOLPGM(" B@:");
  2108. #ifdef BED_WATTS
  2109. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2110. SERIAL_PROTOCOLPGM("W");
  2111. #else
  2112. SERIAL_PROTOCOL(getHeaterPower(-1));
  2113. #endif
  2114. #ifdef PINDA_THERMISTOR
  2115. SERIAL_PROTOCOLPGM(" P:");
  2116. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2117. #endif //PINDA_THERMISTOR
  2118. #ifdef AMBIENT_THERMISTOR
  2119. SERIAL_PROTOCOLPGM(" A:");
  2120. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2121. #endif //AMBIENT_THERMISTOR
  2122. #ifdef SHOW_TEMP_ADC_VALUES
  2123. {
  2124. float raw = 0.0;
  2125. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2126. SERIAL_PROTOCOLPGM(" ADC B:");
  2127. SERIAL_PROTOCOL_F(degBed(),1);
  2128. SERIAL_PROTOCOLPGM("C->");
  2129. raw = rawBedTemp();
  2130. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2131. SERIAL_PROTOCOLPGM(" Rb->");
  2132. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2133. SERIAL_PROTOCOLPGM(" Rxb->");
  2134. SERIAL_PROTOCOL_F(raw, 5);
  2135. #endif
  2136. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2137. SERIAL_PROTOCOLPGM(" T");
  2138. SERIAL_PROTOCOL(cur_extruder);
  2139. SERIAL_PROTOCOLPGM(":");
  2140. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2141. SERIAL_PROTOCOLPGM("C->");
  2142. raw = rawHotendTemp(cur_extruder);
  2143. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2144. SERIAL_PROTOCOLPGM(" Rt");
  2145. SERIAL_PROTOCOL(cur_extruder);
  2146. SERIAL_PROTOCOLPGM("->");
  2147. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2148. SERIAL_PROTOCOLPGM(" Rx");
  2149. SERIAL_PROTOCOL(cur_extruder);
  2150. SERIAL_PROTOCOLPGM("->");
  2151. SERIAL_PROTOCOL_F(raw, 5);
  2152. }
  2153. }
  2154. #endif
  2155. SERIAL_PROTOCOLLN();
  2156. }
  2157. #ifdef TMC2130
  2158. 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)
  2159. #else
  2160. 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)
  2161. #endif //TMC2130
  2162. {
  2163. // Flag for the display update routine and to disable the print cancelation during homing.
  2164. st_synchronize();
  2165. homing_flag = true;
  2166. #if 0
  2167. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2168. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2169. #endif
  2170. // Which axes should be homed?
  2171. bool home_x = home_x_axis;
  2172. bool home_y = home_y_axis;
  2173. bool home_z = home_z_axis;
  2174. // Either all X,Y,Z codes are present, or none of them.
  2175. bool home_all_axes = home_x == home_y && home_x == home_z;
  2176. if (home_all_axes)
  2177. // No X/Y/Z code provided means to home all axes.
  2178. home_x = home_y = home_z = true;
  2179. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2180. if (home_all_axes) {
  2181. raise_z_above(MESH_HOME_Z_SEARCH);
  2182. st_synchronize();
  2183. }
  2184. #ifdef ENABLE_AUTO_BED_LEVELING
  2185. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2186. #endif //ENABLE_AUTO_BED_LEVELING
  2187. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2188. // the planner will not perform any adjustments in the XY plane.
  2189. // Wait for the motors to stop and update the current position with the absolute values.
  2190. world2machine_revert_to_uncorrected();
  2191. // For mesh bed leveling deactivate the matrix temporarily.
  2192. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2193. // in a single axis only.
  2194. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2195. #ifdef MESH_BED_LEVELING
  2196. uint8_t mbl_was_active = mbl.active;
  2197. mbl.active = 0;
  2198. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2199. #endif
  2200. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2201. if (home_z)
  2202. babystep_undo();
  2203. int l_feedmultiply = setup_for_endstop_move();
  2204. set_destination_to_current();
  2205. feedrate = 0.0;
  2206. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2207. if(home_z)
  2208. homeaxis(Z_AXIS);
  2209. #endif
  2210. #ifdef QUICK_HOME
  2211. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2212. if(home_x && home_y) //first diagonal move
  2213. {
  2214. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2215. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2216. plan_set_position_curposXYZE();
  2217. 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);
  2218. feedrate = homing_feedrate[X_AXIS];
  2219. if(homing_feedrate[Y_AXIS]<feedrate)
  2220. feedrate = homing_feedrate[Y_AXIS];
  2221. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2222. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2223. } else {
  2224. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2225. }
  2226. plan_buffer_line_destinationXYZE(feedrate/60);
  2227. st_synchronize();
  2228. axis_is_at_home(X_AXIS);
  2229. axis_is_at_home(Y_AXIS);
  2230. plan_set_position_curposXYZE();
  2231. destination[X_AXIS] = current_position[X_AXIS];
  2232. destination[Y_AXIS] = current_position[Y_AXIS];
  2233. plan_buffer_line_destinationXYZE(feedrate/60);
  2234. feedrate = 0.0;
  2235. st_synchronize();
  2236. endstops_hit_on_purpose();
  2237. current_position[X_AXIS] = destination[X_AXIS];
  2238. current_position[Y_AXIS] = destination[Y_AXIS];
  2239. current_position[Z_AXIS] = destination[Z_AXIS];
  2240. }
  2241. #endif /* QUICK_HOME */
  2242. #ifdef TMC2130
  2243. if(home_x)
  2244. {
  2245. if (!calib)
  2246. homeaxis(X_AXIS);
  2247. else
  2248. tmc2130_home_calibrate(X_AXIS);
  2249. }
  2250. if(home_y)
  2251. {
  2252. if (!calib)
  2253. homeaxis(Y_AXIS);
  2254. else
  2255. tmc2130_home_calibrate(Y_AXIS);
  2256. }
  2257. #else //TMC2130
  2258. if(home_x) homeaxis(X_AXIS);
  2259. if(home_y) homeaxis(Y_AXIS);
  2260. #endif //TMC2130
  2261. if(home_x_axis && home_x_value != 0)
  2262. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2263. if(home_y_axis && home_y_value != 0)
  2264. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2265. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2266. #ifndef Z_SAFE_HOMING
  2267. if(home_z) {
  2268. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2269. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2270. st_synchronize();
  2271. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2272. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2273. raise_z_above(MESH_HOME_Z_SEARCH);
  2274. st_synchronize();
  2275. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2276. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2277. // 1st mesh bed leveling measurement point, corrected.
  2278. world2machine_initialize();
  2279. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2280. world2machine_reset();
  2281. if (destination[Y_AXIS] < Y_MIN_POS)
  2282. destination[Y_AXIS] = Y_MIN_POS;
  2283. feedrate = homing_feedrate[X_AXIS] / 20;
  2284. enable_endstops(false);
  2285. #ifdef DEBUG_BUILD
  2286. SERIAL_ECHOLNPGM("plan_set_position()");
  2287. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2288. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2289. #endif
  2290. plan_set_position_curposXYZE();
  2291. #ifdef DEBUG_BUILD
  2292. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2293. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2294. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2295. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2296. #endif
  2297. plan_buffer_line_destinationXYZE(feedrate);
  2298. st_synchronize();
  2299. current_position[X_AXIS] = destination[X_AXIS];
  2300. current_position[Y_AXIS] = destination[Y_AXIS];
  2301. enable_endstops(true);
  2302. endstops_hit_on_purpose();
  2303. homeaxis(Z_AXIS);
  2304. #else // MESH_BED_LEVELING
  2305. homeaxis(Z_AXIS);
  2306. #endif // MESH_BED_LEVELING
  2307. }
  2308. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2309. if(home_all_axes) {
  2310. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2311. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2312. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2313. feedrate = XY_TRAVEL_SPEED/60;
  2314. current_position[Z_AXIS] = 0;
  2315. plan_set_position_curposXYZE();
  2316. plan_buffer_line_destinationXYZE(feedrate);
  2317. st_synchronize();
  2318. current_position[X_AXIS] = destination[X_AXIS];
  2319. current_position[Y_AXIS] = destination[Y_AXIS];
  2320. homeaxis(Z_AXIS);
  2321. }
  2322. // Let's see if X and Y are homed and probe is inside bed area.
  2323. if(home_z) {
  2324. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2325. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2326. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2327. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2328. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2329. current_position[Z_AXIS] = 0;
  2330. plan_set_position_curposXYZE();
  2331. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2332. feedrate = max_feedrate[Z_AXIS];
  2333. plan_buffer_line_destinationXYZE(feedrate);
  2334. st_synchronize();
  2335. homeaxis(Z_AXIS);
  2336. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2337. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2338. SERIAL_ECHO_START;
  2339. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2340. } else {
  2341. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2342. SERIAL_ECHO_START;
  2343. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2344. }
  2345. }
  2346. #endif // Z_SAFE_HOMING
  2347. #endif // Z_HOME_DIR < 0
  2348. if(home_z_axis && home_z_value != 0)
  2349. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2350. #ifdef ENABLE_AUTO_BED_LEVELING
  2351. if(home_z)
  2352. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2353. #endif
  2354. // Set the planner and stepper routine positions.
  2355. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2356. // contains the machine coordinates.
  2357. plan_set_position_curposXYZE();
  2358. clean_up_after_endstop_move(l_feedmultiply);
  2359. endstops_hit_on_purpose();
  2360. #ifndef MESH_BED_LEVELING
  2361. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2362. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2363. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2364. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2365. lcd_adjust_z();
  2366. #endif
  2367. // Load the machine correction matrix
  2368. world2machine_initialize();
  2369. // and correct the current_position XY axes to match the transformed coordinate system.
  2370. world2machine_update_current();
  2371. #ifdef MESH_BED_LEVELING
  2372. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2373. {
  2374. if (! home_z && mbl_was_active) {
  2375. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2376. mbl.active = true;
  2377. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2378. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2379. }
  2380. }
  2381. #endif
  2382. prusa_statistics(20);
  2383. st_synchronize();
  2384. homing_flag = false;
  2385. #if 0
  2386. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2387. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2388. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2389. #endif
  2390. }
  2391. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2392. {
  2393. #ifdef TMC2130
  2394. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2395. #else
  2396. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2397. #endif //TMC2130
  2398. }
  2399. // G80 - Automatic mesh bed leveling
  2400. static void gcode_G80()
  2401. {
  2402. st_synchronize();
  2403. if (planner_aborted)
  2404. return;
  2405. mesh_bed_leveling_flag = true;
  2406. #ifndef PINDA_THERMISTOR
  2407. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2408. #endif // ndef PINDA_THERMISTOR
  2409. #ifdef SUPPORT_VERBOSITY
  2410. int8_t verbosity_level = 0;
  2411. if (code_seen('V')) {
  2412. // Just 'V' without a number counts as V1.
  2413. char c = strchr_pointer[1];
  2414. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2415. }
  2416. #endif //SUPPORT_VERBOSITY
  2417. // Firstly check if we know where we are
  2418. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2419. // We don't know where we are! HOME!
  2420. // Push the commands to the front of the message queue in the reverse order!
  2421. // There shall be always enough space reserved for these commands.
  2422. repeatcommand_front(); // repeat G80 with all its parameters
  2423. enquecommand_front_P(G28W0);
  2424. return;
  2425. }
  2426. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2427. if (code_seen('N')) {
  2428. nMeasPoints = code_value_uint8();
  2429. if (nMeasPoints != 7) {
  2430. nMeasPoints = 3;
  2431. }
  2432. }
  2433. else {
  2434. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2435. }
  2436. uint8_t nProbeRetry = 3;
  2437. if (code_seen('R')) {
  2438. nProbeRetry = code_value_uint8();
  2439. if (nProbeRetry > 10) {
  2440. nProbeRetry = 10;
  2441. }
  2442. }
  2443. else {
  2444. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2445. }
  2446. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2447. #ifndef PINDA_THERMISTOR
  2448. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2449. {
  2450. temp_compensation_start();
  2451. run = true;
  2452. repeatcommand_front(); // repeat G80 with all its parameters
  2453. enquecommand_front_P(G28W0);
  2454. break;
  2455. }
  2456. run = false;
  2457. #endif //PINDA_THERMISTOR
  2458. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2459. CustomMsg custom_message_type_old = custom_message_type;
  2460. uint8_t custom_message_state_old = custom_message_state;
  2461. custom_message_type = CustomMsg::MeshBedLeveling;
  2462. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2463. lcd_update(1);
  2464. mbl.reset(); //reset mesh bed leveling
  2465. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2466. babystep_undo();
  2467. // Cycle through all points and probe them
  2468. // First move up. During this first movement, the babystepping will be reverted.
  2469. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2470. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2471. // The move to the first calibration point.
  2472. current_position[X_AXIS] = BED_X0;
  2473. current_position[Y_AXIS] = BED_Y0;
  2474. #ifdef SUPPORT_VERBOSITY
  2475. if (verbosity_level >= 1)
  2476. {
  2477. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2478. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2479. }
  2480. #else //SUPPORT_VERBOSITY
  2481. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2482. #endif //SUPPORT_VERBOSITY
  2483. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2484. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2485. // Wait until the move is finished.
  2486. st_synchronize();
  2487. if (planner_aborted)
  2488. {
  2489. custom_message_type = custom_message_type_old;
  2490. custom_message_state = custom_message_state_old;
  2491. return;
  2492. }
  2493. uint8_t mesh_point = 0; //index number of calibration point
  2494. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2495. 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)
  2496. #ifdef SUPPORT_VERBOSITY
  2497. if (verbosity_level >= 1) {
  2498. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2499. }
  2500. #endif // SUPPORT_VERBOSITY
  2501. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2502. while (mesh_point != nMeasPoints * nMeasPoints) {
  2503. // Get coords of a measuring point.
  2504. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2505. uint8_t iy = mesh_point / nMeasPoints;
  2506. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2507. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2508. custom_message_state--;
  2509. mesh_point++;
  2510. continue; //skip
  2511. }*/
  2512. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2513. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2514. {
  2515. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2516. }
  2517. float z0 = 0.f;
  2518. if (has_z && (mesh_point > 0)) {
  2519. uint16_t z_offset_u = 0;
  2520. if (nMeasPoints == 7) {
  2521. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2522. }
  2523. else {
  2524. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2525. }
  2526. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2527. #ifdef SUPPORT_VERBOSITY
  2528. if (verbosity_level >= 1) {
  2529. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2530. }
  2531. #endif // SUPPORT_VERBOSITY
  2532. }
  2533. // Move Z up to MESH_HOME_Z_SEARCH.
  2534. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2535. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2536. float init_z_bckp = current_position[Z_AXIS];
  2537. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2538. st_synchronize();
  2539. // Move to XY position of the sensor point.
  2540. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2541. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2542. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2543. #ifdef SUPPORT_VERBOSITY
  2544. if (verbosity_level >= 1) {
  2545. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2546. SERIAL_PROTOCOL(mesh_point);
  2547. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2548. }
  2549. #else //SUPPORT_VERBOSITY
  2550. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2551. #endif // SUPPORT_VERBOSITY
  2552. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2553. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2554. st_synchronize();
  2555. if (planner_aborted)
  2556. {
  2557. custom_message_type = custom_message_type_old;
  2558. custom_message_state = custom_message_state_old;
  2559. return;
  2560. }
  2561. // Go down until endstop is hit
  2562. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2563. 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
  2564. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2565. break;
  2566. }
  2567. 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.
  2568. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2569. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2570. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2571. st_synchronize();
  2572. 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
  2573. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2574. break;
  2575. }
  2576. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2577. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2578. break;
  2579. }
  2580. }
  2581. 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
  2582. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2583. break;
  2584. }
  2585. #ifdef SUPPORT_VERBOSITY
  2586. if (verbosity_level >= 10) {
  2587. SERIAL_ECHOPGM("X: ");
  2588. MYSERIAL.print(current_position[X_AXIS], 5);
  2589. SERIAL_ECHOLNPGM("");
  2590. SERIAL_ECHOPGM("Y: ");
  2591. MYSERIAL.print(current_position[Y_AXIS], 5);
  2592. SERIAL_PROTOCOLPGM("\n");
  2593. }
  2594. #endif // SUPPORT_VERBOSITY
  2595. float offset_z = 0;
  2596. #ifdef PINDA_THERMISTOR
  2597. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2598. #endif //PINDA_THERMISTOR
  2599. // #ifdef SUPPORT_VERBOSITY
  2600. /* if (verbosity_level >= 1)
  2601. {
  2602. SERIAL_ECHOPGM("mesh bed leveling: ");
  2603. MYSERIAL.print(current_position[Z_AXIS], 5);
  2604. SERIAL_ECHOPGM(" offset: ");
  2605. MYSERIAL.print(offset_z, 5);
  2606. SERIAL_ECHOLNPGM("");
  2607. }*/
  2608. // #endif // SUPPORT_VERBOSITY
  2609. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2610. custom_message_state--;
  2611. mesh_point++;
  2612. lcd_update(1);
  2613. }
  2614. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2615. #ifdef SUPPORT_VERBOSITY
  2616. if (verbosity_level >= 20) {
  2617. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2618. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2619. MYSERIAL.print(current_position[Z_AXIS], 5);
  2620. }
  2621. #endif // SUPPORT_VERBOSITY
  2622. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2623. st_synchronize();
  2624. if (mesh_point != nMeasPoints * nMeasPoints) {
  2625. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2626. bool bState;
  2627. do { // repeat until Z-leveling o.k.
  2628. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2629. #ifdef TMC2130
  2630. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2631. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2632. #else // TMC2130
  2633. lcd_wait_for_click_delay(0); // ~ no timeout
  2634. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2635. #endif // TMC2130
  2636. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2637. bState=enable_z_endstop(false);
  2638. current_position[Z_AXIS] -= 1;
  2639. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2640. st_synchronize();
  2641. enable_z_endstop(true);
  2642. #ifdef TMC2130
  2643. tmc2130_home_enter(Z_AXIS_MASK);
  2644. #endif // TMC2130
  2645. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2646. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2647. st_synchronize();
  2648. #ifdef TMC2130
  2649. tmc2130_home_exit();
  2650. #endif // TMC2130
  2651. enable_z_endstop(bState);
  2652. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2653. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2654. custom_message_type = custom_message_type_old;
  2655. custom_message_state = custom_message_state_old;
  2656. lcd_update_enable(true); // display / status-line recovery
  2657. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2658. repeatcommand_front(); // re-run (i.e. of "G80")
  2659. return;
  2660. }
  2661. clean_up_after_endstop_move(l_feedmultiply);
  2662. // SERIAL_ECHOLNPGM("clean up finished ");
  2663. #ifndef PINDA_THERMISTOR
  2664. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2665. #endif
  2666. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2667. // SERIAL_ECHOLNPGM("babystep applied");
  2668. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2669. #ifdef SUPPORT_VERBOSITY
  2670. if (verbosity_level >= 1) {
  2671. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2672. }
  2673. #endif // SUPPORT_VERBOSITY
  2674. for (uint8_t i = 0; i < 4; ++i) {
  2675. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2676. long correction = 0;
  2677. if (code_seen(codes[i]))
  2678. correction = code_value_long();
  2679. else if (eeprom_bed_correction_valid) {
  2680. unsigned char *addr = (i < 2) ?
  2681. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2682. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2683. correction = eeprom_read_int8(addr);
  2684. }
  2685. if (correction == 0)
  2686. continue;
  2687. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2688. SERIAL_ERROR_START;
  2689. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2690. SERIAL_ECHO(correction);
  2691. SERIAL_ECHOLNPGM(" microns");
  2692. }
  2693. else {
  2694. float offset = float(correction) * 0.001f;
  2695. switch (i) {
  2696. case 0:
  2697. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2698. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2699. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2700. }
  2701. }
  2702. break;
  2703. case 1:
  2704. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2705. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2706. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2707. }
  2708. }
  2709. break;
  2710. case 2:
  2711. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2712. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2713. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2714. }
  2715. }
  2716. break;
  2717. case 3:
  2718. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2719. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2720. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2721. }
  2722. }
  2723. break;
  2724. }
  2725. }
  2726. }
  2727. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2728. if (nMeasPoints == 3) {
  2729. 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)
  2730. }
  2731. /*
  2732. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2733. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2734. SERIAL_PROTOCOLPGM(",");
  2735. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2736. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2737. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2738. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2739. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2740. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2741. SERIAL_PROTOCOLPGM(" ");
  2742. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2743. }
  2744. SERIAL_PROTOCOLPGM("\n");
  2745. }
  2746. */
  2747. if (nMeasPoints == 7 && magnet_elimination) {
  2748. mbl_interpolation(nMeasPoints);
  2749. }
  2750. /*
  2751. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2752. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2753. SERIAL_PROTOCOLPGM(",");
  2754. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2755. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2756. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2757. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2758. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2759. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2760. SERIAL_PROTOCOLPGM(" ");
  2761. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2762. }
  2763. SERIAL_PROTOCOLPGM("\n");
  2764. }
  2765. */
  2766. // SERIAL_ECHOLNPGM("Upsample finished");
  2767. mbl.active = 1; //activate mesh bed leveling
  2768. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2769. go_home_with_z_lift();
  2770. // SERIAL_ECHOLNPGM("Go home finished");
  2771. //unretract (after PINDA preheat retraction)
  2772. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2773. current_position[E_AXIS] += default_retraction;
  2774. plan_buffer_line_curposXYZE(400);
  2775. }
  2776. KEEPALIVE_STATE(NOT_BUSY);
  2777. // Restore custom message state
  2778. lcd_setstatuspgm(MSG_WELCOME);
  2779. custom_message_type = custom_message_type_old;
  2780. custom_message_state = custom_message_state_old;
  2781. lcd_update(2);
  2782. st_synchronize();
  2783. mesh_bed_leveling_flag = false;
  2784. }
  2785. void adjust_bed_reset()
  2786. {
  2787. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2788. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2789. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2790. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2791. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2792. }
  2793. //! @brief Calibrate XYZ
  2794. //! @param onlyZ if true, calibrate only Z axis
  2795. //! @param verbosity_level
  2796. //! @retval true Succeeded
  2797. //! @retval false Failed
  2798. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2799. {
  2800. bool final_result = false;
  2801. #ifdef TMC2130
  2802. FORCE_HIGH_POWER_START;
  2803. #endif // TMC2130
  2804. FORCE_BL_ON_START;
  2805. // Only Z calibration?
  2806. if (!onlyZ)
  2807. {
  2808. setTargetBed(0);
  2809. setAllTargetHotends(0);
  2810. adjust_bed_reset(); //reset bed level correction
  2811. }
  2812. // Disable the default update procedure of the display. We will do a modal dialog.
  2813. lcd_update_enable(false);
  2814. // Let the planner use the uncorrected coordinates.
  2815. mbl.reset();
  2816. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2817. // the planner will not perform any adjustments in the XY plane.
  2818. // Wait for the motors to stop and update the current position with the absolute values.
  2819. world2machine_revert_to_uncorrected();
  2820. // Reset the baby step value applied without moving the axes.
  2821. babystep_reset();
  2822. // Mark all axes as in a need for homing.
  2823. memset(axis_known_position, 0, sizeof(axis_known_position));
  2824. // Home in the XY plane.
  2825. //set_destination_to_current();
  2826. int l_feedmultiply = setup_for_endstop_move();
  2827. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2828. raise_z_above(MESH_HOME_Z_SEARCH);
  2829. st_synchronize();
  2830. home_xy();
  2831. enable_endstops(false);
  2832. current_position[X_AXIS] += 5;
  2833. current_position[Y_AXIS] += 5;
  2834. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2835. st_synchronize();
  2836. // Let the user move the Z axes up to the end stoppers.
  2837. #ifdef TMC2130
  2838. if (calibrate_z_auto())
  2839. {
  2840. #else //TMC2130
  2841. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2842. {
  2843. #endif //TMC2130
  2844. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2845. if(onlyZ){
  2846. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2847. lcd_puts_at_P(0,3,_n("1/9"));
  2848. }else{
  2849. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2850. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2851. lcd_puts_at_P(0,3,_n("1/4"));
  2852. }
  2853. refresh_cmd_timeout();
  2854. #ifndef STEEL_SHEET
  2855. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2856. {
  2857. lcd_wait_for_cool_down();
  2858. }
  2859. #endif //STEEL_SHEET
  2860. if(!onlyZ)
  2861. {
  2862. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2863. #ifdef STEEL_SHEET
  2864. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  2865. if(result == LCD_LEFT_BUTTON_CHOICE) {
  2866. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2867. }
  2868. #endif //STEEL_SHEET
  2869. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2870. KEEPALIVE_STATE(IN_HANDLER);
  2871. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2872. lcd_puts_at_P(0,3,_n("1/4"));
  2873. }
  2874. bool endstops_enabled = enable_endstops(false);
  2875. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2876. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2877. st_synchronize();
  2878. // Move the print head close to the bed.
  2879. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2880. enable_endstops(true);
  2881. #ifdef TMC2130
  2882. tmc2130_home_enter(Z_AXIS_MASK);
  2883. #endif //TMC2130
  2884. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2885. st_synchronize();
  2886. #ifdef TMC2130
  2887. tmc2130_home_exit();
  2888. #endif //TMC2130
  2889. enable_endstops(endstops_enabled);
  2890. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2891. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2892. {
  2893. if (onlyZ)
  2894. {
  2895. clean_up_after_endstop_move(l_feedmultiply);
  2896. // Z only calibration.
  2897. // Load the machine correction matrix
  2898. world2machine_initialize();
  2899. // and correct the current_position to match the transformed coordinate system.
  2900. world2machine_update_current();
  2901. //FIXME
  2902. bool result = sample_mesh_and_store_reference();
  2903. if (result)
  2904. {
  2905. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2906. {
  2907. // Shipped, the nozzle height has been set already. The user can start printing now.
  2908. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2909. }
  2910. final_result = true;
  2911. // babystep_apply();
  2912. }
  2913. }
  2914. else
  2915. {
  2916. // Reset the baby step value and the baby step applied flag.
  2917. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2918. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2919. // Complete XYZ calibration.
  2920. uint8_t point_too_far_mask = 0;
  2921. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2922. clean_up_after_endstop_move(l_feedmultiply);
  2923. // Print head up.
  2924. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2925. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2926. st_synchronize();
  2927. //#ifndef NEW_XYZCAL
  2928. if (result >= 0)
  2929. {
  2930. #ifdef HEATBED_V2
  2931. sample_z();
  2932. #else //HEATBED_V2
  2933. point_too_far_mask = 0;
  2934. // Second half: The fine adjustment.
  2935. // Let the planner use the uncorrected coordinates.
  2936. mbl.reset();
  2937. world2machine_reset();
  2938. // Home in the XY plane.
  2939. int l_feedmultiply = setup_for_endstop_move();
  2940. home_xy();
  2941. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2942. clean_up_after_endstop_move(l_feedmultiply);
  2943. // Print head up.
  2944. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2945. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2946. st_synchronize();
  2947. // if (result >= 0) babystep_apply();
  2948. #endif //HEATBED_V2
  2949. }
  2950. //#endif //NEW_XYZCAL
  2951. lcd_update_enable(true);
  2952. lcd_update(2);
  2953. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2954. if (result >= 0)
  2955. {
  2956. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2957. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2958. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2959. final_result = true;
  2960. }
  2961. }
  2962. #ifdef TMC2130
  2963. tmc2130_home_exit();
  2964. #endif
  2965. }
  2966. else
  2967. {
  2968. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2969. final_result = false;
  2970. }
  2971. }
  2972. else
  2973. {
  2974. // Timeouted.
  2975. }
  2976. lcd_update_enable(true);
  2977. #ifdef TMC2130
  2978. FORCE_HIGH_POWER_END;
  2979. #endif // TMC2130
  2980. FORCE_BL_ON_END;
  2981. return final_result;
  2982. }
  2983. void gcode_M114()
  2984. {
  2985. SERIAL_PROTOCOLPGM("X:");
  2986. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2987. SERIAL_PROTOCOLPGM(" Y:");
  2988. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2989. SERIAL_PROTOCOLPGM(" Z:");
  2990. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2991. SERIAL_PROTOCOLPGM(" E:");
  2992. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2993. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2994. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2995. SERIAL_PROTOCOLPGM(" Y:");
  2996. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2997. SERIAL_PROTOCOLPGM(" Z:");
  2998. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2999. SERIAL_PROTOCOLPGM(" E:");
  3000. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3001. }
  3002. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3003. void gcode_M123()
  3004. {
  3005. 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);
  3006. }
  3007. #endif //FANCHECK and TACH_0 or TACH_1
  3008. //! extracted code to compute z_shift for M600 in case of filament change operation
  3009. //! requested from fsensors.
  3010. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  3011. //! unlike the previous implementation, which was adding 25mm even when the head was
  3012. //! printing at e.g. 24mm height.
  3013. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  3014. //! the printout.
  3015. //! This function is templated to enable fast change of computation data type.
  3016. //! @return new z_shift value
  3017. template<typename T>
  3018. static T gcode_M600_filament_change_z_shift()
  3019. {
  3020. #ifdef FILAMENTCHANGE_ZADD
  3021. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  3022. // avoid floating point arithmetics when not necessary - results in shorter code
  3023. T z_shift = T(FILAMENTCHANGE_ZADD); // always move above printout
  3024. T ztmp = T( current_position[Z_AXIS] );
  3025. if((ztmp + z_shift) < T(MIN_Z_FOR_SWAP)){
  3026. z_shift = T(MIN_Z_FOR_SWAP) - ztmp; // make sure to be at least 25mm above the heat bed
  3027. }
  3028. return z_shift;
  3029. #else
  3030. return T(0);
  3031. #endif
  3032. }
  3033. static void mmu_M600_wait_and_beep() {
  3034. // Beep and wait for user to remove old filament and prepare new filament for load
  3035. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3036. int counterBeep = 0;
  3037. 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
  3038. bool bFirst = true;
  3039. while (!lcd_clicked()) {
  3040. manage_heater();
  3041. manage_inactivity(true);
  3042. #if BEEPER > 0
  3043. if (counterBeep == 500) {
  3044. counterBeep = 0;
  3045. }
  3046. SET_OUTPUT(BEEPER);
  3047. if (counterBeep == 0) {
  3048. if ((eSoundMode == e_SOUND_MODE_BLIND) || (eSoundMode == e_SOUND_MODE_LOUD) || ((eSoundMode == e_SOUND_MODE_ONCE) && bFirst)) {
  3049. bFirst = false;
  3050. WRITE(BEEPER, HIGH);
  3051. }
  3052. }
  3053. if (counterBeep == 20) {
  3054. WRITE(BEEPER, LOW);
  3055. }
  3056. counterBeep++;
  3057. #endif // BEEPER > 0
  3058. delay_keep_alive(4);
  3059. }
  3060. WRITE(BEEPER, LOW);
  3061. }
  3062. /// @brief load filament for mmu v2
  3063. /// @par nozzle_temp nozzle temperature to load filament
  3064. void mmu_M600_load_filament(bool automatic, float nozzle_temp) {
  3065. uint8_t tmp_extruder = MMU2::mmu2.get_current_tool();
  3066. if (automatic) {
  3067. tmp_extruder = ad_getAlternative(tmp_extruder);
  3068. }
  3069. lcd_update_enable(false);
  3070. lcd_clear();
  3071. lcd_puts_at_P(0, 1, _T(MSG_LOADING_FILAMENT));
  3072. lcd_print(' ');
  3073. lcd_print(tmp_extruder + 1);
  3074. // printf_P(PSTR("T code: %d \n"), tmp_extruder);
  3075. // mmu_printf_P(PSTR("T%d\n"), tmp_extruder);
  3076. setTargetHotend(nozzle_temp, active_extruder);
  3077. MMU2::mmu2.load_filament_to_nozzle(tmp_extruder);
  3078. load_filament_final_feed(); // @@TODO verify
  3079. st_synchronize();
  3080. }
  3081. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3082. st_synchronize();
  3083. float lastpos[4];
  3084. prusa_statistics(22);
  3085. //First backup current position and settings
  3086. int feedmultiplyBckp = feedmultiply;
  3087. float HotendTempBckp = degTargetHotend(active_extruder);
  3088. int fanSpeedBckp = fanSpeed;
  3089. lastpos[X_AXIS] = current_position[X_AXIS];
  3090. lastpos[Y_AXIS] = current_position[Y_AXIS];
  3091. lastpos[Z_AXIS] = current_position[Z_AXIS];
  3092. lastpos[E_AXIS] = current_position[E_AXIS];
  3093. // Retract E
  3094. current_position[E_AXIS] += e_shift;
  3095. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3096. st_synchronize();
  3097. // Lift Z
  3098. current_position[Z_AXIS] += z_shift;
  3099. clamp_to_software_endstops(current_position);
  3100. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED);
  3101. st_synchronize();
  3102. // Move XY to side
  3103. current_position[X_AXIS] = x_position;
  3104. current_position[Y_AXIS] = y_position;
  3105. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3106. st_synchronize();
  3107. // Beep, manage nozzle heater and wait for user to start unload filament
  3108. if (!MMU2::mmu2.Enabled())
  3109. M600_wait_for_user(HotendTempBckp);
  3110. lcd_change_fil_state = 0;
  3111. // Unload filament
  3112. if (MMU2::mmu2.Enabled())
  3113. MMU2::mmu2.unload(); // unload just current filament for multimaterial printers (used also in M702)
  3114. else
  3115. unload_filament(true); // unload filament for single material (used also in M702)
  3116. st_synchronize(); // finish moves
  3117. {
  3118. FSensorBlockRunout fsBlockRunout;
  3119. if (!MMU2::mmu2.Enabled()) {
  3120. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3121. lcd_change_fil_state =
  3122. lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"), false, LCD_LEFT_BUTTON_CHOICE); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3123. if (lcd_change_fil_state == LCD_MIDDLE_BUTTON_CHOICE) {
  3124. lcd_clear();
  3125. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3126. current_position[X_AXIS] -= 100;
  3127. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3128. st_synchronize();
  3129. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually.")); ////MSG_CHECK_IDLER c=20 r=5
  3130. }
  3131. }
  3132. if (MMU2::mmu2.Enabled()) {
  3133. if (!automatic) {
  3134. if (saved_printing){
  3135. // if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3136. MMU2::mmu2.eject_filament(MMU2::mmu2.get_current_tool(), false);
  3137. }
  3138. mmu_M600_wait_and_beep();
  3139. if (saved_printing) {
  3140. lcd_clear();
  3141. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3142. //@@TODO mmu_command(MmuCmd::R0);
  3143. // manage_response(false, false);
  3144. }
  3145. }
  3146. mmu_M600_load_filament(automatic, HotendTempBckp);
  3147. } else
  3148. M600_load_filament();
  3149. if (!automatic)
  3150. M600_check_state(HotendTempBckp);
  3151. lcd_update_enable(true);
  3152. // Not let's go back to print
  3153. fanSpeed = fanSpeedBckp;
  3154. // Feed a little of filament to stabilize pressure
  3155. if (!automatic) {
  3156. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3157. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3158. }
  3159. // Move XY back
  3160. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3161. st_synchronize();
  3162. // Move Z back
  3163. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3164. st_synchronize();
  3165. // Set E position to original
  3166. plan_set_e_position(lastpos[E_AXIS]);
  3167. memcpy(current_position, lastpos, sizeof(lastpos));
  3168. set_destination_to_current();
  3169. // Recover feed rate
  3170. feedmultiply = feedmultiplyBckp;
  3171. char cmd[9];
  3172. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3173. enquecommand(cmd);
  3174. }
  3175. lcd_setstatuspgm(MSG_WELCOME);
  3176. custom_message_type = CustomMsg::Status;
  3177. }
  3178. void gcode_M701(uint8_t mmuSlotIndex){
  3179. printf_P(PSTR("gcode_M701 begin\n"));
  3180. FSensorBlockRunout fsBlockRunout;
  3181. prusa_statistics(22);
  3182. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3183. MMU2::mmu2.load_filament(mmuSlotIndex); // loads current extruder
  3184. // mmu_extruder = mmuSlotIndex; // @@TODO shall load filament set current tool to some specific index? We don't do that anymore.
  3185. } else {
  3186. enable_z();
  3187. custom_message_type = CustomMsg::FilamentLoading;
  3188. const int feed_mm_before_raising = 30;
  3189. static_assert(feed_mm_before_raising <= FILAMENTCHANGE_FIRSTFEED);
  3190. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3191. current_position[E_AXIS] += FILAMENTCHANGE_FIRSTFEED - feed_mm_before_raising;
  3192. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3193. st_synchronize();
  3194. raise_z_above(MIN_Z_FOR_LOAD, false);
  3195. current_position[E_AXIS] += feed_mm_before_raising;
  3196. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3197. load_filament_final_feed(); // slow sequence
  3198. st_synchronize();
  3199. Sound_MakeCustom(50, 500, false);
  3200. if (!farm_mode && loading_flag) {
  3201. lcd_load_filament_color_check();
  3202. }
  3203. lcd_update_enable(true);
  3204. lcd_update(2);
  3205. lcd_setstatuspgm(MSG_WELCOME);
  3206. disable_z();
  3207. loading_flag = false;
  3208. custom_message_type = CustomMsg::Status;
  3209. }
  3210. eFilamentAction = FilamentAction::None;
  3211. }
  3212. /**
  3213. * @brief Get serial number from 32U2 processor
  3214. *
  3215. * Typical format of S/N is:CZPX0917X003XC13518
  3216. *
  3217. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3218. * reply is stored in *SN.
  3219. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3220. * and returns a general failure flag.
  3221. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3222. * In that case the value that is stored in the EEPROM should be used instead.
  3223. *
  3224. * @return 0 on success
  3225. * @return 1 on general failure
  3226. */
  3227. #ifdef PRUSA_SN_SUPPORT
  3228. static uint8_t get_PRUSA_SN(char* SN)
  3229. {
  3230. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3231. uint8_t rxIndex;
  3232. bool SN_valid = false;
  3233. ShortTimer timeout;
  3234. selectedSerialPort = 0;
  3235. timeout.start();
  3236. while (!SN_valid)
  3237. {
  3238. rxIndex = 0;
  3239. _delay(50);
  3240. MYSERIAL.flush(); //clear RX buffer
  3241. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3242. while (rxIndex < 19)
  3243. {
  3244. if (timeout.expired(250u))
  3245. goto exit;
  3246. if (MYSERIAL.available() > 0)
  3247. {
  3248. SN[rxIndex] = MYSERIAL.read();
  3249. rxIndex++;
  3250. }
  3251. }
  3252. SN[rxIndex] = 0;
  3253. // printf_P(PSTR("SN:%s\n"), SN);
  3254. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3255. }
  3256. exit:
  3257. selectedSerialPort = selectedSerialPort_bak;
  3258. return !SN_valid;
  3259. }
  3260. #endif //PRUSA_SN_SUPPORT
  3261. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3262. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3263. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3264. //! it may even interfere with other functions of the printer! You have been warned!
  3265. //! The test idea is to measure the time necessary to charge the capacitor.
  3266. //! So the algorithm is as follows:
  3267. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3268. //! 2. Wait a few ms
  3269. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3270. //! Repeat 1.-3. several times
  3271. //! Good RAMBo's times are in the range of approx. 260-320 us
  3272. //! Bad RAMBo's times are approx. 260-1200 us
  3273. //! So basically we are interested in maximum time, the minima are mostly the same.
  3274. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3275. static void gcode_PRUSA_BadRAMBoFanTest(){
  3276. //printf_P(PSTR("Enter fan pin test\n"));
  3277. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3278. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3279. unsigned long tach1max = 0;
  3280. uint8_t tach1cntr = 0;
  3281. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3282. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3283. SET_OUTPUT(TACH_1);
  3284. WRITE(TACH_1, LOW);
  3285. _delay(20); // the delay may be lower
  3286. unsigned long tachMeasure = _micros();
  3287. cli();
  3288. SET_INPUT(TACH_1);
  3289. // just wait brutally in an endless cycle until we reach HIGH
  3290. // if this becomes a problem it may be improved to non-endless cycle
  3291. while( READ(TACH_1) == 0 ) ;
  3292. sei();
  3293. tachMeasure = _micros() - tachMeasure;
  3294. if( tach1max < tachMeasure )
  3295. tach1max = tachMeasure;
  3296. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3297. }
  3298. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3299. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3300. if( tach1max > 500 ){
  3301. // bad RAMBo
  3302. SERIAL_PROTOCOLLNPGM("BAD");
  3303. } else {
  3304. SERIAL_PROTOCOLLNPGM("OK");
  3305. }
  3306. // cleanup after the test function
  3307. SET_INPUT(TACH_1);
  3308. WRITE(TACH_1, HIGH);
  3309. #endif
  3310. }
  3311. // G92 - Set current position to coordinates given
  3312. static void gcode_G92()
  3313. {
  3314. bool codes[NUM_AXIS];
  3315. float values[NUM_AXIS];
  3316. // Check which axes need to be set
  3317. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3318. {
  3319. codes[i] = code_seen(axis_codes[i]);
  3320. if(codes[i])
  3321. values[i] = code_value();
  3322. }
  3323. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3324. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3325. {
  3326. // As a special optimization, when _just_ clearing the E position
  3327. // we schedule a flag asynchronously along with the next block to
  3328. // reset the starting E position instead of stopping the planner
  3329. current_position[E_AXIS] = 0;
  3330. plan_reset_next_e();
  3331. }
  3332. else
  3333. {
  3334. // In any other case we're forced to synchronize
  3335. st_synchronize();
  3336. for(uint8_t i = 0; i < 3; ++i)
  3337. {
  3338. if(codes[i])
  3339. current_position[i] = values[i] + cs.add_homing[i];
  3340. }
  3341. if(codes[E_AXIS])
  3342. current_position[E_AXIS] = values[E_AXIS];
  3343. // Set all at once
  3344. plan_set_position_curposXYZE();
  3345. }
  3346. }
  3347. #ifdef EXTENDED_CAPABILITIES_REPORT
  3348. static void cap_line(const char* name, bool ena = false) {
  3349. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3350. }
  3351. static void extended_capabilities_report()
  3352. {
  3353. // AUTOREPORT_TEMP (M155)
  3354. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3355. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3356. // AUTOREPORT_FANS (M123)
  3357. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3358. #endif //FANCHECK and TACH_0 or TACH_1
  3359. // AUTOREPORT_POSITION (M114)
  3360. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3361. // EXTENDED_M20 (support for L and T parameters)
  3362. cap_line(PSTR("EXTENDED_M20"), 1);
  3363. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3364. }
  3365. #endif //EXTENDED_CAPABILITIES_REPORT
  3366. #ifdef BACKLASH_X
  3367. extern uint8_t st_backlash_x;
  3368. #endif //BACKLASH_X
  3369. #ifdef BACKLASH_Y
  3370. extern uint8_t st_backlash_y;
  3371. #endif //BACKLASH_Y
  3372. //! \ingroup marlin_main
  3373. //! @brief Parse and process commands
  3374. //!
  3375. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3376. //!
  3377. //!
  3378. //! Implemented Codes
  3379. //! -------------------
  3380. //!
  3381. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3382. //!
  3383. //!@n PRUSA CODES
  3384. //!@n P F - Returns FW versions
  3385. //!@n P R - Returns revision of printer
  3386. //!
  3387. //!@n G0 -> G1
  3388. //!@n G1 - Coordinated Movement X Y Z E
  3389. //!@n G2 - CW ARC
  3390. //!@n G3 - CCW ARC
  3391. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3392. //!@n G10 - retract filament according to settings of M207
  3393. //!@n G11 - retract recover filament according to settings of M208
  3394. //!@n G28 - Home all Axes
  3395. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3396. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3397. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3398. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3399. //!@n G80 - Automatic mesh bed leveling
  3400. //!@n G81 - Print bed profile
  3401. //!@n G90 - Use Absolute Coordinates
  3402. //!@n G91 - Use Relative Coordinates
  3403. //!@n G92 - Set current position to coordinates given
  3404. //!
  3405. //!@n M Codes
  3406. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3407. //!@n M1 - Same as M0
  3408. //!@n M17 - Enable/Power all stepper motors
  3409. //!@n M18 - Disable all stepper motors; same as M84
  3410. //!@n M20 - List SD card
  3411. //!@n M21 - Init SD card
  3412. //!@n M22 - Release SD card
  3413. //!@n M23 - Select SD file (M23 filename.g)
  3414. //!@n M24 - Start/resume SD print
  3415. //!@n M25 - Pause SD print
  3416. //!@n M26 - Set SD position in bytes (M26 S12345)
  3417. //!@n M27 - Report SD print status
  3418. //!@n M28 - Start SD write (M28 filename.g)
  3419. //!@n M29 - Stop SD write
  3420. //!@n M30 - Delete file from SD (M30 filename.g)
  3421. //!@n M31 - Output time since last M109 or SD card start to serial
  3422. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3423. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3424. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3425. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3426. //!@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.
  3427. //!@n M73 - Show percent done and print time remaining
  3428. //!@n M80 - Turn on Power Supply
  3429. //!@n M81 - Turn off Power Supply
  3430. //!@n M82 - Set E codes absolute (default)
  3431. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3432. //!@n M84 - Disable steppers until next move,
  3433. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3434. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3435. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3436. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3437. //!@n M104 - Set extruder target temp
  3438. //!@n M105 - Read current temp
  3439. //!@n M106 - Fan on
  3440. //!@n M107 - Fan off
  3441. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3442. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3443. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3444. //!@n M112 - Emergency stop
  3445. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3446. //!@n M114 - Output current position to serial port
  3447. //!@n M115 - Capabilities string
  3448. //!@n M117 - display message
  3449. //!@n M119 - Output Endstop status to serial port
  3450. //!@n M123 - Tachometer value
  3451. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3452. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3453. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3454. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3455. //!@n M140 - Set bed target temp
  3456. //!@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.
  3457. //!@n M155 - Automatically send temperatures, fan speeds, position
  3458. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3459. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3460. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3461. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3462. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3463. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3464. //!@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
  3465. //!@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
  3466. //!@n M206 - set additional homing offset
  3467. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3468. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3469. //!@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.
  3470. //!@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>
  3471. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3472. //!@n M220 S<factor in percent>- set speed factor override percentage
  3473. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3474. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3475. //!@n M240 - Trigger a camera to take a photograph
  3476. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3477. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3478. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3479. //!@n M301 - Set PID parameters P I and D
  3480. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3481. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3482. //!@n M304 - Set bed PID parameters P I and D
  3483. //!@n M310 - Temperature model settings
  3484. //!@n M400 - Finish all moves
  3485. //!@n M401 - Lower z-probe if present
  3486. //!@n M402 - Raise z-probe if present
  3487. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3488. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3489. //!@n M406 - Turn off Filament Sensor extrusion control
  3490. //!@n M407 - Displays measured filament diameter
  3491. //!@n M500 - stores parameters in EEPROM
  3492. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3493. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3494. //!@n M503 - print the current settings (from memory not from EEPROM)
  3495. //!@n M509 - force language selection on next restart
  3496. //!@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)
  3497. //!@n M552 - Set IP address
  3498. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3499. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3500. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3501. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3502. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3503. //!@n M907 - Set digital trimpot motor current using axis codes.
  3504. //!@n M908 - Control digital trimpot directly.
  3505. //!@n M350 - Set microstepping mode.
  3506. //!@n M351 - Toggle MS1 MS2 pins directly.
  3507. //!
  3508. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3509. //!@n M999 - Restart after being stopped by error
  3510. //! <br><br>
  3511. /** @defgroup marlin_main Marlin main */
  3512. /** \ingroup GCodes */
  3513. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3514. /**
  3515. They are shown in order of appearance in the code.
  3516. There are reasons why some G Codes aren't in numerical order.
  3517. */
  3518. void process_commands()
  3519. {
  3520. if (!buflen) return; //empty command
  3521. #ifdef CMDBUFFER_DEBUG
  3522. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3523. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3524. SERIAL_ECHOLNPGM("");
  3525. SERIAL_ECHOPGM("In cmdqueue: ");
  3526. SERIAL_ECHO(buflen);
  3527. SERIAL_ECHOLNPGM("");
  3528. #endif /* CMDBUFFER_DEBUG */
  3529. unsigned long codenum; //throw away variable
  3530. char *starpos = NULL;
  3531. #ifdef ENABLE_AUTO_BED_LEVELING
  3532. float x_tmp, y_tmp, z_tmp, real_z;
  3533. #endif
  3534. // PRUSA GCODES
  3535. KEEPALIVE_STATE(IN_HANDLER);
  3536. /*!
  3537. ---------------------------------------------------------------------------------
  3538. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3539. This causes the given message to be shown in the status line on an attached LCD.
  3540. It is processed early as to allow printing messages that contain G, M, N or T.
  3541. ---------------------------------------------------------------------------------
  3542. ### Special internal commands
  3543. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3544. They are processed early as the commands are complex (strings).
  3545. These are only available on the MK3(S) as these require TMC2130 drivers:
  3546. - CRASH DETECTED
  3547. - CRASH RECOVER
  3548. - CRASH_CANCEL
  3549. - TMC_SET_WAVE
  3550. - TMC_SET_STEP
  3551. - TMC_SET_CHOP
  3552. */
  3553. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3554. {
  3555. starpos = (strchr(strchr_pointer + 5, '*'));
  3556. if (starpos != NULL)
  3557. *(starpos) = '\0';
  3558. lcd_setstatus(strchr_pointer + 5);
  3559. custom_message_type = CustomMsg::M117;
  3560. }
  3561. /*!
  3562. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3563. #### Usage
  3564. M0 [P<ms<] [S<sec>] [string]
  3565. M1 [P<ms>] [S<sec>] [string]
  3566. #### Parameters
  3567. - `P<ms>` - Expire time, in milliseconds
  3568. - `S<sec>` - Expire time, in seconds
  3569. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3570. */
  3571. 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
  3572. const char *src = strchr_pointer + 2;
  3573. codenum = 0;
  3574. bool hasP = false, hasS = false;
  3575. if (code_seen('P')) {
  3576. codenum = code_value_long(); // milliseconds to wait
  3577. hasP = codenum > 0;
  3578. }
  3579. if (code_seen('S')) {
  3580. codenum = code_value_long() * 1000; // seconds to wait
  3581. hasS = codenum > 0;
  3582. }
  3583. starpos = strchr(src, '*');
  3584. if (starpos != NULL) *(starpos) = '\0';
  3585. while (*src == ' ') ++src;
  3586. custom_message_type = CustomMsg::M0Wait;
  3587. if (!hasP && !hasS && *src != '\0') {
  3588. lcd_setstatus(src);
  3589. } else {
  3590. // farmers want to abuse a bug from the previous firmware releases
  3591. // - they need to see the filename on the status screen instead of "Wait for user..."
  3592. // So we won't update the message in farm mode...
  3593. if( ! farm_mode){
  3594. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3595. } else {
  3596. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3597. }
  3598. }
  3599. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3600. st_synchronize();
  3601. previous_millis_cmd.start();
  3602. if (codenum > 0 ) {
  3603. codenum += _millis(); // keep track of when we started waiting
  3604. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3605. while(_millis() < codenum && !lcd_clicked()) {
  3606. manage_heater();
  3607. manage_inactivity(true);
  3608. lcd_update(0);
  3609. }
  3610. KEEPALIVE_STATE(IN_HANDLER);
  3611. lcd_ignore_click(false);
  3612. } else {
  3613. marlin_wait_for_click();
  3614. }
  3615. if (IS_SD_PRINTING)
  3616. custom_message_type = CustomMsg::Status;
  3617. else
  3618. LCD_MESSAGERPGM(MSG_WELCOME);
  3619. }
  3620. #ifdef TMC2130
  3621. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3622. {
  3623. // ### CRASH_DETECTED - TMC2130
  3624. // ---------------------------------
  3625. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3626. {
  3627. uint8_t mask = 0;
  3628. if (code_seen('X')) mask |= X_AXIS_MASK;
  3629. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3630. crashdet_detected(mask);
  3631. }
  3632. // ### CRASH_RECOVER - TMC2130
  3633. // ----------------------------------
  3634. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3635. crashdet_recover();
  3636. // ### CRASH_CANCEL - TMC2130
  3637. // ----------------------------------
  3638. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3639. crashdet_cancel();
  3640. }
  3641. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3642. {
  3643. // ### TMC_SET_WAVE_
  3644. // --------------------
  3645. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3646. {
  3647. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3648. axis = (axis == 'E')?3:(axis - 'X');
  3649. if (axis < 4)
  3650. {
  3651. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3652. tmc2130_set_wave(axis, 247, fac);
  3653. }
  3654. }
  3655. // ### TMC_SET_STEP_
  3656. // ------------------
  3657. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3658. {
  3659. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3660. axis = (axis == 'E')?3:(axis - 'X');
  3661. if (axis < 4)
  3662. {
  3663. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3664. uint16_t res = tmc2130_get_res(axis);
  3665. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3666. }
  3667. }
  3668. // ### TMC_SET_CHOP_
  3669. // -------------------
  3670. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3671. {
  3672. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3673. axis = (axis == 'E')?3:(axis - 'X');
  3674. if (axis < 4)
  3675. {
  3676. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3677. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3678. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3679. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3680. char* str_end = 0;
  3681. if (CMDBUFFER_CURRENT_STRING[14])
  3682. {
  3683. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3684. if (str_end && *str_end)
  3685. {
  3686. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3687. if (str_end && *str_end)
  3688. {
  3689. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3690. if (str_end && *str_end)
  3691. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3692. }
  3693. }
  3694. }
  3695. tmc2130_chopper_config[axis].toff = chop0;
  3696. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3697. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3698. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3699. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3700. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3701. }
  3702. }
  3703. }
  3704. #ifdef BACKLASH_X
  3705. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3706. {
  3707. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3708. st_backlash_x = bl;
  3709. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3710. }
  3711. #endif //BACKLASH_X
  3712. #ifdef BACKLASH_Y
  3713. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3714. {
  3715. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3716. st_backlash_y = bl;
  3717. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3718. }
  3719. #endif //BACKLASH_Y
  3720. #endif //TMC2130
  3721. else if(code_seen_P(PSTR("PRUSA"))){
  3722. /*!
  3723. ---------------------------------------------------------------------------------
  3724. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3725. Set of internal PRUSA commands
  3726. #### Usage
  3727. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3728. #### Parameters
  3729. - `PRN` - Prints revision of the printer
  3730. - `FAN` - Prints fan details
  3731. - `thx`
  3732. - `uvlo`
  3733. - `MMURES` - Reset MMU
  3734. - `RESET` - (Careful!)
  3735. - `fv` - ?
  3736. - `M28`
  3737. - `SN`
  3738. - `Fir` - Prints firmware version
  3739. - `Rev`- Prints filament size, elelectronics, nozzle type
  3740. - `Lang` - Reset the language
  3741. - `Lz`
  3742. - `FR` - Full factory reset
  3743. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3744. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3745. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3746. */
  3747. if (farm_prusa_code_seen()) {}
  3748. else if(code_seen_P(PSTR("FANPINTST"))) {
  3749. gcode_PRUSA_BadRAMBoFanTest();
  3750. }
  3751. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3752. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3753. }
  3754. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3755. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3756. enquecommand_P(PSTR("M24"));
  3757. }
  3758. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3759. {
  3760. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  3761. }
  3762. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3763. #ifdef WATCHDOG
  3764. #if defined(XFLASH) && defined(BOOTAPP)
  3765. boot_app_magic = BOOT_APP_MAGIC;
  3766. boot_app_flags = BOOT_APP_FLG_RUN;
  3767. #endif //defined(XFLASH) && defined(BOOTAPP)
  3768. softReset();
  3769. #elif defined(BOOTAPP) //this is a safety precaution. This is because the new bootloader turns off the heaters, but the old one doesn't. The watchdog should be used most of the time.
  3770. asm volatile("jmp 0x3E000");
  3771. #endif
  3772. }
  3773. #ifdef PRUSA_SN_SUPPORT
  3774. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3775. char SN[20];
  3776. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3777. if (SN[19])
  3778. puts_P(PSTR("SN invalid"));
  3779. else
  3780. puts(SN);
  3781. }
  3782. #endif //PRUSA_SN_SUPPORT
  3783. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3784. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3785. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3786. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3787. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3788. lang_reset();
  3789. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3790. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3791. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3792. // Factory full reset
  3793. factory_reset(0);
  3794. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3795. // Change the MBL status without changing the logical Z position.
  3796. if(code_seen('V')) {
  3797. bool value = code_value_short();
  3798. st_synchronize();
  3799. if(value != mbl.active) {
  3800. mbl.active = value;
  3801. // Use plan_set_z_position to reset the physical values
  3802. plan_set_z_position(current_position[Z_AXIS]);
  3803. }
  3804. }
  3805. //-//
  3806. /*
  3807. } else if(code_seen("rrr")) {
  3808. MYSERIAL.println("=== checking ===");
  3809. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3810. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3811. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3812. MYSERIAL.println(farm_mode,DEC);
  3813. MYSERIAL.println(eCheckMode,DEC);
  3814. } else if(code_seen("www")) {
  3815. MYSERIAL.println("=== @ FF ===");
  3816. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3817. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3818. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3819. */
  3820. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3821. uint16_t nDiameter;
  3822. if(code_seen('D'))
  3823. {
  3824. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3825. nozzle_diameter_check(nDiameter);
  3826. }
  3827. else if(code_seen_P(PSTR("set")) && farm_mode)
  3828. {
  3829. strchr_pointer++; // skip 1st char (~ 's')
  3830. strchr_pointer++; // skip 2nd char (~ 'e')
  3831. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3832. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3833. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3834. }
  3835. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3836. //-// !!! SupportMenu
  3837. /*
  3838. // musi byt PRED "PRUSA model"
  3839. } else if (code_seen("smodel")) { //! PRUSA smodel
  3840. size_t nOffset;
  3841. // ! -> "l"
  3842. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3843. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3844. if(*(strchr_pointer+1+nOffset))
  3845. printer_smodel_check(strchr_pointer);
  3846. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3847. } else if (code_seen("model")) { //! PRUSA model
  3848. uint16_t nPrinterModel;
  3849. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3850. nPrinterModel=(uint16_t)code_value_long();
  3851. if(nPrinterModel!=0)
  3852. printer_model_check(nPrinterModel);
  3853. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3854. } else if (code_seen("version")) { //! PRUSA version
  3855. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3856. while(*strchr_pointer==' ') // skip leading spaces
  3857. strchr_pointer++;
  3858. if(*strchr_pointer!=0)
  3859. fw_version_check(strchr_pointer);
  3860. else SERIAL_PROTOCOLLN(FW_VERSION);
  3861. } else if (code_seen("gcode")) { //! PRUSA gcode
  3862. uint16_t nGcodeLevel;
  3863. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3864. nGcodeLevel=(uint16_t)code_value_long();
  3865. if(nGcodeLevel!=0)
  3866. gcode_level_check(nGcodeLevel);
  3867. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3868. */
  3869. }
  3870. //else if (code_seen('Cal')) {
  3871. // lcd_calibration();
  3872. // }
  3873. }
  3874. // This prevents reading files with "^" in their names.
  3875. // Since it is unclear, if there is some usage of this construct,
  3876. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3877. // else if (code_seen('^')) {
  3878. // // nothing, this is a version line
  3879. // }
  3880. else if(code_seen('G'))
  3881. {
  3882. gcode_in_progress = code_value_short();
  3883. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3884. switch (gcode_in_progress)
  3885. {
  3886. /*!
  3887. ---------------------------------------------------------------------------------
  3888. # G Codes
  3889. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3890. In Prusa Firmware G0 and G1 are the same.
  3891. #### Usage
  3892. G0 [ X | Y | Z | E | F | S ]
  3893. G1 [ X | Y | Z | E | F | S ]
  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. - `E` - The amount to extrude between the starting point and ending point
  3899. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3900. */
  3901. case 0: // G0 -> G1
  3902. case 1: // G1
  3903. {
  3904. uint16_t start_segment_idx = restore_interrupted_gcode();
  3905. get_coordinates(); // For X Y Z E F
  3906. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3907. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3908. }
  3909. #ifdef FWRETRACT
  3910. if(cs.autoretract_enabled) {
  3911. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3912. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3913. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3914. st_synchronize();
  3915. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3916. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3917. retract(!retracted[active_extruder]);
  3918. return;
  3919. }
  3920. }
  3921. }
  3922. #endif //FWRETRACT
  3923. prepare_move(start_segment_idx);
  3924. //ClearToSend();
  3925. }
  3926. break;
  3927. /*!
  3928. ### 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>
  3929. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3930. #### Usage
  3931. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3932. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3933. #### Parameters
  3934. - `X` - The position to move to on the X axis
  3935. - `Y` - The position to move to on the Y axis
  3936. - 'Z' - The position to move to on the Z axis
  3937. - `I` - The point in X space from the current X position to maintain a constant distance from
  3938. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3939. - `E` - The amount to extrude between the starting point and ending point
  3940. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3941. */
  3942. case 2:
  3943. case 3:
  3944. {
  3945. uint16_t start_segment_idx = restore_interrupted_gcode();
  3946. #ifdef SF_ARC_FIX
  3947. bool relative_mode_backup = relative_mode;
  3948. relative_mode = true;
  3949. #endif
  3950. get_coordinates(); // For X Y Z E F
  3951. #ifdef SF_ARC_FIX
  3952. relative_mode=relative_mode_backup;
  3953. #endif
  3954. offset[0] = code_seen('I') ? code_value() : 0.f;
  3955. offset[1] = code_seen('J') ? code_value() : 0.f;
  3956. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3957. } break;
  3958. /*!
  3959. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3960. Pause the machine for a period of time.
  3961. #### Usage
  3962. G4 [ P | S ]
  3963. #### Parameters
  3964. - `P` - Time to wait, in milliseconds
  3965. - `S` - Time to wait, in seconds
  3966. */
  3967. case 4:
  3968. codenum = 0;
  3969. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3970. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3971. if(codenum != 0)
  3972. {
  3973. if(custom_message_type != CustomMsg::M117)
  3974. {
  3975. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3976. }
  3977. }
  3978. st_synchronize();
  3979. codenum += _millis(); // keep track of when we started waiting
  3980. previous_millis_cmd.start();
  3981. while(_millis() < codenum) {
  3982. manage_heater();
  3983. manage_inactivity();
  3984. lcd_update(0);
  3985. }
  3986. break;
  3987. #ifdef FWRETRACT
  3988. /*!
  3989. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3990. Retracts filament according to settings of `M207`
  3991. */
  3992. case 10:
  3993. #if EXTRUDERS > 1
  3994. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3995. retract(true,retracted_swap[active_extruder]);
  3996. #else
  3997. retract(true);
  3998. #endif
  3999. break;
  4000. /*!
  4001. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  4002. Unretracts/recovers filament according to settings of `M208`
  4003. */
  4004. case 11:
  4005. #if EXTRUDERS > 1
  4006. retract(false,retracted_swap[active_extruder]);
  4007. #else
  4008. retract(false);
  4009. #endif
  4010. break;
  4011. #endif //FWRETRACT
  4012. /*!
  4013. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  4014. Units are in millimeters. Prusa doesn't support inches.
  4015. */
  4016. case 21:
  4017. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  4018. /*!
  4019. ### 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>
  4020. 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).
  4021. #### Usage
  4022. G28 [ X | Y | Z | W | C ]
  4023. #### Parameters
  4024. - `X` - Flag to go back to the X axis origin
  4025. - `Y` - Flag to go back to the Y axis origin
  4026. - `Z` - Flag to go back to the Z axis origin
  4027. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  4028. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  4029. */
  4030. case 28:
  4031. {
  4032. long home_x_value = 0;
  4033. long home_y_value = 0;
  4034. long home_z_value = 0;
  4035. // Which axes should be homed?
  4036. bool home_x = code_seen(axis_codes[X_AXIS]);
  4037. if (home_x) home_x_value = code_value_long();
  4038. bool home_y = code_seen(axis_codes[Y_AXIS]);
  4039. if (home_y) home_y_value = code_value_long();
  4040. bool home_z = code_seen(axis_codes[Z_AXIS]);
  4041. if (home_z) home_z_value = code_value_long();
  4042. bool without_mbl = code_seen('W');
  4043. // calibrate?
  4044. #ifdef TMC2130
  4045. bool calib = code_seen('C');
  4046. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4047. #else
  4048. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4049. #endif //TMC2130
  4050. if ((home_x || home_y || without_mbl || home_z) == false) {
  4051. gcode_G80();
  4052. }
  4053. break;
  4054. }
  4055. #ifdef ENABLE_AUTO_BED_LEVELING
  4056. /*!
  4057. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4058. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4059. See `G81`
  4060. */
  4061. case 29:
  4062. {
  4063. #if Z_MIN_PIN == -1
  4064. #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."
  4065. #endif
  4066. // Prevent user from running a G29 without first homing in X and Y
  4067. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4068. {
  4069. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4070. SERIAL_ECHO_START;
  4071. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4072. break; // abort G29, since we don't know where we are
  4073. }
  4074. st_synchronize();
  4075. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4076. //vector_3 corrected_position = plan_get_position_mm();
  4077. //corrected_position.debug("position before G29");
  4078. plan_bed_level_matrix.set_to_identity();
  4079. vector_3 uncorrected_position = plan_get_position();
  4080. //uncorrected_position.debug("position durring G29");
  4081. current_position[X_AXIS] = uncorrected_position.x;
  4082. current_position[Y_AXIS] = uncorrected_position.y;
  4083. current_position[Z_AXIS] = uncorrected_position.z;
  4084. plan_set_position_curposXYZE();
  4085. int l_feedmultiply = setup_for_endstop_move();
  4086. feedrate = homing_feedrate[Z_AXIS];
  4087. #ifdef AUTO_BED_LEVELING_GRID
  4088. // probe at the points of a lattice grid
  4089. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4090. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4091. // solve the plane equation ax + by + d = z
  4092. // A is the matrix with rows [x y 1] for all the probed points
  4093. // B is the vector of the Z positions
  4094. // 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
  4095. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4096. // "A" matrix of the linear system of equations
  4097. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4098. // "B" vector of Z points
  4099. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4100. int probePointCounter = 0;
  4101. bool zig = true;
  4102. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4103. {
  4104. int xProbe, xInc;
  4105. if (zig)
  4106. {
  4107. xProbe = LEFT_PROBE_BED_POSITION;
  4108. //xEnd = RIGHT_PROBE_BED_POSITION;
  4109. xInc = xGridSpacing;
  4110. zig = false;
  4111. } else // zag
  4112. {
  4113. xProbe = RIGHT_PROBE_BED_POSITION;
  4114. //xEnd = LEFT_PROBE_BED_POSITION;
  4115. xInc = -xGridSpacing;
  4116. zig = true;
  4117. }
  4118. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4119. {
  4120. float z_before;
  4121. if (probePointCounter == 0)
  4122. {
  4123. // raise before probing
  4124. z_before = Z_RAISE_BEFORE_PROBING;
  4125. } else
  4126. {
  4127. // raise extruder
  4128. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4129. }
  4130. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4131. eqnBVector[probePointCounter] = measured_z;
  4132. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4133. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4134. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4135. probePointCounter++;
  4136. xProbe += xInc;
  4137. }
  4138. }
  4139. clean_up_after_endstop_move(l_feedmultiply);
  4140. // solve lsq problem
  4141. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4142. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4143. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4144. SERIAL_PROTOCOLPGM(" b: ");
  4145. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4146. SERIAL_PROTOCOLPGM(" d: ");
  4147. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4148. set_bed_level_equation_lsq(plane_equation_coefficients);
  4149. free(plane_equation_coefficients);
  4150. #else // AUTO_BED_LEVELING_GRID not defined
  4151. // Probe at 3 arbitrary points
  4152. // probe 1
  4153. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4154. // probe 2
  4155. 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);
  4156. // probe 3
  4157. 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);
  4158. clean_up_after_endstop_move(l_feedmultiply);
  4159. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4160. #endif // AUTO_BED_LEVELING_GRID
  4161. st_synchronize();
  4162. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4163. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4164. // When the bed is uneven, this height must be corrected.
  4165. 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)
  4166. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4167. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4168. z_tmp = current_position[Z_AXIS];
  4169. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4170. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4171. plan_set_position_curposXYZE();
  4172. }
  4173. break;
  4174. #ifndef Z_PROBE_SLED
  4175. /*!
  4176. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4177. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4178. */
  4179. case 30:
  4180. {
  4181. st_synchronize();
  4182. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4183. int l_feedmultiply = setup_for_endstop_move();
  4184. feedrate = homing_feedrate[Z_AXIS];
  4185. run_z_probe();
  4186. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4187. SERIAL_PROTOCOLPGM(" X: ");
  4188. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4189. SERIAL_PROTOCOLPGM(" Y: ");
  4190. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4191. SERIAL_PROTOCOLPGM(" Z: ");
  4192. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4193. SERIAL_PROTOCOLPGM("\n");
  4194. clean_up_after_endstop_move(l_feedmultiply);
  4195. }
  4196. break;
  4197. #else
  4198. /*!
  4199. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4200. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4201. */
  4202. case 31:
  4203. dock_sled(true);
  4204. break;
  4205. /*!
  4206. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4207. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4208. */
  4209. case 32:
  4210. dock_sled(false);
  4211. break;
  4212. #endif // Z_PROBE_SLED
  4213. #endif // ENABLE_AUTO_BED_LEVELING
  4214. #ifdef MESH_BED_LEVELING
  4215. /*!
  4216. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4217. Sensor must be over the bed.
  4218. The maximum travel distance before an error is triggered is 10mm.
  4219. */
  4220. case 30:
  4221. {
  4222. st_synchronize();
  4223. homing_flag = true;
  4224. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4225. int l_feedmultiply = setup_for_endstop_move();
  4226. feedrate = homing_feedrate[Z_AXIS];
  4227. find_bed_induction_sensor_point_z(-10.f, 3);
  4228. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4229. clean_up_after_endstop_move(l_feedmultiply);
  4230. homing_flag = false;
  4231. }
  4232. break;
  4233. /*!
  4234. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4235. Show/print PINDA temperature interpolating.
  4236. */
  4237. case 75:
  4238. {
  4239. for (uint8_t i = 40; i <= 110; i++)
  4240. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4241. }
  4242. break;
  4243. /*!
  4244. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4245. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4246. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4247. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4248. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4249. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4250. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4251. #### Example
  4252. ```
  4253. G76
  4254. echo PINDA probe calibration start
  4255. echo start temperature: 35.0°
  4256. echo ...
  4257. echo PINDA temperature -- Z shift (mm): 0.---
  4258. ```
  4259. */
  4260. case 76:
  4261. {
  4262. #ifdef PINDA_THERMISTOR
  4263. if (!has_temperature_compensation())
  4264. {
  4265. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4266. break;
  4267. }
  4268. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4269. //we need to know accurate position of first calibration point
  4270. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4271. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4272. break;
  4273. }
  4274. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4275. {
  4276. // We don't know where we are! HOME!
  4277. // Push the commands to the front of the message queue in the reverse order!
  4278. // There shall be always enough space reserved for these commands.
  4279. repeatcommand_front(); // repeat G76 with all its parameters
  4280. enquecommand_front_P(G28W0);
  4281. break;
  4282. }
  4283. 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
  4284. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  4285. if (result == LCD_LEFT_BUTTON_CHOICE)
  4286. {
  4287. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4288. plan_buffer_line_curposXYZE(3000 / 60);
  4289. current_position[Z_AXIS] = 50;
  4290. current_position[Y_AXIS] = 180;
  4291. plan_buffer_line_curposXYZE(3000 / 60);
  4292. st_synchronize();
  4293. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4294. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4295. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4296. plan_buffer_line_curposXYZE(3000 / 60);
  4297. st_synchronize();
  4298. gcode_G28(false, false, true);
  4299. }
  4300. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4301. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4302. current_position[Z_AXIS] = 100;
  4303. plan_buffer_line_curposXYZE(3000 / 60);
  4304. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4305. lcd_temp_cal_show_result(false);
  4306. break;
  4307. }
  4308. }
  4309. st_synchronize();
  4310. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4311. lcd_update_enable(true);
  4312. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4313. float zero_z;
  4314. int z_shift = 0; //unit: steps
  4315. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4316. if (start_temp < 35) start_temp = 35;
  4317. if (start_temp < current_temperature_pinda) start_temp += 5;
  4318. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4319. // setTargetHotend(200, 0);
  4320. setTargetBed(70 + (start_temp - 30));
  4321. custom_message_type = CustomMsg::TempCal;
  4322. custom_message_state = 1;
  4323. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4324. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4325. plan_buffer_line_curposXYZE(3000 / 60);
  4326. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4327. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4328. plan_buffer_line_curposXYZE(3000 / 60);
  4329. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4330. plan_buffer_line_curposXYZE(3000 / 60);
  4331. st_synchronize();
  4332. while (current_temperature_pinda < start_temp)
  4333. {
  4334. delay_keep_alive(1000);
  4335. serialecho_temperatures();
  4336. }
  4337. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4338. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4339. plan_buffer_line_curposXYZE(3000 / 60);
  4340. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4341. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4342. plan_buffer_line_curposXYZE(3000 / 60);
  4343. st_synchronize();
  4344. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4345. if (find_z_result == false) {
  4346. lcd_temp_cal_show_result(find_z_result);
  4347. homing_flag = false;
  4348. break;
  4349. }
  4350. zero_z = current_position[Z_AXIS];
  4351. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4352. int i = -1; for (; i < 5; i++)
  4353. {
  4354. float temp = (40 + i * 5);
  4355. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4356. if (i >= 0) {
  4357. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4358. }
  4359. if (start_temp <= temp) break;
  4360. }
  4361. for (i++; i < 5; i++)
  4362. {
  4363. float temp = (40 + i * 5);
  4364. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4365. custom_message_state = i + 2;
  4366. setTargetBed(50 + 10 * (temp - 30) / 5);
  4367. // setTargetHotend(255, 0);
  4368. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4369. plan_buffer_line_curposXYZE(3000 / 60);
  4370. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4371. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4372. plan_buffer_line_curposXYZE(3000 / 60);
  4373. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4374. plan_buffer_line_curposXYZE(3000 / 60);
  4375. st_synchronize();
  4376. while (current_temperature_pinda < temp)
  4377. {
  4378. delay_keep_alive(1000);
  4379. serialecho_temperatures();
  4380. }
  4381. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4382. plan_buffer_line_curposXYZE(3000 / 60);
  4383. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4384. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4385. plan_buffer_line_curposXYZE(3000 / 60);
  4386. st_synchronize();
  4387. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4388. if (find_z_result == false) {
  4389. lcd_temp_cal_show_result(find_z_result);
  4390. break;
  4391. }
  4392. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4393. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4394. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4395. }
  4396. lcd_temp_cal_show_result(true);
  4397. homing_flag = false;
  4398. #else //PINDA_THERMISTOR
  4399. setTargetBed(PINDA_MIN_T);
  4400. float zero_z;
  4401. int z_shift = 0; //unit: steps
  4402. int t_c; // temperature
  4403. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4404. // We don't know where we are! HOME!
  4405. // Push the commands to the front of the message queue in the reverse order!
  4406. // There shall be always enough space reserved for these commands.
  4407. repeatcommand_front(); // repeat G76 with all its parameters
  4408. enquecommand_front_P(G28W0);
  4409. break;
  4410. }
  4411. puts_P(_N("PINDA probe calibration start"));
  4412. custom_message_type = CustomMsg::TempCal;
  4413. custom_message_state = 1;
  4414. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4415. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4416. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4417. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4418. plan_buffer_line_curposXYZE(3000 / 60);
  4419. st_synchronize();
  4420. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4421. delay_keep_alive(1000);
  4422. serialecho_temperatures();
  4423. }
  4424. //enquecommand_P(PSTR("M190 S50"));
  4425. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4426. delay_keep_alive(1000);
  4427. serialecho_temperatures();
  4428. }
  4429. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4430. current_position[Z_AXIS] = 5;
  4431. plan_buffer_line_curposXYZE(3000 / 60);
  4432. current_position[X_AXIS] = BED_X0;
  4433. current_position[Y_AXIS] = BED_Y0;
  4434. plan_buffer_line_curposXYZE(3000 / 60);
  4435. st_synchronize();
  4436. find_bed_induction_sensor_point_z(-1.f);
  4437. zero_z = current_position[Z_AXIS];
  4438. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4439. for (int i = 0; i<5; i++) {
  4440. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4441. custom_message_state = i + 2;
  4442. t_c = 60 + i * 10;
  4443. setTargetBed(t_c);
  4444. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4445. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4446. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4447. plan_buffer_line_curposXYZE(3000 / 60);
  4448. st_synchronize();
  4449. while (degBed() < t_c) {
  4450. delay_keep_alive(1000);
  4451. serialecho_temperatures();
  4452. }
  4453. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4454. delay_keep_alive(1000);
  4455. serialecho_temperatures();
  4456. }
  4457. current_position[Z_AXIS] = 5;
  4458. plan_buffer_line_curposXYZE(3000 / 60);
  4459. current_position[X_AXIS] = BED_X0;
  4460. current_position[Y_AXIS] = BED_Y0;
  4461. plan_buffer_line_curposXYZE(3000 / 60);
  4462. st_synchronize();
  4463. find_bed_induction_sensor_point_z(-1.f);
  4464. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4465. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4466. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4467. }
  4468. custom_message_type = CustomMsg::Status;
  4469. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4470. puts_P(_N("Temperature calibration done."));
  4471. disable_x();
  4472. disable_y();
  4473. disable_z();
  4474. disable_e0();
  4475. disable_e1();
  4476. disable_e2();
  4477. setTargetBed(0); //set bed target temperature back to 0
  4478. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4479. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4480. lcd_update_enable(true);
  4481. lcd_update(2);
  4482. #endif //PINDA_THERMISTOR
  4483. }
  4484. break;
  4485. /*!
  4486. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4487. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4488. #### Usage
  4489. G80 [ N | R | V | L | R | F | B ]
  4490. #### Parameters
  4491. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4492. - `R` - Probe retries. Default 3 max. 10
  4493. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4494. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4495. #### Additional Parameters
  4496. - `L` - Left Bed Level correct value in um.
  4497. - `R` - Right Bed Level correct value in um.
  4498. - `F` - Front Bed Level correct value in um.
  4499. - `B` - Back Bed Level correct value in um.
  4500. */
  4501. /*
  4502. * Probes a grid and produces a mesh to compensate for variable bed height
  4503. * The S0 report the points as below
  4504. * +----> X-axis
  4505. * |
  4506. * |
  4507. * v Y-axis
  4508. */
  4509. case 80: {
  4510. gcode_G80();
  4511. }
  4512. break;
  4513. /*!
  4514. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4515. Prints mesh bed leveling status and bed profile if activated.
  4516. */
  4517. case 81:
  4518. if (mbl.active) {
  4519. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4520. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4521. SERIAL_PROTOCOL(',');
  4522. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4523. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4524. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4525. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4526. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4527. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4528. SERIAL_PROTOCOLPGM(" ");
  4529. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4530. }
  4531. SERIAL_PROTOCOLLN();
  4532. }
  4533. }
  4534. else
  4535. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4536. break;
  4537. #if 0
  4538. /*!
  4539. ### 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>
  4540. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4541. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4542. */
  4543. case 82:
  4544. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4545. int l_feedmultiply = setup_for_endstop_move();
  4546. find_bed_induction_sensor_point_z();
  4547. clean_up_after_endstop_move(l_feedmultiply);
  4548. SERIAL_PROTOCOLPGM("Bed found at: ");
  4549. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4550. SERIAL_PROTOCOLPGM("\n");
  4551. break;
  4552. /*!
  4553. ### 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>
  4554. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4555. */
  4556. case 83:
  4557. {
  4558. int babystepz = code_seen('S') ? code_value() : 0;
  4559. int BabyPosition = code_seen('P') ? code_value() : 0;
  4560. if (babystepz != 0) {
  4561. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4562. // Is the axis indexed starting with zero or one?
  4563. if (BabyPosition > 4) {
  4564. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4565. }else{
  4566. // Save it to the eeprom
  4567. babystepLoadZ = babystepz;
  4568. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4569. // adjust the Z
  4570. babystepsTodoZadd(babystepLoadZ);
  4571. }
  4572. }
  4573. }
  4574. break;
  4575. /*!
  4576. ### 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>
  4577. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4578. */
  4579. case 84:
  4580. babystepsTodoZsubtract(babystepLoadZ);
  4581. // babystepLoadZ = 0;
  4582. break;
  4583. /*!
  4584. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4585. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4586. */
  4587. case 85:
  4588. lcd_pick_babystep();
  4589. break;
  4590. #endif
  4591. /*!
  4592. ### 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>
  4593. This G-code will be performed at the start of a calibration script.
  4594. (Prusa3D specific)
  4595. */
  4596. case 86:
  4597. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4598. break;
  4599. /*!
  4600. ### 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>
  4601. This G-code will be performed at the end of a calibration script.
  4602. (Prusa3D specific)
  4603. */
  4604. case 87:
  4605. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4606. break;
  4607. /*!
  4608. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4609. Currently has no effect.
  4610. */
  4611. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4612. case 88:
  4613. break;
  4614. #endif // ENABLE_MESH_BED_LEVELING
  4615. /*!
  4616. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4617. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4618. */
  4619. case 90: {
  4620. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4621. }
  4622. break;
  4623. /*!
  4624. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4625. All coordinates from now on are relative to the last position. E axis is left intact.
  4626. */
  4627. case 91: {
  4628. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4629. }
  4630. break;
  4631. /*!
  4632. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4633. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4634. If a parameter is omitted, that axis will not be affected.
  4635. 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`).
  4636. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4637. #### Usage
  4638. G92 [ X | Y | Z | E ]
  4639. #### Parameters
  4640. - `X` - new X axis position
  4641. - `Y` - new Y axis position
  4642. - `Z` - new Z axis position
  4643. - `E` - new extruder position
  4644. */
  4645. case 92: {
  4646. gcode_G92();
  4647. }
  4648. break;
  4649. #ifdef PRUSA_FARM
  4650. /*!
  4651. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4652. Enable Prusa-specific Farm functions and g-code.
  4653. See Internal Prusa commands.
  4654. */
  4655. case 98:
  4656. farm_gcode_g98();
  4657. break;
  4658. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4659. Disables Prusa-specific Farm functions and g-code.
  4660. */
  4661. case 99:
  4662. farm_gcode_g99();
  4663. break;
  4664. #endif //PRUSA_FARM
  4665. default:
  4666. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4667. }
  4668. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4669. gcode_in_progress = 0;
  4670. } // end if(code_seen('G'))
  4671. /*!
  4672. ### End of G-Codes
  4673. */
  4674. /*!
  4675. ---------------------------------------------------------------------------------
  4676. # M Commands
  4677. */
  4678. else if(code_seen('M'))
  4679. {
  4680. int index;
  4681. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4682. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4683. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4684. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4685. } else
  4686. {
  4687. mcode_in_progress = code_value_short();
  4688. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4689. switch(mcode_in_progress)
  4690. {
  4691. /*!
  4692. ### 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>
  4693. */
  4694. case 17:
  4695. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4696. enable_x();
  4697. enable_y();
  4698. enable_z();
  4699. enable_e0();
  4700. enable_e1();
  4701. enable_e2();
  4702. break;
  4703. #ifdef SDSUPPORT
  4704. /*!
  4705. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4706. #### Usage
  4707. M20 [ L | T ]
  4708. #### Parameters
  4709. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4710. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4711. */
  4712. case 20:
  4713. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4714. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4715. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4716. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4717. break;
  4718. /*!
  4719. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4720. */
  4721. case 21:
  4722. card.initsd();
  4723. break;
  4724. /*!
  4725. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4726. */
  4727. case 22:
  4728. card.release();
  4729. break;
  4730. /*!
  4731. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4732. #### Usage
  4733. M23 [filename]
  4734. */
  4735. case 23:
  4736. starpos = (strchr(strchr_pointer + 4,'*'));
  4737. if(starpos!=NULL)
  4738. *(starpos)='\0';
  4739. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4740. break;
  4741. /*!
  4742. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4743. */
  4744. case 24:
  4745. if (isPrintPaused)
  4746. lcd_resume_print();
  4747. else
  4748. {
  4749. if (!card.get_sdpos())
  4750. {
  4751. // A new print has started from scratch, reset stats
  4752. failstats_reset_print();
  4753. sdpos_atomic = 0;
  4754. #ifndef LA_NOCOMPAT
  4755. la10c_reset();
  4756. #endif
  4757. }
  4758. card.startFileprint();
  4759. starttime=_millis();
  4760. }
  4761. break;
  4762. /*!
  4763. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4764. Set position in SD card file to index in bytes.
  4765. This command is expected to be called after M23 and before M24.
  4766. Otherwise effect of this command is undefined.
  4767. #### Usage
  4768. M26 [ S ]
  4769. #### Parameters
  4770. - `S` - Index in bytes
  4771. */
  4772. case 26:
  4773. if(card.cardOK && code_seen('S')) {
  4774. long index = code_value_long();
  4775. card.setIndex(index);
  4776. // We don't disable interrupt during update of sdpos_atomic
  4777. // as we expect, that SD card print is not active in this moment
  4778. sdpos_atomic = index;
  4779. }
  4780. break;
  4781. /*!
  4782. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4783. #### Usage
  4784. M27 [ P ]
  4785. #### Parameters
  4786. - `P` - Show full SFN path instead of LFN only.
  4787. */
  4788. case 27:
  4789. card.getStatus(code_seen('P'));
  4790. break;
  4791. /*!
  4792. ### 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>
  4793. */
  4794. case 28:
  4795. starpos = (strchr(strchr_pointer + 4,'*'));
  4796. if(starpos != NULL){
  4797. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4798. strchr_pointer = strchr(npos,' ') + 1;
  4799. *(starpos) = '\0';
  4800. }
  4801. card.openFileWrite(strchr_pointer+4);
  4802. break;
  4803. /*! ### 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>
  4804. 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.
  4805. */
  4806. case 29:
  4807. //processed in write to file routine above
  4808. //card,saving = false;
  4809. break;
  4810. /*!
  4811. ### 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>
  4812. #### Usage
  4813. M30 [filename]
  4814. */
  4815. case 30:
  4816. if (card.cardOK){
  4817. card.closefile();
  4818. starpos = (strchr(strchr_pointer + 4,'*'));
  4819. if(starpos != NULL){
  4820. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4821. strchr_pointer = strchr(npos,' ') + 1;
  4822. *(starpos) = '\0';
  4823. }
  4824. card.removeFile(strchr_pointer + 4);
  4825. }
  4826. break;
  4827. /*!
  4828. ### 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>
  4829. @todo What are the parameters P and S for in M32?
  4830. */
  4831. case 32:
  4832. {
  4833. if(card.sdprinting) {
  4834. st_synchronize();
  4835. }
  4836. starpos = (strchr(strchr_pointer + 4,'*'));
  4837. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4838. if(namestartpos==NULL)
  4839. {
  4840. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4841. }
  4842. else
  4843. namestartpos++; //to skip the '!'
  4844. if(starpos!=NULL)
  4845. *(starpos)='\0';
  4846. bool call_procedure=(code_seen('P'));
  4847. if(strchr_pointer>namestartpos)
  4848. call_procedure=false; //false alert, 'P' found within filename
  4849. if( card.cardOK )
  4850. {
  4851. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4852. if(code_seen('S'))
  4853. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4854. card.setIndex(code_value_long());
  4855. card.startFileprint();
  4856. if(!call_procedure)
  4857. {
  4858. if(!card.get_sdpos())
  4859. {
  4860. // A new print has started from scratch, reset stats
  4861. failstats_reset_print();
  4862. sdpos_atomic = 0;
  4863. #ifndef LA_NOCOMPAT
  4864. la10c_reset();
  4865. #endif
  4866. }
  4867. starttime=_millis(); // procedure calls count as normal print time.
  4868. }
  4869. }
  4870. } break;
  4871. /*!
  4872. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4873. #### Usage
  4874. M928 [filename]
  4875. */
  4876. case 928:
  4877. starpos = (strchr(strchr_pointer + 5,'*'));
  4878. if(starpos != NULL){
  4879. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4880. strchr_pointer = strchr(npos,' ') + 1;
  4881. *(starpos) = '\0';
  4882. }
  4883. card.openLogFile(strchr_pointer+5);
  4884. break;
  4885. #endif //SDSUPPORT
  4886. /*!
  4887. ### 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>
  4888. */
  4889. case 31: //M31 take time since the start of the SD print or an M109 command
  4890. {
  4891. stoptime=_millis();
  4892. char time[30];
  4893. unsigned long t=(stoptime-starttime)/1000;
  4894. int sec,min;
  4895. min=t/60;
  4896. sec=t%60;
  4897. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4898. SERIAL_ECHO_START;
  4899. SERIAL_ECHOLN(time);
  4900. lcd_setstatus(time);
  4901. autotempShutdown();
  4902. }
  4903. break;
  4904. /*!
  4905. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4906. #### Usage
  4907. M42 [ P | S ]
  4908. #### Parameters
  4909. - `P` - Pin number.
  4910. - `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.
  4911. */
  4912. case 42:
  4913. if (code_seen('S'))
  4914. {
  4915. uint8_t pin_status = code_value_uint8();
  4916. int8_t pin_number = LED_PIN;
  4917. if (code_seen('P'))
  4918. pin_number = code_value_uint8();
  4919. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4920. {
  4921. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4922. {
  4923. pin_number = -1;
  4924. break;
  4925. }
  4926. }
  4927. #if defined(FAN_PIN) && FAN_PIN > -1
  4928. if (pin_number == FAN_PIN)
  4929. fanSpeed = pin_status;
  4930. #endif
  4931. if (pin_number > -1)
  4932. {
  4933. pinMode(pin_number, OUTPUT);
  4934. digitalWrite(pin_number, pin_status);
  4935. analogWrite(pin_number, pin_status);
  4936. }
  4937. }
  4938. break;
  4939. /*!
  4940. ### 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>
  4941. */
  4942. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4943. // Reset the baby step value and the baby step applied flag.
  4944. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4945. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4946. // Reset the skew and offset in both RAM and EEPROM.
  4947. reset_bed_offset_and_skew();
  4948. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4949. // the planner will not perform any adjustments in the XY plane.
  4950. // Wait for the motors to stop and update the current position with the absolute values.
  4951. world2machine_revert_to_uncorrected();
  4952. break;
  4953. /*!
  4954. ### 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>
  4955. #### Usage
  4956. M45 [ V ]
  4957. #### Parameters
  4958. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4959. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4960. */
  4961. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4962. {
  4963. int8_t verbosity_level = 0;
  4964. bool only_Z = code_seen('Z');
  4965. #ifdef SUPPORT_VERBOSITY
  4966. if (code_seen('V'))
  4967. {
  4968. // Just 'V' without a number counts as V1.
  4969. char c = strchr_pointer[1];
  4970. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4971. }
  4972. #endif //SUPPORT_VERBOSITY
  4973. gcode_M45(only_Z, verbosity_level);
  4974. }
  4975. break;
  4976. /*!
  4977. ### 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>
  4978. */
  4979. case 46:
  4980. {
  4981. // M46: Prusa3D: Show the assigned IP address.
  4982. if (card.ToshibaFlashAir_isEnabled()) {
  4983. uint8_t ip[4];
  4984. if (card.ToshibaFlashAir_GetIP(ip)) {
  4985. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  4986. SERIAL_PROTOCOL(uint8_t(ip[0]));
  4987. SERIAL_PROTOCOL('.');
  4988. SERIAL_PROTOCOL(uint8_t(ip[1]));
  4989. SERIAL_PROTOCOL('.');
  4990. SERIAL_PROTOCOL(uint8_t(ip[2]));
  4991. SERIAL_PROTOCOL('.');
  4992. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  4993. } else {
  4994. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  4995. }
  4996. } else {
  4997. SERIAL_PROTOCOLLNPGM("n/a");
  4998. }
  4999. break;
  5000. }
  5001. /*!
  5002. ### 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>
  5003. */
  5004. case 47:
  5005. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5006. lcd_diag_show_end_stops();
  5007. KEEPALIVE_STATE(IN_HANDLER);
  5008. break;
  5009. #if 0
  5010. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5011. {
  5012. // Disable the default update procedure of the display. We will do a modal dialog.
  5013. lcd_update_enable(false);
  5014. // Let the planner use the uncorrected coordinates.
  5015. mbl.reset();
  5016. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5017. // the planner will not perform any adjustments in the XY plane.
  5018. // Wait for the motors to stop and update the current position with the absolute values.
  5019. world2machine_revert_to_uncorrected();
  5020. // Move the print head close to the bed.
  5021. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5022. 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);
  5023. st_synchronize();
  5024. // Home in the XY plane.
  5025. set_destination_to_current();
  5026. int l_feedmultiply = setup_for_endstop_move();
  5027. home_xy();
  5028. int8_t verbosity_level = 0;
  5029. if (code_seen('V')) {
  5030. // Just 'V' without a number counts as V1.
  5031. char c = strchr_pointer[1];
  5032. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5033. }
  5034. bool success = scan_bed_induction_points(verbosity_level);
  5035. clean_up_after_endstop_move(l_feedmultiply);
  5036. // Print head up.
  5037. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5038. 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);
  5039. st_synchronize();
  5040. lcd_update_enable(true);
  5041. break;
  5042. }
  5043. #endif
  5044. #ifdef ENABLE_AUTO_BED_LEVELING
  5045. #ifdef Z_PROBE_REPEATABILITY_TEST
  5046. /*!
  5047. ### 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>
  5048. 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.
  5049. 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.
  5050. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5051. #### Usage
  5052. M48 [ n | X | Y | V | L ]
  5053. #### Parameters
  5054. - `n` - Number of samples. Valid values 4-50
  5055. - `X` - X position for samples
  5056. - `Y` - Y position for samples
  5057. - `V` - Verbose level. Valid values 1-4
  5058. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5059. */
  5060. case 48: // M48 Z-Probe repeatability
  5061. {
  5062. #if Z_MIN_PIN == -1
  5063. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5064. #endif
  5065. double sum=0.0;
  5066. double mean=0.0;
  5067. double sigma=0.0;
  5068. double sample_set[50];
  5069. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5070. double X_current, Y_current, Z_current;
  5071. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5072. if (code_seen('V') || code_seen('v')) {
  5073. verbose_level = code_value();
  5074. if (verbose_level<0 || verbose_level>4 ) {
  5075. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5076. goto Sigma_Exit;
  5077. }
  5078. }
  5079. if (verbose_level > 0) {
  5080. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5081. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5082. }
  5083. if (code_seen('n')) {
  5084. n_samples = code_value();
  5085. if (n_samples<4 || n_samples>50 ) {
  5086. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5087. goto Sigma_Exit;
  5088. }
  5089. }
  5090. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5091. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5092. Z_current = st_get_position_mm(Z_AXIS);
  5093. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5094. ext_position = st_get_position_mm(E_AXIS);
  5095. if (code_seen('X') || code_seen('x') ) {
  5096. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5097. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5098. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5099. goto Sigma_Exit;
  5100. }
  5101. }
  5102. if (code_seen('Y') || code_seen('y') ) {
  5103. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5104. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5105. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5106. goto Sigma_Exit;
  5107. }
  5108. }
  5109. if (code_seen('L') || code_seen('l') ) {
  5110. n_legs = code_value();
  5111. if ( n_legs==1 )
  5112. n_legs = 2;
  5113. if ( n_legs<0 || n_legs>15 ) {
  5114. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5115. goto Sigma_Exit;
  5116. }
  5117. }
  5118. //
  5119. // Do all the preliminary setup work. First raise the probe.
  5120. //
  5121. st_synchronize();
  5122. plan_bed_level_matrix.set_to_identity();
  5123. plan_buffer_line( X_current, Y_current, Z_start_location,
  5124. ext_position,
  5125. homing_feedrate[Z_AXIS]/60,
  5126. active_extruder);
  5127. st_synchronize();
  5128. //
  5129. // Now get everything to the specified probe point So we can safely do a probe to
  5130. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5131. // use that as a starting point for each probe.
  5132. //
  5133. if (verbose_level > 2)
  5134. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5135. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5136. ext_position,
  5137. homing_feedrate[X_AXIS]/60,
  5138. active_extruder);
  5139. st_synchronize();
  5140. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5141. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5142. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5143. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5144. //
  5145. // OK, do the inital probe to get us close to the bed.
  5146. // Then retrace the right amount and use that in subsequent probes
  5147. //
  5148. int l_feedmultiply = setup_for_endstop_move();
  5149. run_z_probe();
  5150. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5151. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5152. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5153. ext_position,
  5154. homing_feedrate[X_AXIS]/60,
  5155. active_extruder);
  5156. st_synchronize();
  5157. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5158. for( n=0; n<n_samples; n++) {
  5159. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5160. if ( n_legs) {
  5161. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5162. int rotational_direction, l;
  5163. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5164. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5165. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5166. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5167. //SERIAL_ECHOPAIR(" theta: ",theta);
  5168. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5169. //SERIAL_PROTOCOLLNPGM("");
  5170. for( l=0; l<n_legs-1; l++) {
  5171. if (rotational_direction==1)
  5172. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5173. else
  5174. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5175. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5176. if ( radius<0.0 )
  5177. radius = -radius;
  5178. X_current = X_probe_location + cos(theta) * radius;
  5179. Y_current = Y_probe_location + sin(theta) * radius;
  5180. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5181. X_current = X_MIN_POS;
  5182. if ( X_current>X_MAX_POS)
  5183. X_current = X_MAX_POS;
  5184. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5185. Y_current = Y_MIN_POS;
  5186. if ( Y_current>Y_MAX_POS)
  5187. Y_current = Y_MAX_POS;
  5188. if (verbose_level>3 ) {
  5189. SERIAL_ECHOPAIR("x: ", X_current);
  5190. SERIAL_ECHOPAIR("y: ", Y_current);
  5191. SERIAL_PROTOCOLLNPGM("");
  5192. }
  5193. do_blocking_move_to( X_current, Y_current, Z_current );
  5194. }
  5195. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5196. }
  5197. int l_feedmultiply = setup_for_endstop_move();
  5198. run_z_probe();
  5199. sample_set[n] = current_position[Z_AXIS];
  5200. //
  5201. // Get the current mean for the data points we have so far
  5202. //
  5203. sum=0.0;
  5204. for( j=0; j<=n; j++) {
  5205. sum = sum + sample_set[j];
  5206. }
  5207. mean = sum / (double (n+1));
  5208. //
  5209. // Now, use that mean to calculate the standard deviation for the
  5210. // data points we have so far
  5211. //
  5212. sum=0.0;
  5213. for( j=0; j<=n; j++) {
  5214. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5215. }
  5216. sigma = sqrt( sum / (double (n+1)) );
  5217. if (verbose_level > 1) {
  5218. SERIAL_PROTOCOL(n+1);
  5219. SERIAL_PROTOCOL(" of ");
  5220. SERIAL_PROTOCOL(n_samples);
  5221. SERIAL_PROTOCOLPGM(" z: ");
  5222. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5223. }
  5224. if (verbose_level > 2) {
  5225. SERIAL_PROTOCOL(" mean: ");
  5226. SERIAL_PROTOCOL_F(mean,6);
  5227. SERIAL_PROTOCOL(" sigma: ");
  5228. SERIAL_PROTOCOL_F(sigma,6);
  5229. }
  5230. if (verbose_level > 0)
  5231. SERIAL_PROTOCOLPGM("\n");
  5232. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5233. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5234. st_synchronize();
  5235. }
  5236. _delay(1000);
  5237. clean_up_after_endstop_move(l_feedmultiply);
  5238. // enable_endstops(true);
  5239. if (verbose_level > 0) {
  5240. SERIAL_PROTOCOLPGM("Mean: ");
  5241. SERIAL_PROTOCOL_F(mean, 6);
  5242. SERIAL_PROTOCOLPGM("\n");
  5243. }
  5244. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5245. SERIAL_PROTOCOL_F(sigma, 6);
  5246. SERIAL_PROTOCOLPGM("\n\n");
  5247. Sigma_Exit:
  5248. break;
  5249. }
  5250. #endif // Z_PROBE_REPEATABILITY_TEST
  5251. #endif // ENABLE_AUTO_BED_LEVELING
  5252. /*!
  5253. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5254. #### Usage
  5255. M73 [ P | R | Q | S | C | D ]
  5256. #### Parameters
  5257. - `P` - Percent in normal mode
  5258. - `R` - Time remaining in normal mode
  5259. - `Q` - Percent in silent mode
  5260. - `S` - Time in silent mode
  5261. - `C` - Time to change/pause/user interaction in normal mode
  5262. - `D` - Time to change/pause/user interaction in silent mode
  5263. */
  5264. case 73: //M73 show percent done, time remaining and time to change/pause
  5265. {
  5266. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5267. if(code_seen('R')) print_time_remaining_normal = code_value();
  5268. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5269. if(code_seen('S')) print_time_remaining_silent = code_value();
  5270. if(code_seen('C')){
  5271. float print_time_to_change_normal_f = code_value_float();
  5272. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5273. }
  5274. if(code_seen('D')){
  5275. float print_time_to_change_silent_f = code_value_float();
  5276. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5277. }
  5278. {
  5279. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5280. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5281. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5282. }
  5283. break;
  5284. }
  5285. /*!
  5286. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5287. #### Usage
  5288. M104 [ S ]
  5289. #### Parameters
  5290. - `S` - Target temperature
  5291. */
  5292. case 104: // M104
  5293. {
  5294. uint8_t extruder;
  5295. if(setTargetedHotend(104,extruder)){
  5296. break;
  5297. }
  5298. if (code_seen('S'))
  5299. {
  5300. setTargetHotendSafe(code_value(), extruder);
  5301. }
  5302. break;
  5303. }
  5304. /*!
  5305. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5306. It is processed much earlier as to bypass the cmdqueue.
  5307. */
  5308. case 112:
  5309. kill(MSG_M112_KILL, 3);
  5310. break;
  5311. /*!
  5312. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5313. #### Usage
  5314. M140 [ S ]
  5315. #### Parameters
  5316. - `S` - Target temperature
  5317. */
  5318. case 140:
  5319. if (code_seen('S')) setTargetBed(code_value());
  5320. break;
  5321. /*!
  5322. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5323. Prints temperatures:
  5324. - `T:` - Hotend (actual / target)
  5325. - `B:` - Bed (actual / target)
  5326. - `Tx:` - x Tool (actual / target)
  5327. - `@:` - Hotend power
  5328. - `B@:` - Bed power
  5329. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5330. - `A:` - Ambient actual (only MK3/s)
  5331. _Example:_
  5332. 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
  5333. */
  5334. case 105:
  5335. {
  5336. uint8_t extruder;
  5337. if(setTargetedHotend(105, extruder)){
  5338. break;
  5339. }
  5340. SERIAL_PROTOCOLPGM("ok ");
  5341. gcode_M105(extruder);
  5342. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5343. cmdbuffer_front_already_processed = true;
  5344. break;
  5345. }
  5346. #if defined(AUTO_REPORT)
  5347. /*!
  5348. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5349. #### Usage
  5350. M155 [ S ] [ C ]
  5351. #### Parameters
  5352. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5353. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5354. bit 0 = Auto-report temperatures
  5355. bit 1 = Auto-report fans
  5356. bit 2 = Auto-report position
  5357. bit 3 = free
  5358. bit 4 = free
  5359. bit 5 = free
  5360. bit 6 = free
  5361. bit 7 = free
  5362. */
  5363. case 155:
  5364. {
  5365. if (code_seen('S')){
  5366. autoReportFeatures.SetPeriod( code_value_uint8() );
  5367. }
  5368. if (code_seen('C')){
  5369. autoReportFeatures.SetMask(code_value_uint8());
  5370. } else{
  5371. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5372. }
  5373. }
  5374. break;
  5375. #endif //AUTO_REPORT
  5376. /*!
  5377. ### 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>
  5378. #### Usage
  5379. M104 [ B | R | S ]
  5380. #### Parameters (not mandatory)
  5381. - `S` - Set extruder temperature
  5382. - `R` - Set extruder temperature
  5383. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5384. Parameters S and R are treated identically.
  5385. Command always waits for both cool down and heat up.
  5386. If no parameters are supplied waits for previously set extruder temperature.
  5387. */
  5388. case 109:
  5389. {
  5390. uint8_t extruder;
  5391. if(setTargetedHotend(109, extruder)){
  5392. break;
  5393. }
  5394. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5395. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5396. prusa_statistics(1);
  5397. #ifdef AUTOTEMP
  5398. autotemp_enabled=false;
  5399. #endif
  5400. if (code_seen('S')) {
  5401. setTargetHotendSafe(code_value(), extruder);
  5402. } else if (code_seen('R')) {
  5403. setTargetHotendSafe(code_value(), extruder);
  5404. }
  5405. #ifdef AUTOTEMP
  5406. if (code_seen('S')) autotemp_min=code_value();
  5407. if (code_seen('B')) autotemp_max=code_value();
  5408. if (code_seen('F'))
  5409. {
  5410. autotemp_factor=code_value();
  5411. autotemp_enabled=true;
  5412. }
  5413. #endif
  5414. codenum = _millis();
  5415. /* See if we are heating up or cooling down */
  5416. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5417. cancel_heatup = false;
  5418. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5419. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5420. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5421. prusa_statistics(2);
  5422. //starttime=_millis();
  5423. previous_millis_cmd.start();
  5424. }
  5425. break;
  5426. /*!
  5427. ### 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>
  5428. #### Usage
  5429. M190 [ R | S ]
  5430. #### Parameters (not mandatory)
  5431. - `S` - Set extruder temperature and wait for heating
  5432. - `R` - Set extruder temperature and wait for heating or cooling
  5433. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5434. */
  5435. case 190:
  5436. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5437. {
  5438. bool CooldownNoWait = false;
  5439. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5440. heating_status = HeatingStatus::BED_HEATING;
  5441. prusa_statistics(1);
  5442. if (code_seen('S'))
  5443. {
  5444. setTargetBed(code_value());
  5445. CooldownNoWait = true;
  5446. }
  5447. else if (code_seen('R'))
  5448. {
  5449. setTargetBed(code_value());
  5450. }
  5451. codenum = _millis();
  5452. cancel_heatup = false;
  5453. target_direction = isHeatingBed(); // true if heating, false if cooling
  5454. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5455. {
  5456. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5457. {
  5458. if (!farm_mode) {
  5459. float tt = degHotend(active_extruder);
  5460. SERIAL_PROTOCOLPGM("T:");
  5461. SERIAL_PROTOCOL(tt);
  5462. SERIAL_PROTOCOLPGM(" E:");
  5463. SERIAL_PROTOCOL((int)active_extruder);
  5464. SERIAL_PROTOCOLPGM(" B:");
  5465. SERIAL_PROTOCOL_F(degBed(), 1);
  5466. SERIAL_PROTOCOLLN();
  5467. }
  5468. codenum = _millis();
  5469. }
  5470. manage_heater();
  5471. manage_inactivity();
  5472. lcd_update(0);
  5473. }
  5474. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5475. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5476. previous_millis_cmd.start();
  5477. }
  5478. #endif
  5479. break;
  5480. #if defined(FAN_PIN) && FAN_PIN > -1
  5481. /*!
  5482. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5483. #### Usage
  5484. M106 [ S ]
  5485. #### Parameters
  5486. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5487. */
  5488. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5489. if (code_seen('S')){
  5490. fanSpeed = code_value_uint8();
  5491. }
  5492. else {
  5493. fanSpeed = 255;
  5494. }
  5495. break;
  5496. /*!
  5497. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5498. */
  5499. case 107:
  5500. fanSpeed = 0;
  5501. break;
  5502. #endif //FAN_PIN
  5503. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5504. /*!
  5505. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5506. Only works if the firmware is compiled with PS_ON_PIN defined.
  5507. */
  5508. case 80:
  5509. SET_OUTPUT(PS_ON_PIN); //GND
  5510. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5511. // If you have a switch on suicide pin, this is useful
  5512. // if you want to start another print with suicide feature after
  5513. // a print without suicide...
  5514. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5515. SET_OUTPUT(SUICIDE_PIN);
  5516. WRITE(SUICIDE_PIN, HIGH);
  5517. #endif
  5518. powersupply = true;
  5519. LCD_MESSAGERPGM(MSG_WELCOME);
  5520. lcd_update(0);
  5521. break;
  5522. /*!
  5523. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5524. Only works if the firmware is compiled with PS_ON_PIN defined.
  5525. */
  5526. case 81:
  5527. disable_heater();
  5528. st_synchronize();
  5529. disable_e0();
  5530. disable_e1();
  5531. disable_e2();
  5532. finishAndDisableSteppers();
  5533. fanSpeed = 0;
  5534. _delay(1000); // Wait a little before to switch off
  5535. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5536. st_synchronize();
  5537. suicide();
  5538. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5539. SET_OUTPUT(PS_ON_PIN);
  5540. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5541. #endif
  5542. powersupply = false;
  5543. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5544. lcd_update(0);
  5545. break;
  5546. #endif
  5547. /*!
  5548. ### 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>
  5549. Makes the extruder interpret extrusion as absolute positions.
  5550. */
  5551. case 82:
  5552. axis_relative_modes &= ~E_AXIS_MASK;
  5553. break;
  5554. /*!
  5555. ### 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>
  5556. Makes the extruder interpret extrusion values as relative positions.
  5557. */
  5558. case 83:
  5559. axis_relative_modes |= E_AXIS_MASK;
  5560. break;
  5561. /*!
  5562. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5563. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5564. This command can be used without any additional parameters. In that case all steppers are disabled.
  5565. 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.
  5566. M84 [ S | X | Y | Z | E ]
  5567. - `S` - Seconds
  5568. - `X` - X axis
  5569. - `Y` - Y axis
  5570. - `Z` - Z axis
  5571. - `E` - Extruder
  5572. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5573. Equal to M84 (compatibility)
  5574. */
  5575. case 18: //compatibility
  5576. case 84: // M84
  5577. if(code_seen('S')){
  5578. stepper_inactive_time = code_value() * 1000;
  5579. }
  5580. else
  5581. {
  5582. 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])));
  5583. if(all_axis)
  5584. {
  5585. st_synchronize();
  5586. disable_e0();
  5587. disable_e1();
  5588. disable_e2();
  5589. finishAndDisableSteppers();
  5590. }
  5591. else
  5592. {
  5593. st_synchronize();
  5594. if (code_seen('X')) disable_x();
  5595. if (code_seen('Y')) disable_y();
  5596. if (code_seen('Z')) disable_z();
  5597. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5598. if (code_seen('E')) {
  5599. disable_e0();
  5600. disable_e1();
  5601. disable_e2();
  5602. }
  5603. #endif
  5604. }
  5605. }
  5606. break;
  5607. /*!
  5608. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5609. #### Usage
  5610. M85 [ S ]
  5611. #### Parameters
  5612. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5613. */
  5614. case 85: // M85
  5615. if(code_seen('S')) {
  5616. max_inactive_time = code_value() * 1000;
  5617. }
  5618. break;
  5619. #ifdef SAFETYTIMER
  5620. /*!
  5621. ### 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>
  5622. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5623. #### Usage
  5624. M86 [ S ]
  5625. #### Parameters
  5626. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5627. */
  5628. case 86:
  5629. if (code_seen('S')) {
  5630. safetytimer_inactive_time = code_value() * 1000;
  5631. safetyTimer.start();
  5632. }
  5633. break;
  5634. #endif
  5635. /*!
  5636. ### 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>
  5637. 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)
  5638. #### Usage
  5639. M92 [ X | Y | Z | E ]
  5640. #### Parameters
  5641. - `X` - Steps per unit for the X drive
  5642. - `Y` - Steps per unit for the Y drive
  5643. - `Z` - Steps per unit for the Z drive
  5644. - `E` - Steps per unit for the extruder drive
  5645. */
  5646. case 92:
  5647. for(int8_t i=0; i < NUM_AXIS; i++)
  5648. {
  5649. if(code_seen(axis_codes[i]))
  5650. {
  5651. if(i == E_AXIS) { // E
  5652. float value = code_value();
  5653. if(value < 20.0) {
  5654. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5655. cs.max_jerk[E_AXIS] *= factor;
  5656. max_feedrate[i] *= factor;
  5657. axis_steps_per_sqr_second[i] *= factor;
  5658. }
  5659. cs.axis_steps_per_unit[i] = value;
  5660. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5661. fsensor.init();
  5662. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5663. }
  5664. else {
  5665. cs.axis_steps_per_unit[i] = code_value();
  5666. }
  5667. }
  5668. }
  5669. reset_acceleration_rates();
  5670. break;
  5671. /*!
  5672. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5673. Sets the line number in G-code
  5674. #### Usage
  5675. M110 [ N ]
  5676. #### Parameters
  5677. - `N` - Line number
  5678. */
  5679. case 110:
  5680. if (code_seen('N'))
  5681. gcode_LastN = code_value_long();
  5682. break;
  5683. /*!
  5684. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5685. 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).
  5686. #### Usage
  5687. M113 [ S ]
  5688. #### Parameters
  5689. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5690. */
  5691. case 113:
  5692. if (code_seen('S')) {
  5693. host_keepalive_interval = code_value_uint8();
  5694. // NOMORE(host_keepalive_interval, 60);
  5695. }
  5696. else {
  5697. SERIAL_ECHO_START;
  5698. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5699. SERIAL_PROTOCOLLN();
  5700. }
  5701. break;
  5702. /*!
  5703. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5704. Print the firmware info and capabilities
  5705. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5706. `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.
  5707. _Examples:_
  5708. `M115` results:
  5709. `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`
  5710. `M115 V` results:
  5711. `3.8.1`
  5712. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5713. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5714. #### Usage
  5715. M115 [ V | U ]
  5716. #### Parameters
  5717. - V - Report current installed firmware version
  5718. - U - Firmware version provided by G-code to be compared to current one.
  5719. */
  5720. case 115: // M115
  5721. if (code_seen('V')) {
  5722. // Report the Prusa version number.
  5723. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5724. } else if (code_seen('U')) {
  5725. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5726. // pause the print for 30s and ask the user to upgrade the firmware.
  5727. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5728. } else {
  5729. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5730. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5731. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5732. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5733. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5734. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5735. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5736. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5737. SERIAL_ECHOPGM(" UUID:");
  5738. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5739. #ifdef EXTENDED_CAPABILITIES_REPORT
  5740. extended_capabilities_report();
  5741. #endif //EXTENDED_CAPABILITIES_REPORT
  5742. }
  5743. break;
  5744. /*!
  5745. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5746. */
  5747. case 114:
  5748. gcode_M114();
  5749. break;
  5750. /*
  5751. M117 moved up to get the high priority
  5752. case 117: // M117 display message
  5753. starpos = (strchr(strchr_pointer + 5,'*'));
  5754. if(starpos!=NULL)
  5755. *(starpos)='\0';
  5756. lcd_setstatus(strchr_pointer + 5);
  5757. break;*/
  5758. #ifdef M120_M121_ENABLED
  5759. /*!
  5760. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5761. */
  5762. case 120:
  5763. enable_endstops(true) ;
  5764. break;
  5765. /*!
  5766. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5767. */
  5768. case 121:
  5769. enable_endstops(false) ;
  5770. break;
  5771. #endif //M120_M121_ENABLED
  5772. /*!
  5773. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5774. 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.
  5775. */
  5776. case 119:
  5777. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5778. SERIAL_PROTOCOLLN();
  5779. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5780. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5781. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5782. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5783. }else{
  5784. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5785. }
  5786. SERIAL_PROTOCOLLN();
  5787. #endif
  5788. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5789. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5790. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5791. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5792. }else{
  5793. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5794. }
  5795. SERIAL_PROTOCOLLN();
  5796. #endif
  5797. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5798. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5799. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5800. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5801. }else{
  5802. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5803. }
  5804. SERIAL_PROTOCOLLN();
  5805. #endif
  5806. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5807. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5808. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5809. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5810. }else{
  5811. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5812. }
  5813. SERIAL_PROTOCOLLN();
  5814. #endif
  5815. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5816. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5817. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5818. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5819. }else{
  5820. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5821. }
  5822. SERIAL_PROTOCOLLN();
  5823. #endif
  5824. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5825. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5826. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5827. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5828. }else{
  5829. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5830. }
  5831. SERIAL_PROTOCOLLN();
  5832. #endif
  5833. break;
  5834. //!@todo update for all axes, use for loop
  5835. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5836. /*!
  5837. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5838. This command is used to report fan speeds and fan pwm values.
  5839. #### Usage
  5840. M123
  5841. - E0: - Hotend fan speed in RPM
  5842. - PRN1: - Part cooling fans speed in RPM
  5843. - E0@: - Hotend fan PWM value
  5844. - PRN1@: -Part cooling fan PWM value
  5845. _Example:_
  5846. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5847. */
  5848. case 123:
  5849. gcode_M123();
  5850. break;
  5851. #endif //FANCHECK and TACH_0 and TACH_1
  5852. #ifdef BLINKM
  5853. /*!
  5854. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5855. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5856. #### Usage
  5857. M150 [ R | U | B ]
  5858. #### Parameters
  5859. - `R` - Red color value
  5860. - `U` - Green color value. It is NOT `G`!
  5861. - `B` - Blue color value
  5862. */
  5863. case 150:
  5864. {
  5865. byte red;
  5866. byte grn;
  5867. byte blu;
  5868. if(code_seen('R')) red = code_value();
  5869. if(code_seen('U')) grn = code_value();
  5870. if(code_seen('B')) blu = code_value();
  5871. SendColors(red,grn,blu);
  5872. }
  5873. break;
  5874. #endif //BLINKM
  5875. /*!
  5876. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5877. #### Usage
  5878. M200 [ D | T ]
  5879. #### Parameters
  5880. - `D` - Diameter in mm
  5881. - `T` - Number of extruder (MMUs)
  5882. */
  5883. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5884. {
  5885. uint8_t extruder = active_extruder;
  5886. if(code_seen('T')) {
  5887. extruder = code_value_uint8();
  5888. if(extruder >= EXTRUDERS) {
  5889. SERIAL_ECHO_START;
  5890. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5891. break;
  5892. }
  5893. }
  5894. if(code_seen('D')) {
  5895. float diameter = code_value();
  5896. if (diameter == 0.0) {
  5897. // setting any extruder filament size disables volumetric on the assumption that
  5898. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5899. // for all extruders
  5900. cs.volumetric_enabled = false;
  5901. } else {
  5902. cs.filament_size[extruder] = code_value();
  5903. // make sure all extruders have some sane value for the filament size
  5904. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5905. #if EXTRUDERS > 1
  5906. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5907. #if EXTRUDERS > 2
  5908. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5909. #endif
  5910. #endif
  5911. cs.volumetric_enabled = true;
  5912. }
  5913. } else {
  5914. //reserved for setting filament diameter via UFID or filament measuring device
  5915. break;
  5916. }
  5917. calculate_extruder_multipliers();
  5918. }
  5919. break;
  5920. /*!
  5921. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5922. For each axis individually.
  5923. ##### Usage
  5924. M201 [ X | Y | Z | E ]
  5925. ##### Parameters
  5926. - `X` - Acceleration for X axis in units/s^2
  5927. - `Y` - Acceleration for Y axis in units/s^2
  5928. - `Z` - Acceleration for Z axis in units/s^2
  5929. - `E` - Acceleration for the active or specified extruder in units/s^2
  5930. */
  5931. case 201:
  5932. for (int8_t i = 0; i < NUM_AXIS; i++)
  5933. {
  5934. if (code_seen(axis_codes[i]))
  5935. {
  5936. unsigned long val = code_value();
  5937. #ifdef TMC2130
  5938. unsigned long val_silent = val;
  5939. if ((i == X_AXIS) || (i == Y_AXIS))
  5940. {
  5941. if (val > NORMAL_MAX_ACCEL_XY)
  5942. val = NORMAL_MAX_ACCEL_XY;
  5943. if (val_silent > SILENT_MAX_ACCEL_XY)
  5944. val_silent = SILENT_MAX_ACCEL_XY;
  5945. }
  5946. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5947. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5948. #else //TMC2130
  5949. max_acceleration_units_per_sq_second[i] = val;
  5950. #endif //TMC2130
  5951. }
  5952. }
  5953. // 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)
  5954. reset_acceleration_rates();
  5955. break;
  5956. #if 0 // Not used for Sprinter/grbl gen6
  5957. case 202: // M202
  5958. for(int8_t i=0; i < NUM_AXIS; i++) {
  5959. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5960. }
  5961. break;
  5962. #endif
  5963. /*!
  5964. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5965. For each axis individually.
  5966. ##### Usage
  5967. M203 [ X | Y | Z | E ]
  5968. ##### Parameters
  5969. - `X` - Maximum feedrate for X axis
  5970. - `Y` - Maximum feedrate for Y axis
  5971. - `Z` - Maximum feedrate for Z axis
  5972. - `E` - Maximum feedrate for extruder drives
  5973. */
  5974. case 203: // M203 max feedrate mm/sec
  5975. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5976. {
  5977. if (code_seen(axis_codes[i]))
  5978. {
  5979. float val = code_value();
  5980. #ifdef TMC2130
  5981. float val_silent = val;
  5982. if ((i == X_AXIS) || (i == Y_AXIS))
  5983. {
  5984. if (val > NORMAL_MAX_FEEDRATE_XY)
  5985. val = NORMAL_MAX_FEEDRATE_XY;
  5986. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5987. val_silent = SILENT_MAX_FEEDRATE_XY;
  5988. }
  5989. cs.max_feedrate_normal[i] = val;
  5990. cs.max_feedrate_silent[i] = val_silent;
  5991. #else //TMC2130
  5992. max_feedrate[i] = val;
  5993. #endif //TMC2130
  5994. }
  5995. }
  5996. break;
  5997. /*!
  5998. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  5999. #### Old format:
  6000. ##### Usage
  6001. M204 [ S | T ]
  6002. ##### Parameters
  6003. - `S` - normal moves
  6004. - `T` - filmanent only moves
  6005. #### New format:
  6006. ##### Usage
  6007. M204 [ P | R | T ]
  6008. ##### Parameters
  6009. - `P` - printing moves
  6010. - `R` - filmanent only moves
  6011. - `T` - travel moves (as of now T is ignored)
  6012. */
  6013. case 204:
  6014. {
  6015. if(code_seen('S')) {
  6016. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6017. // and it is also generated by Slic3r to control acceleration per extrusion type
  6018. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6019. cs.acceleration = cs.travel_acceleration = code_value();
  6020. // Interpret the T value as retract acceleration in the old Marlin format.
  6021. if(code_seen('T'))
  6022. cs.retract_acceleration = code_value();
  6023. } else {
  6024. // New acceleration format, compatible with the upstream Marlin.
  6025. if(code_seen('P'))
  6026. cs.acceleration = code_value();
  6027. if(code_seen('R'))
  6028. cs.retract_acceleration = code_value();
  6029. if(code_seen('T'))
  6030. cs.travel_acceleration = code_value();
  6031. }
  6032. }
  6033. break;
  6034. /*!
  6035. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6036. Set some advanced settings related to movement.
  6037. #### Usage
  6038. M205 [ S | T | B | X | Y | Z | E ]
  6039. #### Parameters
  6040. - `S` - Minimum feedrate for print moves (unit/s)
  6041. - `T` - Minimum feedrate for travel moves (units/s)
  6042. - `B` - Minimum segment time (us)
  6043. - `X` - Maximum X jerk (units/s)
  6044. - `Y` - Maximum Y jerk (units/s)
  6045. - `Z` - Maximum Z jerk (units/s)
  6046. - `E` - Maximum E jerk (units/s)
  6047. */
  6048. case 205:
  6049. {
  6050. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6051. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6052. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6053. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6054. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6055. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6056. if(code_seen('E'))
  6057. {
  6058. float e = code_value();
  6059. #ifndef LA_NOCOMPAT
  6060. e = la10c_jerk(e);
  6061. #endif
  6062. cs.max_jerk[E_AXIS] = e;
  6063. }
  6064. }
  6065. break;
  6066. /*!
  6067. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6068. #### Usage
  6069. M206 [ X | Y | Z ]
  6070. #### Parameters
  6071. - `X` - X axis offset
  6072. - `Y` - Y axis offset
  6073. - `Z` - Z axis offset
  6074. */
  6075. case 206:
  6076. for(uint8_t i=0; i < 3; i++)
  6077. {
  6078. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6079. }
  6080. break;
  6081. #ifdef FWRETRACT
  6082. /*!
  6083. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6084. #### Usage
  6085. M207 [ S | F | Z ]
  6086. #### Parameters
  6087. - `S` - positive length to retract, in mm
  6088. - `F` - retraction feedrate, in mm/min
  6089. - `Z` - additional zlift/hop
  6090. */
  6091. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6092. {
  6093. if(code_seen('S'))
  6094. {
  6095. cs.retract_length = code_value() ;
  6096. }
  6097. if(code_seen('F'))
  6098. {
  6099. cs.retract_feedrate = code_value()/60 ;
  6100. }
  6101. if(code_seen('Z'))
  6102. {
  6103. cs.retract_zlift = code_value() ;
  6104. }
  6105. }break;
  6106. /*!
  6107. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6108. #### Usage
  6109. M208 [ S | F ]
  6110. #### Parameters
  6111. - `S` - positive length surplus to the M207 Snnn, in mm
  6112. - `F` - feedrate, in mm/sec
  6113. */
  6114. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6115. {
  6116. if(code_seen('S'))
  6117. {
  6118. cs.retract_recover_length = code_value() ;
  6119. }
  6120. if(code_seen('F'))
  6121. {
  6122. cs.retract_recover_feedrate = code_value()/60 ;
  6123. }
  6124. }break;
  6125. /*!
  6126. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6127. 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.
  6128. #### Usage
  6129. M209 [ S ]
  6130. #### Parameters
  6131. - `S` - 1=true or 0=false
  6132. */
  6133. 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.
  6134. {
  6135. if(code_seen('S'))
  6136. {
  6137. switch(code_value_uint8())
  6138. {
  6139. case 0:
  6140. {
  6141. cs.autoretract_enabled=false;
  6142. retracted[0]=false;
  6143. #if EXTRUDERS > 1
  6144. retracted[1]=false;
  6145. #endif
  6146. #if EXTRUDERS > 2
  6147. retracted[2]=false;
  6148. #endif
  6149. }break;
  6150. case 1:
  6151. {
  6152. cs.autoretract_enabled=true;
  6153. retracted[0]=false;
  6154. #if EXTRUDERS > 1
  6155. retracted[1]=false;
  6156. #endif
  6157. #if EXTRUDERS > 2
  6158. retracted[2]=false;
  6159. #endif
  6160. }break;
  6161. default:
  6162. SERIAL_ECHO_START;
  6163. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6164. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6165. SERIAL_ECHOLNPGM("\"(1)");
  6166. }
  6167. }
  6168. }break;
  6169. #endif // FWRETRACT
  6170. /*!
  6171. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6172. #### Usage
  6173. M214 [P] [S] [N] [R] [F]
  6174. #### Parameters
  6175. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6176. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6177. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6178. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6179. except when the results in segment lengths greater than or less than the minimum
  6180. and maximum segment length. Set to 0 to disable.
  6181. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6182. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6183. */
  6184. 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>
  6185. {
  6186. // Extract all possible parameters if they appear
  6187. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6188. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6189. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6190. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6191. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6192. // 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
  6193. if (p <=0 || s < 0 || p < s)
  6194. {
  6195. // Should we display some error here?
  6196. break;
  6197. }
  6198. cs.mm_per_arc_segment = p;
  6199. cs.min_mm_per_arc_segment = s;
  6200. cs.n_arc_correction = n;
  6201. cs.min_arc_segments = r;
  6202. cs.arc_segments_per_sec = f;
  6203. }break;
  6204. #if EXTRUDERS > 1
  6205. /*!
  6206. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6207. 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.
  6208. #### Usage
  6209. M218 [ X | Y ]
  6210. #### Parameters
  6211. - `X` - X offset
  6212. - `Y` - Y offset
  6213. */
  6214. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6215. {
  6216. uint8_t extruder;
  6217. if(setTargetedHotend(218, extruder)){
  6218. break;
  6219. }
  6220. if(code_seen('X'))
  6221. {
  6222. extruder_offset[X_AXIS][extruder] = code_value();
  6223. }
  6224. if(code_seen('Y'))
  6225. {
  6226. extruder_offset[Y_AXIS][extruder] = code_value();
  6227. }
  6228. SERIAL_ECHO_START;
  6229. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6230. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6231. {
  6232. SERIAL_ECHO(" ");
  6233. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6234. SERIAL_ECHO(",");
  6235. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6236. }
  6237. SERIAL_ECHOLN("");
  6238. }break;
  6239. #endif
  6240. /*!
  6241. ### 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>
  6242. #### Usage
  6243. M220 [ B | S | R ]
  6244. #### Parameters
  6245. - `B` - Backup current speed factor
  6246. - `S` - Speed factor override percentage (0..100 or higher)
  6247. - `R` - Restore previous speed factor
  6248. */
  6249. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6250. {
  6251. bool codesWereSeen = false;
  6252. if (code_seen('B')) //backup current speed factor
  6253. {
  6254. saved_feedmultiply_mm = feedmultiply;
  6255. codesWereSeen = true;
  6256. }
  6257. if (code_seen('S'))
  6258. {
  6259. feedmultiply = code_value_short();
  6260. codesWereSeen = true;
  6261. }
  6262. if (code_seen('R')) //restore previous feedmultiply
  6263. {
  6264. feedmultiply = saved_feedmultiply_mm;
  6265. codesWereSeen = true;
  6266. }
  6267. if (!codesWereSeen)
  6268. {
  6269. printf_P(PSTR("%i%%\n"), feedmultiply);
  6270. }
  6271. }
  6272. break;
  6273. /*!
  6274. ### 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>
  6275. #### Usage
  6276. M221 [ S | T ]
  6277. #### Parameters
  6278. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6279. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6280. */
  6281. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6282. {
  6283. if (code_seen('S'))
  6284. {
  6285. int tmp_code = code_value_short();
  6286. if (code_seen('T'))
  6287. {
  6288. uint8_t extruder;
  6289. if (setTargetedHotend(221, extruder))
  6290. break;
  6291. extruder_multiply[extruder] = tmp_code;
  6292. }
  6293. else
  6294. {
  6295. extrudemultiply = tmp_code ;
  6296. }
  6297. }
  6298. else
  6299. {
  6300. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6301. }
  6302. calculate_extruder_multipliers();
  6303. }
  6304. break;
  6305. /*!
  6306. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6307. Wait until the specified pin reaches the state required
  6308. #### Usage
  6309. M226 [ P | S ]
  6310. #### Parameters
  6311. - `P` - pin number
  6312. - `S` - pin state
  6313. */
  6314. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6315. {
  6316. if(code_seen('P')){
  6317. int pin_number = code_value_short(); // pin number
  6318. int pin_state = -1; // required pin state - default is inverted
  6319. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6320. if(pin_state >= -1 && pin_state <= 1){
  6321. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6322. {
  6323. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6324. {
  6325. pin_number = -1;
  6326. break;
  6327. }
  6328. }
  6329. if (pin_number > -1)
  6330. {
  6331. int target = LOW;
  6332. st_synchronize();
  6333. pinMode(pin_number, INPUT);
  6334. switch(pin_state){
  6335. case 1:
  6336. target = HIGH;
  6337. break;
  6338. case 0:
  6339. target = LOW;
  6340. break;
  6341. case -1:
  6342. target = !digitalRead(pin_number);
  6343. break;
  6344. }
  6345. while(digitalRead(pin_number) != target){
  6346. manage_heater();
  6347. manage_inactivity();
  6348. lcd_update(0);
  6349. }
  6350. }
  6351. }
  6352. }
  6353. }
  6354. break;
  6355. #if NUM_SERVOS > 0
  6356. /*!
  6357. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6358. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6359. #### Usage
  6360. M280 [ P | S ]
  6361. #### Parameters
  6362. - `P` - Servo index (id)
  6363. - `S` - Target position
  6364. */
  6365. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6366. {
  6367. int servo_index = -1;
  6368. int servo_position = 0;
  6369. if (code_seen('P'))
  6370. servo_index = code_value();
  6371. if (code_seen('S')) {
  6372. servo_position = code_value();
  6373. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6374. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6375. servos[servo_index].attach(0);
  6376. #endif
  6377. servos[servo_index].write(servo_position);
  6378. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6379. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6380. servos[servo_index].detach();
  6381. #endif
  6382. }
  6383. else {
  6384. SERIAL_ECHO_START;
  6385. SERIAL_ECHO("Servo ");
  6386. SERIAL_ECHO(servo_index);
  6387. SERIAL_ECHOLN(" out of range");
  6388. }
  6389. }
  6390. else if (servo_index >= 0) {
  6391. SERIAL_PROTOCOL(MSG_OK);
  6392. SERIAL_PROTOCOL(" Servo ");
  6393. SERIAL_PROTOCOL(servo_index);
  6394. SERIAL_PROTOCOL(": ");
  6395. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6396. }
  6397. }
  6398. break;
  6399. #endif // NUM_SERVOS > 0
  6400. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6401. /*!
  6402. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6403. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6404. #### Usage
  6405. M300 [ S | P ]
  6406. #### Parameters
  6407. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6408. - `P` - duration in milliseconds
  6409. */
  6410. case 300: // M300
  6411. {
  6412. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6413. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6414. #if BEEPER > 0
  6415. if (beepP > 0)
  6416. Sound_MakeCustom(beepP,beepS,false);
  6417. #endif
  6418. }
  6419. break;
  6420. #endif // M300
  6421. #ifdef PIDTEMP
  6422. /*!
  6423. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6424. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6425. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6426. #### Usage
  6427. M301 [ P | I | D ]
  6428. #### Parameters
  6429. - `P` - proportional (Kp)
  6430. - `I` - integral (Ki)
  6431. - `D` - derivative (Kd)
  6432. */
  6433. case 301:
  6434. {
  6435. if(code_seen('P')) cs.Kp = code_value();
  6436. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6437. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6438. updatePID();
  6439. SERIAL_PROTOCOLRPGM(MSG_OK);
  6440. SERIAL_PROTOCOLPGM(" p:");
  6441. SERIAL_PROTOCOL(cs.Kp);
  6442. SERIAL_PROTOCOLPGM(" i:");
  6443. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6444. SERIAL_PROTOCOLPGM(" d:");
  6445. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6446. SERIAL_PROTOCOLLN();
  6447. }
  6448. break;
  6449. #endif //PIDTEMP
  6450. #ifdef PIDTEMPBED
  6451. /*!
  6452. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6453. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6454. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6455. #### Usage
  6456. M304 [ P | I | D ]
  6457. #### Parameters
  6458. - `P` - proportional (Kp)
  6459. - `I` - integral (Ki)
  6460. - `D` - derivative (Kd)
  6461. */
  6462. case 304:
  6463. {
  6464. if(code_seen('P')) cs.bedKp = code_value();
  6465. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6466. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6467. updatePID();
  6468. SERIAL_PROTOCOLRPGM(MSG_OK);
  6469. SERIAL_PROTOCOLPGM(" p:");
  6470. SERIAL_PROTOCOL(cs.bedKp);
  6471. SERIAL_PROTOCOLPGM(" i:");
  6472. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6473. SERIAL_PROTOCOLPGM(" d:");
  6474. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6475. }
  6476. break;
  6477. #endif //PIDTEMP
  6478. /*!
  6479. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6480. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6481. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6482. */
  6483. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6484. {
  6485. #ifdef CHDK
  6486. SET_OUTPUT(CHDK);
  6487. WRITE(CHDK, HIGH);
  6488. chdkHigh = _millis();
  6489. chdkActive = true;
  6490. #else
  6491. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6492. const uint8_t NUM_PULSES=16;
  6493. const float PULSE_LENGTH=0.01524;
  6494. for(int i=0; i < NUM_PULSES; i++) {
  6495. WRITE(PHOTOGRAPH_PIN, HIGH);
  6496. _delay_ms(PULSE_LENGTH);
  6497. WRITE(PHOTOGRAPH_PIN, LOW);
  6498. _delay_ms(PULSE_LENGTH);
  6499. }
  6500. _delay(7.33);
  6501. for(int i=0; i < NUM_PULSES; i++) {
  6502. WRITE(PHOTOGRAPH_PIN, HIGH);
  6503. _delay_ms(PULSE_LENGTH);
  6504. WRITE(PHOTOGRAPH_PIN, LOW);
  6505. _delay_ms(PULSE_LENGTH);
  6506. }
  6507. #endif
  6508. #endif //chdk end if
  6509. }
  6510. break;
  6511. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6512. /*!
  6513. ### 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>
  6514. 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.
  6515. #### Usage
  6516. M302 [ S ]
  6517. #### Parameters
  6518. - `S` - Cold extrude minimum temperature
  6519. */
  6520. case 302:
  6521. {
  6522. int temp = 0;
  6523. if (code_seen('S')) temp=code_value_short();
  6524. set_extrude_min_temp(temp);
  6525. }
  6526. break;
  6527. #endif
  6528. /*!
  6529. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6530. 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.
  6531. #### Usage
  6532. M303 [ E | S | C ]
  6533. #### Parameters
  6534. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6535. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6536. - `C` - Cycles, default `5`
  6537. */
  6538. case 303:
  6539. {
  6540. float temp = 150.0;
  6541. int e = 0;
  6542. int c = 5;
  6543. if (code_seen('E')) e = code_value_short();
  6544. if (e < 0)
  6545. temp = 70;
  6546. if (code_seen('S')) temp = code_value();
  6547. if (code_seen('C')) c = code_value_short();
  6548. PID_autotune(temp, e, c);
  6549. }
  6550. break;
  6551. #ifdef TEMP_MODEL
  6552. /*!
  6553. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6554. #### Usage
  6555. M310 ; report values
  6556. M310 [ A ] [ F ] ; autotune
  6557. M310 [ S ] ; set 0=disable 1=enable
  6558. M310 [ I ] [ R ] ; set resistance at index
  6559. M310 [ P | C ] ; set power, capacitance
  6560. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6561. M310 [ T ] ; set ambient temperature correction
  6562. #### Parameters
  6563. - `I` - resistance index position (0-15)
  6564. - `R` - resistance value at index (K/W; requires `I`)
  6565. - `P` - power (W)
  6566. - `C` - capacitance (J/K)
  6567. - `S` - set 0=disable 1=enable
  6568. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6569. - `E` - error threshold (K/s; default in variant)
  6570. - `W` - warning threshold (K/s; default in variant)
  6571. - `T` - ambient temperature correction (K; default in variant)
  6572. - `A` - autotune C+R values
  6573. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6574. */
  6575. case 310:
  6576. {
  6577. // parse all parameters
  6578. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6579. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6580. if(code_seen('C')) C = code_value();
  6581. if(code_seen('P')) P = code_value();
  6582. if(code_seen('I')) I = code_value_short();
  6583. if(code_seen('R')) R = code_value();
  6584. if(code_seen('S')) S = code_value_short();
  6585. if(code_seen('B')) B = code_value_short();
  6586. if(code_seen('E')) E = code_value();
  6587. if(code_seen('W')) W = code_value();
  6588. if(code_seen('T')) T = code_value();
  6589. if(code_seen('A')) A = code_value_short();
  6590. if(code_seen('F')) F = code_value_short();
  6591. // report values if nothing has been requested
  6592. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6593. temp_model_report_settings();
  6594. break;
  6595. }
  6596. // update all parameters
  6597. if(B >= 0) temp_model_set_warn_beep(B);
  6598. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6599. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6600. // enable the model last, if requested
  6601. if(S >= 0) temp_model_set_enabled(S);
  6602. // run autotune
  6603. if(A >= 0) temp_model_autotune(A, F > 0);
  6604. }
  6605. break;
  6606. #endif
  6607. /*!
  6608. ### 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>
  6609. Finishes all current moves and and thus clears the buffer.
  6610. Equivalent to `G4` with no parameters.
  6611. */
  6612. case 400:
  6613. {
  6614. st_synchronize();
  6615. }
  6616. break;
  6617. /*!
  6618. ### 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>
  6619. Currently three different materials are needed (default, flex and PVA).
  6620. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6621. #### Usage
  6622. M403 [ E | F ]
  6623. #### Parameters
  6624. - `E` - Extruder number. 0-indexed.
  6625. - `F` - Filament type
  6626. */
  6627. case 403:
  6628. {
  6629. // currently three different materials are needed (default, flex and PVA)
  6630. // add storing this information for different load/unload profiles etc. in the future
  6631. if (MMU2::mmu2.Enabled())
  6632. {
  6633. uint8_t extruder = 255;
  6634. uint8_t filament = FILAMENT_UNDEFINED;
  6635. if(code_seen('E')) extruder = code_value_uint8();
  6636. if(code_seen('F')) filament = code_value_uint8();
  6637. MMU2::mmu2.set_filament_type(extruder, filament);
  6638. }
  6639. }
  6640. break;
  6641. /*!
  6642. ### 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>
  6643. Save current parameters to EEPROM.
  6644. */
  6645. case 500:
  6646. {
  6647. Config_StoreSettings();
  6648. }
  6649. break;
  6650. /*!
  6651. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6652. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6653. */
  6654. case 501:
  6655. {
  6656. Config_RetrieveSettings();
  6657. }
  6658. break;
  6659. /*!
  6660. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6661. 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.
  6662. */
  6663. case 502:
  6664. {
  6665. Config_ResetDefault();
  6666. }
  6667. break;
  6668. /*!
  6669. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6670. 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.
  6671. */
  6672. case 503:
  6673. {
  6674. Config_PrintSettings();
  6675. }
  6676. break;
  6677. /*!
  6678. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6679. Resets the language to English.
  6680. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6681. */
  6682. case 509:
  6683. {
  6684. lang_reset();
  6685. SERIAL_ECHO_START;
  6686. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6687. }
  6688. break;
  6689. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6690. /*!
  6691. ### 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>
  6692. 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`.
  6693. #### Usage
  6694. M540 [ S ]
  6695. #### Parameters
  6696. - `S` - disabled=0, enabled=1
  6697. */
  6698. case 540:
  6699. {
  6700. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6701. }
  6702. break;
  6703. #endif
  6704. #ifdef ENABLE_AUTO_BED_LEVELING
  6705. /*!
  6706. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6707. 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.
  6708. 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.)
  6709. #### Usage
  6710. M851 [ Z ]
  6711. #### Parameters
  6712. - `Z` - Z offset probe to nozzle.
  6713. */
  6714. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6715. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6716. {
  6717. float value;
  6718. if (code_seen('Z'))
  6719. {
  6720. value = code_value();
  6721. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6722. {
  6723. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6724. SERIAL_ECHO_START;
  6725. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6726. SERIAL_PROTOCOLLN();
  6727. }
  6728. else
  6729. {
  6730. SERIAL_ECHO_START;
  6731. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6732. SERIAL_ECHORPGM(MSG_Z_MIN);
  6733. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6734. SERIAL_ECHORPGM(MSG_Z_MAX);
  6735. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6736. SERIAL_PROTOCOLLN();
  6737. }
  6738. }
  6739. else
  6740. {
  6741. SERIAL_ECHO_START;
  6742. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6743. SERIAL_ECHO(-cs.zprobe_zoffset);
  6744. SERIAL_PROTOCOLLN();
  6745. }
  6746. break;
  6747. }
  6748. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6749. #endif // ENABLE_AUTO_BED_LEVELING
  6750. /*!
  6751. ### 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>
  6752. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6753. If P is not specified nothing happens.
  6754. 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.
  6755. #### Usage
  6756. M552 [ P<IP_address> ]
  6757. #### Parameters
  6758. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6759. */
  6760. case 552:
  6761. {
  6762. if (code_seen('P'))
  6763. {
  6764. uint8_t valCnt = 0;
  6765. IP_address = 0;
  6766. do
  6767. {
  6768. *strchr_pointer = '*';
  6769. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6770. valCnt++;
  6771. } while ((valCnt < 4) && code_seen('.'));
  6772. if (valCnt != 4)
  6773. IP_address = 0;
  6774. }
  6775. } break;
  6776. #ifdef FILAMENTCHANGEENABLE
  6777. /*!
  6778. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6779. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6780. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6781. #### Usage
  6782. M600 [ X | Y | Z | E | L | AUTO ]
  6783. - `X` - X position, default 211
  6784. - `Y` - Y position, default 0
  6785. - `Z` - relative lift Z, default 2.
  6786. - `E` - initial retract, default -2
  6787. - `L` - later retract distance for removal, default -80
  6788. - `AUTO` - Automatically (only with MMU)
  6789. */
  6790. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6791. {
  6792. st_synchronize();
  6793. float x_position = current_position[X_AXIS];
  6794. float y_position = current_position[Y_AXIS];
  6795. float z_shift = 0; // is it necessary to be a float?
  6796. float e_shift_init = 0;
  6797. float e_shift_late = 0;
  6798. bool automatic = false;
  6799. //Retract extruder
  6800. if(code_seen('E'))
  6801. {
  6802. e_shift_init = code_value();
  6803. }
  6804. else
  6805. {
  6806. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6807. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6808. #endif
  6809. }
  6810. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6811. if (code_seen('L'))
  6812. {
  6813. e_shift_late = code_value();
  6814. }
  6815. else
  6816. {
  6817. #ifdef FILAMENTCHANGE_FINALRETRACT
  6818. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6819. #endif
  6820. }
  6821. //Lift Z
  6822. if(code_seen('Z'))
  6823. {
  6824. z_shift = code_value();
  6825. }
  6826. else
  6827. {
  6828. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6829. }
  6830. //Move XY to side
  6831. if(code_seen('X'))
  6832. {
  6833. x_position = code_value();
  6834. }
  6835. else
  6836. {
  6837. #ifdef FILAMENTCHANGE_XPOS
  6838. x_position = FILAMENTCHANGE_XPOS;
  6839. #endif
  6840. }
  6841. if(code_seen('Y'))
  6842. {
  6843. y_position = code_value();
  6844. }
  6845. else
  6846. {
  6847. #ifdef FILAMENTCHANGE_YPOS
  6848. y_position = FILAMENTCHANGE_YPOS ;
  6849. #endif
  6850. }
  6851. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6852. automatic = true;
  6853. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6854. }
  6855. break;
  6856. #endif //FILAMENTCHANGEENABLE
  6857. /*!
  6858. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6859. */
  6860. /*!
  6861. ### M125 - Pause print (TODO: not implemented)
  6862. */
  6863. /*!
  6864. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6865. */
  6866. case 25:
  6867. case 601:
  6868. {
  6869. if (!isPrintPaused) {
  6870. st_synchronize();
  6871. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6872. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6873. lcd_pause_print();
  6874. }
  6875. }
  6876. break;
  6877. /*!
  6878. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6879. */
  6880. case 602:
  6881. {
  6882. if (isPrintPaused) lcd_resume_print();
  6883. }
  6884. break;
  6885. /*!
  6886. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6887. */
  6888. case 603: {
  6889. lcd_print_stop();
  6890. }
  6891. break;
  6892. #ifdef PINDA_THERMISTOR
  6893. /*!
  6894. ### 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>
  6895. Wait for PINDA thermistor to reach target temperature
  6896. #### Usage
  6897. M860 [ S ]
  6898. #### Parameters
  6899. - `S` - Target temperature
  6900. */
  6901. case 860:
  6902. {
  6903. int set_target_pinda = 0;
  6904. if (code_seen('S')) {
  6905. set_target_pinda = code_value_short();
  6906. }
  6907. else {
  6908. break;
  6909. }
  6910. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6911. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6912. SERIAL_PROTOCOLLN(set_target_pinda);
  6913. codenum = _millis();
  6914. cancel_heatup = false;
  6915. bool is_pinda_cooling = false;
  6916. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6917. is_pinda_cooling = true;
  6918. }
  6919. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6920. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6921. {
  6922. SERIAL_PROTOCOLPGM("P:");
  6923. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6924. SERIAL_PROTOCOL('/');
  6925. SERIAL_PROTOCOLLN(set_target_pinda);
  6926. codenum = _millis();
  6927. }
  6928. manage_heater();
  6929. manage_inactivity();
  6930. lcd_update(0);
  6931. }
  6932. LCD_MESSAGERPGM(MSG_OK);
  6933. break;
  6934. }
  6935. /*!
  6936. ### 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>
  6937. Set compensation ustep value `S` for compensation table index `I`.
  6938. #### Usage
  6939. M861 [ ? | ! | Z | S | I ]
  6940. #### Parameters
  6941. - `?` - Print current EEPROM offset values
  6942. - `!` - Set factory default values
  6943. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6944. - `S` - Microsteps
  6945. - `I` - Table index
  6946. */
  6947. case 861: {
  6948. const char * const _header = PSTR("index, temp, ustep, um");
  6949. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6950. int16_t usteps = 0;
  6951. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6952. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6953. SERIAL_PROTOCOLLNRPGM(_header);
  6954. for (uint8_t i = 0; i < 6; i++)
  6955. {
  6956. if(i > 0) {
  6957. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6958. }
  6959. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6960. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6961. SERIAL_PROTOCOLPGM(", ");
  6962. SERIAL_PROTOCOL(35 + (i * 5));
  6963. SERIAL_PROTOCOLPGM(", ");
  6964. SERIAL_PROTOCOL(usteps);
  6965. SERIAL_PROTOCOLPGM(", ");
  6966. SERIAL_PROTOCOLLN(mm * 1000);
  6967. }
  6968. }
  6969. else if (code_seen('!')) { // ! - Set factory default values
  6970. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6971. int16_t z_shift = 8; //40C - 20um - 8usteps
  6972. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6973. z_shift = 24; //45C - 60um - 24usteps
  6974. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6975. z_shift = 48; //50C - 120um - 48usteps
  6976. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6977. z_shift = 80; //55C - 200um - 80usteps
  6978. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6979. z_shift = 120; //60C - 300um - 120usteps
  6980. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6981. SERIAL_PROTOCOLLNPGM("factory restored");
  6982. }
  6983. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6984. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6985. int16_t z_shift = 0;
  6986. for (uint8_t i = 0; i < 5; i++) {
  6987. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  6988. }
  6989. SERIAL_PROTOCOLLNPGM("zerorized");
  6990. }
  6991. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6992. int16_t usteps = code_value_short();
  6993. if (code_seen('I')) {
  6994. uint8_t index = code_value_uint8();
  6995. if (index < 5) {
  6996. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  6997. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6998. SERIAL_PROTOCOLLNRPGM(_header);
  6999. for (uint8_t i = 0; i < 6; i++)
  7000. {
  7001. usteps = 0;
  7002. if (i > 0) {
  7003. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  7004. }
  7005. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7006. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7007. SERIAL_PROTOCOLPGM(", ");
  7008. SERIAL_PROTOCOL(35 + (i * 5));
  7009. SERIAL_PROTOCOLPGM(", ");
  7010. SERIAL_PROTOCOL(usteps);
  7011. SERIAL_PROTOCOLPGM(", ");
  7012. SERIAL_PROTOCOLLN(mm * 1000);
  7013. }
  7014. }
  7015. }
  7016. }
  7017. else {
  7018. SERIAL_PROTOCOLLNPGM("no valid command");
  7019. }
  7020. } break;
  7021. #endif //PINDA_THERMISTOR
  7022. /*!
  7023. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  7024. Checks the parameters of the printer and gcode and performs compatibility check
  7025. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  7026. - M862.2 { P<model_code> | Q }
  7027. - M862.3 { P"<model_name>" | Q }
  7028. - M862.4 { P<fw_version> | Q }
  7029. - M862.5 { P<gcode_level> | Q }
  7030. When run with P<> argument, the check is performed against the input value.
  7031. When run with Q argument, the current value is shown.
  7032. M862.3 accepts text identifiers of printer types too.
  7033. The syntax of M862.3 is (note the quotes around the type):
  7034. M862.3 P "MK3S"
  7035. Accepted printer type identifiers and their numeric counterparts:
  7036. - MK1 (100)
  7037. - MK2 (200)
  7038. - MK2MM (201)
  7039. - MK2S (202)
  7040. - MK2SMM (203)
  7041. - MK2.5 (250)
  7042. - MK2.5MMU2 (20250)
  7043. - MK2.5S (252)
  7044. - MK2.5SMMU2S (20252)
  7045. - MK3 (300)
  7046. - MK3MMU2 (20300)
  7047. - MK3S (302)
  7048. - MK3SMMU2S (20302)
  7049. */
  7050. case 862: // M862: print checking
  7051. float nDummy;
  7052. uint8_t nCommand;
  7053. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7054. switch((ClPrintChecking)nCommand)
  7055. {
  7056. case ClPrintChecking::_Nozzle: // ~ .1
  7057. uint16_t nDiameter;
  7058. if(code_seen('P'))
  7059. {
  7060. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7061. nozzle_diameter_check(nDiameter);
  7062. }
  7063. else if(code_seen('Q'))
  7064. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7065. break;
  7066. case ClPrintChecking::_Model: // ~ .2
  7067. if(code_seen('P'))
  7068. {
  7069. uint16_t nPrinterModel;
  7070. nPrinterModel=(uint16_t)code_value_long();
  7071. // based on current state of MMU (active/stopped/connecting) perform a runtime update of the printer type
  7072. fSetMmuMode(MMU2::mmu2.Enabled());
  7073. printer_model_check(nPrinterModel);
  7074. }
  7075. else if(code_seen('Q'))
  7076. SERIAL_PROTOCOLLN(nPrinterType);
  7077. break;
  7078. case ClPrintChecking::_Smodel: // ~ .3
  7079. if(code_seen('P'))
  7080. printer_smodel_check(strchr_pointer);
  7081. else if(code_seen('Q'))
  7082. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7083. break;
  7084. case ClPrintChecking::_Version: // ~ .4
  7085. if(code_seen('P'))
  7086. fw_version_check(++strchr_pointer);
  7087. else if(code_seen('Q'))
  7088. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7089. break;
  7090. case ClPrintChecking::_Gcode: // ~ .5
  7091. if(code_seen('P'))
  7092. {
  7093. uint16_t nGcodeLevel;
  7094. nGcodeLevel=(uint16_t)code_value_long();
  7095. gcode_level_check(nGcodeLevel);
  7096. }
  7097. else if(code_seen('Q'))
  7098. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7099. break;
  7100. }
  7101. break;
  7102. #ifdef LIN_ADVANCE
  7103. /*!
  7104. ### 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>
  7105. 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.
  7106. #### Usage
  7107. M900 [ K | R | W | H | D]
  7108. #### Parameters
  7109. - `K` - Advance K factor
  7110. - `R` - Set ratio directly (overrides WH/D)
  7111. - `W` - Width
  7112. - `H` - Height
  7113. - `D` - Diameter Set ratio from WH/D
  7114. */
  7115. case 900:
  7116. gcode_M900();
  7117. break;
  7118. #endif
  7119. /*!
  7120. ### 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>
  7121. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7122. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7123. #### Usage
  7124. M907 [ X | Y | Z | E | B | S ]
  7125. #### Parameters
  7126. - `X` - X motor driver
  7127. - `Y` - Y motor driver
  7128. - `Z` - Z motor driver
  7129. - `E` - Extruder motor driver
  7130. - `B` - Second Extruder motor driver
  7131. - `S` - All motors
  7132. */
  7133. case 907:
  7134. {
  7135. #ifdef TMC2130
  7136. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7137. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7138. if(code_seen(axis_codes[i])){
  7139. if( i == E_AXIS && FarmOrUserECool() ){
  7140. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7141. SERIAL_ECHOLNPGM(", M907 E ignored");
  7142. continue;
  7143. }
  7144. long cur_mA = code_value_long();
  7145. uint8_t val = tmc2130_cur2val(cur_mA);
  7146. tmc2130_set_current_h(i, val);
  7147. tmc2130_set_current_r(i, val);
  7148. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7149. }
  7150. }
  7151. #else //TMC2130
  7152. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7153. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7154. if(code_seen('B')) st_current_set(4,code_value());
  7155. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7156. #endif
  7157. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7158. if(code_seen('X')) st_current_set(0, code_value());
  7159. #endif
  7160. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7161. if(code_seen('Z')) st_current_set(1, code_value());
  7162. #endif
  7163. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7164. if(code_seen('E')) st_current_set(2, code_value());
  7165. #endif
  7166. #endif //TMC2130
  7167. }
  7168. break;
  7169. /*!
  7170. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7171. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7172. #### Usage
  7173. M908 [ P | S ]
  7174. #### Parameters
  7175. - `P` - channel
  7176. - `S` - current
  7177. */
  7178. case 908:
  7179. {
  7180. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7181. uint8_t channel,current;
  7182. if(code_seen('P')) channel=code_value();
  7183. if(code_seen('S')) current=code_value();
  7184. digitalPotWrite(channel, current);
  7185. #endif
  7186. }
  7187. break;
  7188. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7189. /*!
  7190. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7191. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7192. */
  7193. case 910:
  7194. {
  7195. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7196. }
  7197. break;
  7198. /*!
  7199. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7200. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7201. #### Usage
  7202. M911 [ X | Y | Z | E ]
  7203. #### Parameters
  7204. - `X` - X stepper driver holding current value
  7205. - `Y` - Y stepper driver holding current value
  7206. - `Z` - Z stepper driver holding current value
  7207. - `E` - Extruder stepper driver holding current value
  7208. */
  7209. case 911:
  7210. {
  7211. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7212. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7213. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7214. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7215. }
  7216. break;
  7217. /*!
  7218. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7219. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7220. #### Usage
  7221. M912 [ X | Y | Z | E ]
  7222. #### Parameters
  7223. - `X` - X stepper driver running current value
  7224. - `Y` - Y stepper driver running current value
  7225. - `Z` - Z stepper driver running current value
  7226. - `E` - Extruder stepper driver running current value
  7227. */
  7228. case 912:
  7229. {
  7230. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7231. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7232. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7233. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7234. }
  7235. break;
  7236. /*!
  7237. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7238. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7239. Shows TMC2130 currents.
  7240. */
  7241. case 913:
  7242. {
  7243. tmc2130_print_currents();
  7244. }
  7245. break;
  7246. /*!
  7247. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7248. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7249. */
  7250. case 914:
  7251. {
  7252. tmc2130_mode = TMC2130_MODE_NORMAL;
  7253. update_mode_profile();
  7254. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7255. }
  7256. break;
  7257. /*!
  7258. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7259. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7260. */
  7261. case 915:
  7262. {
  7263. tmc2130_mode = TMC2130_MODE_SILENT;
  7264. update_mode_profile();
  7265. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7266. }
  7267. break;
  7268. /*!
  7269. ### 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>
  7270. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7271. #### Usage
  7272. M916 [ X | Y | Z | E ]
  7273. #### Parameters
  7274. - `X` - X stepper driver stallguard sensitivity threshold value
  7275. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7276. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7277. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7278. */
  7279. case 916:
  7280. {
  7281. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7282. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7283. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7284. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7285. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7286. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7287. }
  7288. break;
  7289. /*!
  7290. ### 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>
  7291. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7292. #### Usage
  7293. M917 [ X | Y | Z | E ]
  7294. #### Parameters
  7295. - `X` - X stepper driver PWM amplitude offset value
  7296. - `Y` - Y stepper driver PWM amplitude offset value
  7297. - `Z` - Z stepper driver PWM amplitude offset value
  7298. - `E` - Extruder stepper driver PWM amplitude offset value
  7299. */
  7300. case 917:
  7301. {
  7302. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7303. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7304. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7305. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7306. }
  7307. break;
  7308. /*!
  7309. ### 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>
  7310. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7311. #### Usage
  7312. M918 [ X | Y | Z | E ]
  7313. #### Parameters
  7314. - `X` - X stepper driver PWM amplitude gradient value
  7315. - `Y` - Y stepper driver PWM amplitude gradient value
  7316. - `Z` - Z stepper driver PWM amplitude gradient value
  7317. - `E` - Extruder stepper driver PWM amplitude gradient value
  7318. */
  7319. case 918:
  7320. {
  7321. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7322. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7323. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7324. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7325. }
  7326. break;
  7327. #endif //TMC2130_SERVICE_CODES_M910_M918
  7328. /*!
  7329. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7330. 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!
  7331. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7332. #### Usage
  7333. M350 [ X | Y | Z | E | B | S ]
  7334. #### Parameters
  7335. - `X` - X new resolution
  7336. - `Y` - Y new resolution
  7337. - `Z` - Z new resolution
  7338. - `E` - E new resolution
  7339. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7340. - `B` - Second extruder new resolution
  7341. - `S` - All axes new resolution
  7342. */
  7343. case 350:
  7344. {
  7345. #ifdef TMC2130
  7346. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7347. {
  7348. if(code_seen(axis_codes[i]))
  7349. {
  7350. uint16_t res_new = code_value();
  7351. #ifdef ALLOW_ALL_MRES
  7352. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7353. #else
  7354. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7355. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7356. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7357. #endif
  7358. if (res_valid)
  7359. {
  7360. st_synchronize();
  7361. uint16_t res = tmc2130_get_res(i);
  7362. tmc2130_set_res(i, res_new);
  7363. cs.axis_ustep_resolution[i] = res_new;
  7364. if (res_new > res)
  7365. {
  7366. uint16_t fac = (res_new / res);
  7367. cs.axis_steps_per_unit[i] *= fac;
  7368. position[i] *= fac;
  7369. }
  7370. else
  7371. {
  7372. uint16_t fac = (res / res_new);
  7373. cs.axis_steps_per_unit[i] /= fac;
  7374. position[i] /= fac;
  7375. }
  7376. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7377. if (i == E_AXIS)
  7378. fsensor.init();
  7379. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7380. }
  7381. }
  7382. }
  7383. reset_acceleration_rates();
  7384. #else //TMC2130
  7385. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7386. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7387. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7388. if(code_seen('B')) microstep_mode(4,code_value());
  7389. microstep_readings();
  7390. #endif
  7391. #endif //TMC2130
  7392. }
  7393. break;
  7394. /*!
  7395. ### 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>
  7396. Toggle MS1 MS2 pins directly.
  7397. #### Usage
  7398. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7399. #### Parameters
  7400. - `X` - Update X axis
  7401. - `Y` - Update Y axis
  7402. - `Z` - Update Z axis
  7403. - `E` - Update E axis
  7404. - `S` - which MSx pin to toggle
  7405. - `B` - new pin value
  7406. */
  7407. case 351:
  7408. {
  7409. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7410. if(code_seen('S')) switch((int)code_value())
  7411. {
  7412. case 1:
  7413. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7414. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7415. break;
  7416. case 2:
  7417. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7418. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7419. break;
  7420. }
  7421. microstep_readings();
  7422. #endif
  7423. }
  7424. break;
  7425. /*!
  7426. ### M701 - Load filament <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7427. #### Usage
  7428. M701 [ E | T ]
  7429. #### Parameters
  7430. - `E` - ID of filament to load, ranges from 0 to 4
  7431. - `T` - Alias of `E`. Used for compatibility with Marlin
  7432. */
  7433. case 701:
  7434. {
  7435. uint8_t mmuSlotIndex = 0xffU;
  7436. if (MMU2::mmu2.Enabled() && code_seen('E'))
  7437. mmuSlotIndex = code_value_uint8();
  7438. gcode_M701(mmuSlotIndex);
  7439. }
  7440. break;
  7441. /*!
  7442. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7443. #### Usage
  7444. M702 [ C ]
  7445. #### Parameters
  7446. - `C` - Unload just current filament
  7447. - without any parameters unload all filaments
  7448. */
  7449. case 702:
  7450. {
  7451. if (code_seen('C')) {
  7452. if(MMU2::mmu2.Enabled()) MMU2::mmu2.unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  7453. }
  7454. else {
  7455. if(MMU2::mmu2.Enabled()) MMU2::mmu2.unload(); //! unload current filament
  7456. else unload_filament();
  7457. }
  7458. }
  7459. break;
  7460. /*!
  7461. #### End of M-Commands
  7462. */
  7463. default:
  7464. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7465. }
  7466. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7467. mcode_in_progress = 0;
  7468. }
  7469. }
  7470. // end if(code_seen('M')) (end of M codes)
  7471. /*!
  7472. -----------------------------------------------------------------------------------------
  7473. # T Codes
  7474. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7475. #### For MMU_V2:
  7476. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7477. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7478. @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.
  7479. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7480. */
  7481. else if(code_seen('T')){
  7482. TCodes(strchr_pointer, code_value());
  7483. } // end if(code_seen('T')) (end of T codes)
  7484. /*!
  7485. #### End of T-Codes
  7486. */
  7487. /**
  7488. *---------------------------------------------------------------------------------
  7489. *# D codes
  7490. */
  7491. else if (code_seen('D')) // D codes (debug)
  7492. {
  7493. switch(code_value_short())
  7494. {
  7495. /*!
  7496. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7497. */
  7498. case -1:
  7499. dcode__1(); break;
  7500. #ifdef DEBUG_DCODES
  7501. /*!
  7502. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7503. #### Usage
  7504. D0 [ B ]
  7505. #### Parameters
  7506. - `B` - Bootloader
  7507. */
  7508. case 0:
  7509. dcode_0(); break;
  7510. /*!
  7511. *
  7512. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7513. D1
  7514. *
  7515. */
  7516. case 1:
  7517. dcode_1(); break;
  7518. #endif
  7519. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7520. /*!
  7521. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7522. This command can be used without any additional parameters. It will read the entire RAM.
  7523. #### Usage
  7524. D2 [ A | C | X ]
  7525. #### Parameters
  7526. - `A` - Address (x0000-x1fff)
  7527. - `C` - Count (1-8192)
  7528. - `X` - Data
  7529. #### Notes
  7530. - The hex address needs to be lowercase without the 0 before the x
  7531. - Count is decimal
  7532. - The hex data needs to be lowercase
  7533. */
  7534. case 2:
  7535. dcode_2(); break;
  7536. #endif //DEBUG_DCODES
  7537. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7538. /*!
  7539. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7540. This command can be used without any additional parameters. It will read the entire eeprom.
  7541. #### Usage
  7542. D3 [ A | C | X ]
  7543. #### Parameters
  7544. - `A` - Address (x0000-x0fff)
  7545. - `C` - Count (1-4096)
  7546. - `X` - Data (hex)
  7547. #### Notes
  7548. - The hex address needs to be lowercase without the 0 before the x
  7549. - Count is decimal
  7550. - The hex data needs to be lowercase
  7551. */
  7552. case 3:
  7553. dcode_3(); break;
  7554. #endif //DEBUG_DCODE3
  7555. #ifdef DEBUG_DCODES
  7556. /*!
  7557. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7558. To read the digital value of a pin you need only to define the pin number.
  7559. #### Usage
  7560. D4 [ P | F | V ]
  7561. #### Parameters
  7562. - `P` - Pin (0-255)
  7563. - `F` - Function in/out (0/1)
  7564. - `V` - Value (0/1)
  7565. */
  7566. case 4:
  7567. dcode_4(); break;
  7568. #endif //DEBUG_DCODES
  7569. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7570. /*!
  7571. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7572. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7573. #### Usage
  7574. D5 [ A | C | X | E ]
  7575. #### Parameters
  7576. - `A` - Address (x00000-x3ffff)
  7577. - `C` - Count (1-8192)
  7578. - `X` - Data (hex)
  7579. - `E` - Erase
  7580. #### Notes
  7581. - The hex address needs to be lowercase without the 0 before the x
  7582. - Count is decimal
  7583. - The hex data needs to be lowercase
  7584. */
  7585. case 5:
  7586. dcode_5(); break;
  7587. #endif //DEBUG_DCODE5
  7588. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7589. /*!
  7590. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7591. Reserved
  7592. */
  7593. case 6:
  7594. dcode_6(); break;
  7595. #endif
  7596. #ifdef DEBUG_DCODES
  7597. /*!
  7598. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7599. Reserved
  7600. */
  7601. case 7:
  7602. dcode_7(); break;
  7603. /*!
  7604. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7605. #### Usage
  7606. D8 [ ? | ! | P | Z ]
  7607. #### Parameters
  7608. - `?` - Read PINDA temperature shift values
  7609. - `!` - Reset PINDA temperature shift values to default
  7610. - `P` - Pinda temperature [C]
  7611. - `Z` - Z Offset [mm]
  7612. */
  7613. case 8:
  7614. dcode_8(); break;
  7615. /*!
  7616. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7617. #### Usage
  7618. D9 [ I | V ]
  7619. #### Parameters
  7620. - `I` - ADC channel index
  7621. - `0` - Heater 0 temperature
  7622. - `1` - Heater 1 temperature
  7623. - `2` - Bed temperature
  7624. - `3` - PINDA temperature
  7625. - `4` - PWR voltage
  7626. - `5` - Ambient temperature
  7627. - `6` - BED voltage
  7628. - `V` Value to be written as simulated
  7629. */
  7630. case 9:
  7631. dcode_9(); break;
  7632. /*!
  7633. ### 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>
  7634. */
  7635. case 10:
  7636. dcode_10(); break;
  7637. /*!
  7638. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7639. Writes the current time in the log file.
  7640. */
  7641. #endif //DEBUG_DCODES
  7642. #ifdef XFLASH_DUMP
  7643. /*!
  7644. ### 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>
  7645. Generate a crash dump for later retrival.
  7646. #### Usage
  7647. D20 [E]
  7648. ### Parameters
  7649. - `E` - Perform an emergency crash dump (resets the printer).
  7650. ### Notes
  7651. - A crash dump can be later recovered with D21, or cleared with D22.
  7652. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7653. is completed.
  7654. */
  7655. case 20: {
  7656. dcode_20();
  7657. break;
  7658. };
  7659. /*!
  7660. ### 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>
  7661. Output the complete crash dump (if present) to the serial.
  7662. #### Usage
  7663. D21
  7664. ### Notes
  7665. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7666. */
  7667. case 21: {
  7668. dcode_21();
  7669. break;
  7670. };
  7671. /*!
  7672. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7673. Clear an existing internal crash dump.
  7674. #### Usage
  7675. D22
  7676. */
  7677. case 22: {
  7678. dcode_22();
  7679. break;
  7680. };
  7681. #endif //XFLASH_DUMP
  7682. #ifdef EMERGENCY_SERIAL_DUMP
  7683. /*!
  7684. ### 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>
  7685. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7686. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7687. #### Usage
  7688. D23 [E] [R]
  7689. #### Parameters
  7690. - `E` - Perform an emergency crash dump (resets the printer).
  7691. - `R` - Disable online dumps.
  7692. */
  7693. case 23: {
  7694. dcode_23();
  7695. break;
  7696. };
  7697. #endif
  7698. #ifdef TEMP_MODEL_DEBUG
  7699. /*!
  7700. ## D70 - Enable low-level temperature model logging for offline simulation
  7701. #### Usage
  7702. D70 [ S ]
  7703. #### Parameters
  7704. - `S` - Enable 0-1 (default 0)
  7705. */
  7706. case 70: {
  7707. if(code_seen('S'))
  7708. temp_model_log_enable(code_value_short());
  7709. break;
  7710. }
  7711. #endif
  7712. #ifdef HEATBED_ANALYSIS
  7713. /*!
  7714. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7715. This command will log data to SD card file "mesh.txt".
  7716. #### Usage
  7717. D80 [ E | F | G | H | I | J ]
  7718. #### Parameters
  7719. - `E` - Dimension X (default 40)
  7720. - `F` - Dimention Y (default 40)
  7721. - `G` - Points X (default 40)
  7722. - `H` - Points Y (default 40)
  7723. - `I` - Offset X (default 74)
  7724. - `J` - Offset Y (default 34)
  7725. */
  7726. case 80:
  7727. dcode_80(); break;
  7728. /*!
  7729. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7730. This command will log data to SD card file "wldsd.txt".
  7731. #### Usage
  7732. D81 [ E | F | G | H | I | J ]
  7733. #### Parameters
  7734. - `E` - Dimension X (default 40)
  7735. - `F` - Dimention Y (default 40)
  7736. - `G` - Points X (default 40)
  7737. - `H` - Points Y (default 40)
  7738. - `I` - Offset X (default 74)
  7739. - `J` - Offset Y (default 34)
  7740. */
  7741. case 81:
  7742. dcode_81(); break;
  7743. #endif //HEATBED_ANALYSIS
  7744. #ifdef DEBUG_DCODES
  7745. /*!
  7746. ### 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>
  7747. */
  7748. case 106:
  7749. dcode_106(); break;
  7750. #ifdef TMC2130
  7751. /*!
  7752. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7753. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7754. #### Usage
  7755. D2130 [ Axis | Command | Subcommand | Value ]
  7756. #### Parameters
  7757. - Axis
  7758. - `X` - X stepper driver
  7759. - `Y` - Y stepper driver
  7760. - `Z` - Z stepper driver
  7761. - `E` - Extruder stepper driver
  7762. - Commands
  7763. - `0` - Current off
  7764. - `1` - Current on
  7765. - `+` - Single step
  7766. - `-` - Single step oposite direction
  7767. - `NNN` - Value sereval steps
  7768. - `?` - Read register
  7769. - Subcommands for read register
  7770. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7771. - `step` - Step
  7772. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7773. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7774. - `wave` - Microstep linearity compensation curve
  7775. - `!` - Set register
  7776. - Subcommands for set register
  7777. - `mres` - Micro step resolution
  7778. - `step` - Step
  7779. - `wave` - Microstep linearity compensation curve
  7780. - Values for set register
  7781. - `0, 180 --> 250` - Off
  7782. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7783. - `@` - Home calibrate axis
  7784. Examples:
  7785. D2130E?wave
  7786. Print extruder microstep linearity compensation curve
  7787. D2130E!wave0
  7788. Disable extruder linearity compensation curve, (sine curve is used)
  7789. D2130E!wave220
  7790. (sin(x))^1.1 extruder microstep compensation curve used
  7791. Notes:
  7792. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7793. *
  7794. */
  7795. case 2130:
  7796. dcode_2130(); break;
  7797. #endif //TMC2130
  7798. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7799. /*!
  7800. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7801. #### Usage
  7802. D9125 [ ? | ! | R | X | Y | L ]
  7803. #### Parameters
  7804. - `?` - Print values
  7805. - `!` - Print values
  7806. - `R` - Resolution. Not active in code
  7807. - `X` - X values
  7808. - `Y` - Y values
  7809. - `L` - Activate filament sensor log
  7810. */
  7811. case 9125:
  7812. dcode_9125(); break;
  7813. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7814. #endif //DEBUG_DCODES
  7815. default:
  7816. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7817. }
  7818. }
  7819. else
  7820. {
  7821. SERIAL_ECHO_START;
  7822. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7823. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7824. SERIAL_ECHOLNPGM("\"(2)");
  7825. }
  7826. KEEPALIVE_STATE(NOT_BUSY);
  7827. ClearToSend();
  7828. }
  7829. /*!
  7830. #### End of D-Codes
  7831. */
  7832. /** @defgroup GCodes G-Code List
  7833. */
  7834. // ---------------------------------------------------
  7835. void FlushSerialRequestResend()
  7836. {
  7837. //char cmdbuffer[bufindr][100]="Resend:";
  7838. MYSERIAL.flush();
  7839. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7840. }
  7841. // Confirm the execution of a command, if sent from a serial line.
  7842. // Execution of a command from a SD card will not be confirmed.
  7843. void ClearToSend()
  7844. {
  7845. previous_millis_cmd.start();
  7846. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7847. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7848. }
  7849. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7850. void update_currents() {
  7851. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7852. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7853. float tmp_motor[3];
  7854. //SERIAL_ECHOLNPGM("Currents updated: ");
  7855. if (destination[Z_AXIS] < Z_SILENT) {
  7856. //SERIAL_ECHOLNPGM("LOW");
  7857. for (uint8_t i = 0; i < 3; i++) {
  7858. st_current_set(i, current_low[i]);
  7859. /*MYSERIAL.print(int(i));
  7860. SERIAL_ECHOPGM(": ");
  7861. MYSERIAL.println(current_low[i]);*/
  7862. }
  7863. }
  7864. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7865. //SERIAL_ECHOLNPGM("HIGH");
  7866. for (uint8_t i = 0; i < 3; i++) {
  7867. st_current_set(i, current_high[i]);
  7868. /*MYSERIAL.print(int(i));
  7869. SERIAL_ECHOPGM(": ");
  7870. MYSERIAL.println(current_high[i]);*/
  7871. }
  7872. }
  7873. else {
  7874. for (uint8_t i = 0; i < 3; i++) {
  7875. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7876. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7877. st_current_set(i, tmp_motor[i]);
  7878. /*MYSERIAL.print(int(i));
  7879. SERIAL_ECHOPGM(": ");
  7880. MYSERIAL.println(tmp_motor[i]);*/
  7881. }
  7882. }
  7883. }
  7884. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7885. void get_coordinates() {
  7886. bool seen[4]={false,false,false,false};
  7887. for(int8_t i=0; i < NUM_AXIS; i++) {
  7888. if(code_seen(axis_codes[i]))
  7889. {
  7890. bool relative = axis_relative_modes & (1 << i);
  7891. destination[i] = code_value();
  7892. if (i == E_AXIS) {
  7893. float emult = extruder_multiplier[active_extruder];
  7894. if (emult != 1.) {
  7895. if (! relative) {
  7896. destination[i] -= current_position[i];
  7897. relative = true;
  7898. }
  7899. destination[i] *= emult;
  7900. }
  7901. }
  7902. if (relative)
  7903. destination[i] += current_position[i];
  7904. seen[i]=true;
  7905. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7906. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7907. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7908. }
  7909. else destination[i] = current_position[i]; //Are these else lines really needed?
  7910. }
  7911. if(code_seen('F')) {
  7912. next_feedrate = code_value();
  7913. if(next_feedrate > 0.0) feedrate = next_feedrate;
  7914. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  7915. {
  7916. // float e_max_speed =
  7917. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  7918. }
  7919. }
  7920. }
  7921. void clamp_to_software_endstops(float target[3])
  7922. {
  7923. #ifdef DEBUG_DISABLE_SWLIMITS
  7924. return;
  7925. #endif //DEBUG_DISABLE_SWLIMITS
  7926. world2machine_clamp(target[0], target[1]);
  7927. // Clamp the Z coordinate.
  7928. if (min_software_endstops) {
  7929. float negative_z_offset = 0;
  7930. #ifdef ENABLE_AUTO_BED_LEVELING
  7931. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  7932. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  7933. #endif
  7934. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  7935. }
  7936. if (max_software_endstops) {
  7937. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  7938. }
  7939. }
  7940. uint16_t restore_interrupted_gcode() {
  7941. // When recovering from a previous print move, restore the originally
  7942. // calculated start position on the first USB/SD command. This accounts
  7943. // properly for relative moves
  7944. if (
  7945. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  7946. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  7947. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  7948. )
  7949. ) {
  7950. memcpy(current_position, saved_start_position, sizeof(current_position));
  7951. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  7952. return saved_segment_idx;
  7953. }
  7954. else
  7955. return 1; //begin with the first segment
  7956. }
  7957. #ifdef MESH_BED_LEVELING
  7958. 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) {
  7959. float dx = x - current_position[X_AXIS];
  7960. float dy = y - current_position[Y_AXIS];
  7961. uint16_t n_segments = 0;
  7962. if (mbl.active) {
  7963. float len = fabs(dx) + fabs(dy);
  7964. if (len > 0)
  7965. // Split to 3cm segments or shorter.
  7966. n_segments = uint16_t(ceil(len / 30.f));
  7967. }
  7968. if (n_segments > 1 && start_segment_idx) {
  7969. float dz = z - current_position[Z_AXIS];
  7970. float de = e - current_position[E_AXIS];
  7971. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  7972. float t = float(i) / float(n_segments);
  7973. plan_buffer_line(current_position[X_AXIS] + t * dx,
  7974. current_position[Y_AXIS] + t * dy,
  7975. current_position[Z_AXIS] + t * dz,
  7976. current_position[E_AXIS] + t * de,
  7977. feed_rate, extruder, current_position, i);
  7978. if (planner_aborted)
  7979. return;
  7980. }
  7981. }
  7982. // The rest of the path.
  7983. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  7984. }
  7985. #endif // MESH_BED_LEVELING
  7986. void prepare_move(uint16_t start_segment_idx)
  7987. {
  7988. clamp_to_software_endstops(destination);
  7989. previous_millis_cmd.start();
  7990. // Do not use feedmultiply for E or Z only moves
  7991. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  7992. plan_buffer_line_destinationXYZE(feedrate/60);
  7993. }
  7994. else {
  7995. #ifdef MESH_BED_LEVELING
  7996. 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);
  7997. #else
  7998. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  7999. #endif
  8000. }
  8001. set_current_to_destination();
  8002. }
  8003. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8004. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8005. // Trace the arc
  8006. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8007. // As far as the parser is concerned, the position is now == target. In reality the
  8008. // motion control system might still be processing the action and the real tool position
  8009. // in any intermediate location.
  8010. set_current_to_destination();
  8011. previous_millis_cmd.start();
  8012. }
  8013. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8014. #if defined(FAN_PIN)
  8015. #if CONTROLLERFAN_PIN == FAN_PIN
  8016. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8017. #endif
  8018. #endif
  8019. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8020. unsigned long lastMotorCheck = 0;
  8021. void controllerFan()
  8022. {
  8023. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8024. {
  8025. lastMotorCheck = _millis();
  8026. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8027. #if EXTRUDERS > 2
  8028. || !READ(E2_ENABLE_PIN)
  8029. #endif
  8030. #if EXTRUDER > 1
  8031. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8032. || !READ(X2_ENABLE_PIN)
  8033. #endif
  8034. || !READ(E1_ENABLE_PIN)
  8035. #endif
  8036. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8037. {
  8038. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8039. }
  8040. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8041. {
  8042. digitalWrite(CONTROLLERFAN_PIN, 0);
  8043. analogWrite(CONTROLLERFAN_PIN, 0);
  8044. }
  8045. else
  8046. {
  8047. // allows digital or PWM fan output to be used (see M42 handling)
  8048. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8049. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8050. }
  8051. }
  8052. }
  8053. #endif
  8054. #ifdef SAFETYTIMER
  8055. /**
  8056. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8057. *
  8058. * Full screen blocking notification message is shown after heater turning off.
  8059. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8060. * damage print.
  8061. *
  8062. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8063. */
  8064. static void handleSafetyTimer()
  8065. {
  8066. #if (EXTRUDERS > 1)
  8067. #error Implemented only for one extruder.
  8068. #endif //(EXTRUDERS > 1)
  8069. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8070. {
  8071. safetyTimer.stop();
  8072. }
  8073. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8074. {
  8075. safetyTimer.start();
  8076. }
  8077. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8078. {
  8079. setTargetBed(0);
  8080. setAllTargetHotends(0);
  8081. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8082. }
  8083. }
  8084. #endif //SAFETYTIMER
  8085. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8086. {
  8087. #ifdef FILAMENT_SENSOR
  8088. if (fsensor.update()) {
  8089. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8090. }
  8091. #endif
  8092. #ifdef SAFETYTIMER
  8093. handleSafetyTimer();
  8094. #endif //SAFETYTIMER
  8095. #if defined(KILL_PIN) && KILL_PIN > -1
  8096. static int killCount = 0; // make the inactivity button a bit less responsive
  8097. const int KILL_DELAY = 10000;
  8098. #endif
  8099. if(buflen < (BUFSIZE-1)){
  8100. get_command();
  8101. }
  8102. if(previous_millis_cmd.expired(max_inactive_time))
  8103. if(max_inactive_time)
  8104. kill(_n("Inactivity Shutdown"), 4);
  8105. if(stepper_inactive_time) {
  8106. if(previous_millis_cmd.expired(stepper_inactive_time))
  8107. {
  8108. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8109. disable_x();
  8110. disable_y();
  8111. disable_z();
  8112. disable_e0();
  8113. disable_e1();
  8114. disable_e2();
  8115. }
  8116. }
  8117. }
  8118. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8119. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8120. {
  8121. chdkActive = false;
  8122. WRITE(CHDK, LOW);
  8123. }
  8124. #endif
  8125. #if defined(KILL_PIN) && KILL_PIN > -1
  8126. // Check if the kill button was pressed and wait just in case it was an accidental
  8127. // key kill key press
  8128. // -------------------------------------------------------------------------------
  8129. if( 0 == READ(KILL_PIN) )
  8130. {
  8131. killCount++;
  8132. }
  8133. else if (killCount > 0)
  8134. {
  8135. killCount--;
  8136. }
  8137. // Exceeded threshold and we can confirm that it was not accidental
  8138. // KILL the machine
  8139. // ----------------------------------------------------------------
  8140. if ( killCount >= KILL_DELAY)
  8141. {
  8142. kill(NULL, 5);
  8143. }
  8144. #endif
  8145. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8146. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8147. #endif
  8148. #ifdef EXTRUDER_RUNOUT_PREVENT
  8149. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8150. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8151. {
  8152. bool oldstatus=READ(E0_ENABLE_PIN);
  8153. enable_e0();
  8154. float oldepos=current_position[E_AXIS];
  8155. float oldedes=destination[E_AXIS];
  8156. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8157. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8158. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8159. current_position[E_AXIS]=oldepos;
  8160. destination[E_AXIS]=oldedes;
  8161. plan_set_e_position(oldepos);
  8162. previous_millis_cmd.start();
  8163. st_synchronize();
  8164. WRITE(E0_ENABLE_PIN,oldstatus);
  8165. }
  8166. #endif
  8167. check_axes_activity();
  8168. MMU2::mmu2.mmu_loop();
  8169. // handle longpress
  8170. if(lcd_longpress_trigger)
  8171. {
  8172. // long press is not possible in modal mode, wait until ready
  8173. if (lcd_longpress_func && lcd_update_enabled)
  8174. {
  8175. lcd_longpress_func();
  8176. lcd_longpress_trigger = 0;
  8177. }
  8178. }
  8179. #if defined(AUTO_REPORT)
  8180. host_autoreport();
  8181. #endif //AUTO_REPORT
  8182. host_keepalive();
  8183. }
  8184. void kill(const char *full_screen_message, unsigned char id)
  8185. {
  8186. printf_P(_N("KILL: %d\n"), id);
  8187. //return;
  8188. cli(); // Stop interrupts
  8189. disable_heater();
  8190. disable_x();
  8191. // SERIAL_ECHOLNPGM("kill - disable Y");
  8192. disable_y();
  8193. poweroff_z();
  8194. disable_e0();
  8195. disable_e1();
  8196. disable_e2();
  8197. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8198. pinMode(PS_ON_PIN,INPUT);
  8199. #endif
  8200. SERIAL_ERROR_START;
  8201. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8202. if (full_screen_message != NULL) {
  8203. SERIAL_ERRORLNRPGM(full_screen_message);
  8204. lcd_display_message_fullscreen_P(full_screen_message);
  8205. } else {
  8206. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8207. }
  8208. // FMC small patch to update the LCD before ending
  8209. sei(); // enable interrupts
  8210. for ( int i=5; i--; lcd_update(0))
  8211. {
  8212. _delay(200);
  8213. }
  8214. cli(); // disable interrupts
  8215. suicide();
  8216. while(1)
  8217. {
  8218. #ifdef WATCHDOG
  8219. wdt_reset();
  8220. #endif //WATCHDOG
  8221. /* Intentionally left empty */
  8222. } // Wait for reset
  8223. }
  8224. void UnconditionalStop()
  8225. {
  8226. CRITICAL_SECTION_START;
  8227. // Disable all heaters and unroll the temperature wait loop stack
  8228. disable_heater();
  8229. cancel_heatup = true;
  8230. heating_status = HeatingStatus::NO_HEATING;
  8231. // Clear any saved printing state
  8232. cancel_saved_printing();
  8233. // Abort the planner
  8234. planner_abort_hard();
  8235. // Reset the queue
  8236. cmdqueue_reset();
  8237. cmdqueue_serial_disabled = false;
  8238. // Reset the sd status
  8239. card.sdprinting = false;
  8240. card.closefile();
  8241. st_reset_timer();
  8242. CRITICAL_SECTION_END;
  8243. }
  8244. // Emergency stop used by overtemp functions which allows recovery
  8245. // WARNING: This function is called *continuously* during a thermal failure.
  8246. //
  8247. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8248. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8249. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8250. // kept in busy state and *must* be recovered from the LCD.
  8251. void ThermalStop(bool allow_pause)
  8252. {
  8253. if(Stopped == false) {
  8254. Stopped = true;
  8255. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8256. if (!isPrintPaused) {
  8257. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8258. // we cannot make a distinction for the host here, the pause must be instantaneous
  8259. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8260. // disable heaters and save the original temperatures to saved_*, which will get
  8261. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8262. // original values after the pause handler is called.
  8263. float bed_temp = saved_bed_temperature;
  8264. float ext_temp = saved_extruder_temperature;
  8265. int fan_speed = saved_fan_speed;
  8266. lcd_pause_print();
  8267. saved_bed_temperature = bed_temp;
  8268. saved_extruder_temperature = ext_temp;
  8269. saved_fan_speed = fan_speed;
  8270. }
  8271. } else {
  8272. // We got a hard thermal error and/or there is no print going on. Just stop.
  8273. lcd_print_stop();
  8274. // Also prevent further menu entry
  8275. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8276. }
  8277. // Report the status on the serial, switch to a busy state
  8278. SERIAL_ERROR_START;
  8279. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8280. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8281. // higher-priority alert status message)
  8282. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8283. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8284. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8285. WRITE(BEEPER, HIGH);
  8286. }
  8287. // Return to the status screen to stop any pending menu action which could have been
  8288. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8289. // error is immediately shown.
  8290. if (menu_menu != lcd_status_screen)
  8291. lcd_return_to_status();
  8292. }
  8293. bool IsStopped() { return Stopped; };
  8294. void finishAndDisableSteppers()
  8295. {
  8296. st_synchronize();
  8297. disable_x();
  8298. disable_y();
  8299. disable_z();
  8300. disable_e0();
  8301. disable_e1();
  8302. disable_e2();
  8303. #ifndef LA_NOCOMPAT
  8304. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8305. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8306. // state for the next print.
  8307. la10c_reset();
  8308. #endif
  8309. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8310. print_time_remaining_init();
  8311. }
  8312. #ifdef FAST_PWM_FAN
  8313. void setPwmFrequency(uint8_t pin, int val)
  8314. {
  8315. val &= 0x07;
  8316. switch(digitalPinToTimer(pin))
  8317. {
  8318. #if defined(TCCR0A)
  8319. case TIMER0A:
  8320. case TIMER0B:
  8321. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8322. // TCCR0B |= val;
  8323. break;
  8324. #endif
  8325. #if defined(TCCR1A)
  8326. case TIMER1A:
  8327. case TIMER1B:
  8328. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8329. // TCCR1B |= val;
  8330. break;
  8331. #endif
  8332. #if defined(TCCR2)
  8333. case TIMER2:
  8334. case TIMER2:
  8335. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8336. TCCR2 |= val;
  8337. break;
  8338. #endif
  8339. #if defined(TCCR2A)
  8340. case TIMER2A:
  8341. case TIMER2B:
  8342. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8343. TCCR2B |= val;
  8344. break;
  8345. #endif
  8346. #if defined(TCCR3A)
  8347. case TIMER3A:
  8348. case TIMER3B:
  8349. case TIMER3C:
  8350. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8351. TCCR3B |= val;
  8352. break;
  8353. #endif
  8354. #if defined(TCCR4A)
  8355. case TIMER4A:
  8356. case TIMER4B:
  8357. case TIMER4C:
  8358. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8359. TCCR4B |= val;
  8360. break;
  8361. #endif
  8362. #if defined(TCCR5A)
  8363. case TIMER5A:
  8364. case TIMER5B:
  8365. case TIMER5C:
  8366. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8367. TCCR5B |= val;
  8368. break;
  8369. #endif
  8370. }
  8371. }
  8372. #endif //FAST_PWM_FAN
  8373. //! @brief Get and validate extruder number
  8374. //!
  8375. //! If it is not specified, active_extruder is returned in parameter extruder.
  8376. //! @param [in] code M code number
  8377. //! @param [out] extruder
  8378. //! @return error
  8379. //! @retval true Invalid extruder specified in T code
  8380. //! @retval false Valid extruder specified in T code, or not specifiead
  8381. bool setTargetedHotend(int code, uint8_t &extruder)
  8382. {
  8383. extruder = active_extruder;
  8384. if(code_seen('T')) {
  8385. extruder = code_value_uint8();
  8386. if(extruder >= EXTRUDERS) {
  8387. SERIAL_ECHO_START;
  8388. switch(code){
  8389. case 104:
  8390. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8391. break;
  8392. case 105:
  8393. SERIAL_ECHORPGM(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8394. break;
  8395. case 109:
  8396. SERIAL_ECHORPGM(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8397. break;
  8398. case 218:
  8399. SERIAL_ECHORPGM(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8400. break;
  8401. case 221:
  8402. SERIAL_ECHORPGM(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8403. break;
  8404. }
  8405. SERIAL_PROTOCOLLN((int)extruder);
  8406. return true;
  8407. }
  8408. }
  8409. return false;
  8410. }
  8411. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8412. {
  8413. if (eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 1) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 2) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 3) == 255)
  8414. {
  8415. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8416. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8417. }
  8418. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8419. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8420. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8421. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8422. total_filament_used = 0;
  8423. }
  8424. float calculate_extruder_multiplier(float diameter) {
  8425. float out = 1.f;
  8426. if (cs.volumetric_enabled && diameter > 0.f) {
  8427. float area = M_PI * diameter * diameter * 0.25;
  8428. out = 1.f / area;
  8429. }
  8430. if (extrudemultiply != 100)
  8431. out *= float(extrudemultiply) * 0.01f;
  8432. return out;
  8433. }
  8434. void calculate_extruder_multipliers() {
  8435. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8436. #if EXTRUDERS > 1
  8437. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8438. #if EXTRUDERS > 2
  8439. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8440. #endif
  8441. #endif
  8442. }
  8443. void delay_keep_alive(unsigned int ms)
  8444. {
  8445. for (;;) {
  8446. manage_heater();
  8447. // Manage inactivity, but don't disable steppers on timeout.
  8448. manage_inactivity(true);
  8449. lcd_update(0);
  8450. if (ms == 0)
  8451. break;
  8452. else if (ms >= 50) {
  8453. _delay(50);
  8454. ms -= 50;
  8455. } else {
  8456. _delay(ms);
  8457. ms = 0;
  8458. }
  8459. }
  8460. }
  8461. static void wait_for_heater(long codenum, uint8_t extruder) {
  8462. if (!degTargetHotend(extruder))
  8463. return;
  8464. #ifdef TEMP_RESIDENCY_TIME
  8465. long residencyStart;
  8466. residencyStart = -1;
  8467. /* continue to loop until we have reached the target temp
  8468. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8469. cancel_heatup = false;
  8470. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8471. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8472. #else
  8473. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8474. #endif //TEMP_RESIDENCY_TIME
  8475. if ((_millis() - codenum) > 1000UL)
  8476. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8477. if (!farm_mode) {
  8478. SERIAL_PROTOCOLPGM("T:");
  8479. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8480. SERIAL_PROTOCOLPGM(" E:");
  8481. SERIAL_PROTOCOL((int)extruder);
  8482. #ifdef TEMP_RESIDENCY_TIME
  8483. SERIAL_PROTOCOLPGM(" W:");
  8484. if (residencyStart > -1)
  8485. {
  8486. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8487. SERIAL_PROTOCOLLN(codenum);
  8488. }
  8489. else
  8490. {
  8491. SERIAL_PROTOCOLLN('?');
  8492. }
  8493. }
  8494. #else
  8495. SERIAL_PROTOCOLLN();
  8496. #endif
  8497. codenum = _millis();
  8498. }
  8499. manage_heater();
  8500. manage_inactivity(true); //do not disable steppers
  8501. lcd_update(0);
  8502. #ifdef TEMP_RESIDENCY_TIME
  8503. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8504. or when current temp falls outside the hysteresis after target temp was reached */
  8505. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8506. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8507. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8508. {
  8509. residencyStart = _millis();
  8510. }
  8511. #endif //TEMP_RESIDENCY_TIME
  8512. }
  8513. }
  8514. void check_babystep()
  8515. {
  8516. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8517. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8518. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8519. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8520. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8521. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8522. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8523. babystep_z);
  8524. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8525. lcd_update_enable(true);
  8526. }
  8527. }
  8528. #ifdef HEATBED_ANALYSIS
  8529. void d_setup()
  8530. {
  8531. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8532. pinMode(D_DATA, INPUT_PULLUP);
  8533. pinMode(D_REQUIRE, OUTPUT);
  8534. digitalWrite(D_REQUIRE, HIGH);
  8535. }
  8536. float d_ReadData()
  8537. {
  8538. int digit[13];
  8539. String mergeOutput;
  8540. float output;
  8541. digitalWrite(D_REQUIRE, HIGH);
  8542. for (int i = 0; i<13; i++)
  8543. {
  8544. for (int j = 0; j < 4; j++)
  8545. {
  8546. while (digitalRead(D_DATACLOCK) == LOW) {}
  8547. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8548. bitWrite(digit[i], j, digitalRead(D_DATA));
  8549. }
  8550. }
  8551. digitalWrite(D_REQUIRE, LOW);
  8552. mergeOutput = "";
  8553. output = 0;
  8554. for (int r = 5; r <= 10; r++) //Merge digits
  8555. {
  8556. mergeOutput += digit[r];
  8557. }
  8558. output = mergeOutput.toFloat();
  8559. if (digit[4] == 8) //Handle sign
  8560. {
  8561. output *= -1;
  8562. }
  8563. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8564. {
  8565. output /= 10;
  8566. }
  8567. return output;
  8568. }
  8569. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8570. int t1 = 0;
  8571. int t_delay = 0;
  8572. int digit[13];
  8573. int m;
  8574. char str[3];
  8575. //String mergeOutput;
  8576. char mergeOutput[15];
  8577. float output;
  8578. int mesh_point = 0; //index number of calibration point
  8579. 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
  8580. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8581. float mesh_home_z_search = 4;
  8582. float measure_z_height = 0.2f;
  8583. float row[x_points_num];
  8584. int ix = 0;
  8585. int iy = 0;
  8586. const char* filename_wldsd = "mesh.txt";
  8587. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8588. char numb_wldsd[8]; // (" -A.BCD" + null)
  8589. #ifdef MICROMETER_LOGGING
  8590. d_setup();
  8591. #endif //MICROMETER_LOGGING
  8592. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8593. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8594. unsigned int custom_message_type_old = custom_message_type;
  8595. unsigned int custom_message_state_old = custom_message_state;
  8596. custom_message_type = CustomMsg::MeshBedLeveling;
  8597. custom_message_state = (x_points_num * y_points_num) + 10;
  8598. lcd_update(1);
  8599. //mbl.reset();
  8600. babystep_undo();
  8601. card.openFile(filename_wldsd, false);
  8602. /*destination[Z_AXIS] = mesh_home_z_search;
  8603. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8604. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8605. for(int8_t i=0; i < NUM_AXIS; i++) {
  8606. current_position[i] = destination[i];
  8607. }
  8608. st_synchronize();
  8609. */
  8610. destination[Z_AXIS] = measure_z_height;
  8611. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8612. for(int8_t i=0; i < NUM_AXIS; i++) {
  8613. current_position[i] = destination[i];
  8614. }
  8615. st_synchronize();
  8616. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8617. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8618. SERIAL_PROTOCOL(x_points_num);
  8619. SERIAL_PROTOCOLPGM(",");
  8620. SERIAL_PROTOCOL(y_points_num);
  8621. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8622. SERIAL_PROTOCOL(mesh_home_z_search);
  8623. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8624. SERIAL_PROTOCOL(x_dimension);
  8625. SERIAL_PROTOCOLPGM(",");
  8626. SERIAL_PROTOCOL(y_dimension);
  8627. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8628. while (mesh_point != x_points_num * y_points_num) {
  8629. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8630. iy = mesh_point / x_points_num;
  8631. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8632. float z0 = 0.f;
  8633. /*destination[Z_AXIS] = mesh_home_z_search;
  8634. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8635. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8636. for(int8_t i=0; i < NUM_AXIS; i++) {
  8637. current_position[i] = destination[i];
  8638. }
  8639. st_synchronize();*/
  8640. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8641. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8642. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8643. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8644. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8645. set_current_to_destination();
  8646. st_synchronize();
  8647. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8648. delay_keep_alive(1000);
  8649. #ifdef MICROMETER_LOGGING
  8650. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8651. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8652. //strcat(data_wldsd, numb_wldsd);
  8653. //MYSERIAL.println(data_wldsd);
  8654. //delay(1000);
  8655. //delay(3000);
  8656. //t1 = millis();
  8657. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8658. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8659. memset(digit, 0, sizeof(digit));
  8660. //cli();
  8661. digitalWrite(D_REQUIRE, LOW);
  8662. for (int i = 0; i<13; i++)
  8663. {
  8664. //t1 = millis();
  8665. for (int j = 0; j < 4; j++)
  8666. {
  8667. while (digitalRead(D_DATACLOCK) == LOW) {}
  8668. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8669. //printf_P(PSTR("Done %d\n"), j);
  8670. bitWrite(digit[i], j, digitalRead(D_DATA));
  8671. }
  8672. //t_delay = (millis() - t1);
  8673. //SERIAL_PROTOCOLPGM(" ");
  8674. //SERIAL_PROTOCOL_F(t_delay, 5);
  8675. //SERIAL_PROTOCOLPGM(" ");
  8676. }
  8677. //sei();
  8678. digitalWrite(D_REQUIRE, HIGH);
  8679. mergeOutput[0] = '\0';
  8680. output = 0;
  8681. for (int r = 5; r <= 10; r++) //Merge digits
  8682. {
  8683. sprintf(str, "%d", digit[r]);
  8684. strcat(mergeOutput, str);
  8685. }
  8686. output = atof(mergeOutput);
  8687. if (digit[4] == 8) //Handle sign
  8688. {
  8689. output *= -1;
  8690. }
  8691. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8692. {
  8693. output *= 0.1;
  8694. }
  8695. //output = d_ReadData();
  8696. //row[ix] = current_position[Z_AXIS];
  8697. //row[ix] = d_ReadData();
  8698. row[ix] = output;
  8699. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8700. memset(data_wldsd, 0, sizeof(data_wldsd));
  8701. for (int i = 0; i < x_points_num; i++) {
  8702. SERIAL_PROTOCOLPGM(" ");
  8703. SERIAL_PROTOCOL_F(row[i], 5);
  8704. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8705. dtostrf(row[i], 7, 3, numb_wldsd);
  8706. strcat(data_wldsd, numb_wldsd);
  8707. }
  8708. card.write_command(data_wldsd);
  8709. SERIAL_PROTOCOLPGM("\n");
  8710. }
  8711. custom_message_state--;
  8712. mesh_point++;
  8713. lcd_update(1);
  8714. }
  8715. #endif //MICROMETER_LOGGING
  8716. card.closefile();
  8717. //clean_up_after_endstop_move(l_feedmultiply);
  8718. }
  8719. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8720. int t1 = 0;
  8721. int t_delay = 0;
  8722. int digit[13];
  8723. int m;
  8724. char str[3];
  8725. //String mergeOutput;
  8726. char mergeOutput[15];
  8727. float output;
  8728. int mesh_point = 0; //index number of calibration point
  8729. 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
  8730. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8731. float mesh_home_z_search = 4;
  8732. float row[x_points_num];
  8733. int ix = 0;
  8734. int iy = 0;
  8735. const char* filename_wldsd = "wldsd.txt";
  8736. char data_wldsd[70];
  8737. char numb_wldsd[10];
  8738. d_setup();
  8739. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8740. // We don't know where we are! HOME!
  8741. // Push the commands to the front of the message queue in the reverse order!
  8742. // There shall be always enough space reserved for these commands.
  8743. repeatcommand_front(); // repeat G80 with all its parameters
  8744. enquecommand_front_P(G28W0);
  8745. enquecommand_front_P((PSTR("G1 Z5")));
  8746. return;
  8747. }
  8748. unsigned int custom_message_type_old = custom_message_type;
  8749. unsigned int custom_message_state_old = custom_message_state;
  8750. custom_message_type = CustomMsg::MeshBedLeveling;
  8751. custom_message_state = (x_points_num * y_points_num) + 10;
  8752. lcd_update(1);
  8753. mbl.reset();
  8754. babystep_undo();
  8755. card.openFile(filename_wldsd, false);
  8756. current_position[Z_AXIS] = mesh_home_z_search;
  8757. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8758. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8759. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8760. int l_feedmultiply = setup_for_endstop_move(false);
  8761. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8762. SERIAL_PROTOCOL(x_points_num);
  8763. SERIAL_PROTOCOLPGM(",");
  8764. SERIAL_PROTOCOL(y_points_num);
  8765. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8766. SERIAL_PROTOCOL(mesh_home_z_search);
  8767. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8768. SERIAL_PROTOCOL(x_dimension);
  8769. SERIAL_PROTOCOLPGM(",");
  8770. SERIAL_PROTOCOL(y_dimension);
  8771. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8772. while (mesh_point != x_points_num * y_points_num) {
  8773. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8774. iy = mesh_point / x_points_num;
  8775. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8776. float z0 = 0.f;
  8777. current_position[Z_AXIS] = mesh_home_z_search;
  8778. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8779. st_synchronize();
  8780. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8781. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8782. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8783. st_synchronize();
  8784. 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
  8785. break;
  8786. card.closefile();
  8787. }
  8788. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8789. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8790. //strcat(data_wldsd, numb_wldsd);
  8791. //MYSERIAL.println(data_wldsd);
  8792. //_delay(1000);
  8793. //_delay(3000);
  8794. //t1 = _millis();
  8795. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8796. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8797. memset(digit, 0, sizeof(digit));
  8798. //cli();
  8799. digitalWrite(D_REQUIRE, LOW);
  8800. for (int i = 0; i<13; i++)
  8801. {
  8802. //t1 = _millis();
  8803. for (int j = 0; j < 4; j++)
  8804. {
  8805. while (digitalRead(D_DATACLOCK) == LOW) {}
  8806. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8807. bitWrite(digit[i], j, digitalRead(D_DATA));
  8808. }
  8809. //t_delay = (_millis() - t1);
  8810. //SERIAL_PROTOCOLPGM(" ");
  8811. //SERIAL_PROTOCOL_F(t_delay, 5);
  8812. //SERIAL_PROTOCOLPGM(" ");
  8813. }
  8814. //sei();
  8815. digitalWrite(D_REQUIRE, HIGH);
  8816. mergeOutput[0] = '\0';
  8817. output = 0;
  8818. for (int r = 5; r <= 10; r++) //Merge digits
  8819. {
  8820. sprintf(str, "%d", digit[r]);
  8821. strcat(mergeOutput, str);
  8822. }
  8823. output = atof(mergeOutput);
  8824. if (digit[4] == 8) //Handle sign
  8825. {
  8826. output *= -1;
  8827. }
  8828. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8829. {
  8830. output *= 0.1;
  8831. }
  8832. //output = d_ReadData();
  8833. //row[ix] = current_position[Z_AXIS];
  8834. memset(data_wldsd, 0, sizeof(data_wldsd));
  8835. for (int i = 0; i <3; i++) {
  8836. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8837. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8838. strcat(data_wldsd, numb_wldsd);
  8839. strcat(data_wldsd, ";");
  8840. }
  8841. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8842. dtostrf(output, 8, 5, numb_wldsd);
  8843. strcat(data_wldsd, numb_wldsd);
  8844. //strcat(data_wldsd, ";");
  8845. card.write_command(data_wldsd);
  8846. //row[ix] = d_ReadData();
  8847. row[ix] = output; // current_position[Z_AXIS];
  8848. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8849. for (int i = 0; i < x_points_num; i++) {
  8850. SERIAL_PROTOCOLPGM(" ");
  8851. SERIAL_PROTOCOL_F(row[i], 5);
  8852. }
  8853. SERIAL_PROTOCOLPGM("\n");
  8854. }
  8855. custom_message_state--;
  8856. mesh_point++;
  8857. lcd_update(1);
  8858. }
  8859. card.closefile();
  8860. clean_up_after_endstop_move(l_feedmultiply);
  8861. }
  8862. #endif //HEATBED_ANALYSIS
  8863. #ifndef PINDA_THERMISTOR
  8864. static void temp_compensation_start() {
  8865. custom_message_type = CustomMsg::TempCompPreheat;
  8866. custom_message_state = PINDA_HEAT_T + 1;
  8867. lcd_update(2);
  8868. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8869. current_position[E_AXIS] -= default_retraction;
  8870. }
  8871. plan_buffer_line_curposXYZE(400, active_extruder);
  8872. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8873. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8874. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8875. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8876. st_synchronize();
  8877. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8878. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8879. delay_keep_alive(1000);
  8880. custom_message_state = PINDA_HEAT_T - i;
  8881. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8882. else lcd_update(1);
  8883. }
  8884. custom_message_type = CustomMsg::Status;
  8885. custom_message_state = 0;
  8886. }
  8887. static void temp_compensation_apply() {
  8888. int i_add;
  8889. int z_shift = 0;
  8890. float z_shift_mm;
  8891. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8892. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8893. i_add = (target_temperature_bed - 60) / 10;
  8894. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  8895. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8896. }else {
  8897. //interpolation
  8898. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8899. }
  8900. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8901. 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);
  8902. st_synchronize();
  8903. plan_set_z_position(current_position[Z_AXIS]);
  8904. }
  8905. else {
  8906. //we have no temp compensation data
  8907. }
  8908. }
  8909. #endif //ndef PINDA_THERMISTOR
  8910. float temp_comp_interpolation(float inp_temperature) {
  8911. //cubic spline interpolation
  8912. int n, i, j;
  8913. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8914. int shift[10];
  8915. int temp_C[10];
  8916. n = 6; //number of measured points
  8917. shift[0] = 0;
  8918. for (i = 0; i < n; i++) {
  8919. if (i > 0) {
  8920. //read shift in steps from EEPROM
  8921. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  8922. }
  8923. temp_C[i] = 50 + i * 10; //temperature in C
  8924. #ifdef PINDA_THERMISTOR
  8925. constexpr int start_compensating_temp = 35;
  8926. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  8927. #ifdef SUPERPINDA_SUPPORT
  8928. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  8929. #endif //SUPERPINDA_SUPPORT
  8930. #else
  8931. temp_C[i] = 50 + i * 10; //temperature in C
  8932. #endif
  8933. x[i] = (float)temp_C[i];
  8934. f[i] = (float)shift[i];
  8935. }
  8936. if (inp_temperature < x[0]) return 0;
  8937. for (i = n - 1; i>0; i--) {
  8938. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  8939. h[i - 1] = x[i] - x[i - 1];
  8940. }
  8941. //*********** formation of h, s , f matrix **************
  8942. for (i = 1; i<n - 1; i++) {
  8943. m[i][i] = 2 * (h[i - 1] + h[i]);
  8944. if (i != 1) {
  8945. m[i][i - 1] = h[i - 1];
  8946. m[i - 1][i] = h[i - 1];
  8947. }
  8948. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  8949. }
  8950. //*********** forward elimination **************
  8951. for (i = 1; i<n - 2; i++) {
  8952. temp = (m[i + 1][i] / m[i][i]);
  8953. for (j = 1; j <= n - 1; j++)
  8954. m[i + 1][j] -= temp*m[i][j];
  8955. }
  8956. //*********** backward substitution *********
  8957. for (i = n - 2; i>0; i--) {
  8958. sum = 0;
  8959. for (j = i; j <= n - 2; j++)
  8960. sum += m[i][j] * s[j];
  8961. s[i] = (m[i][n - 1] - sum) / m[i][i];
  8962. }
  8963. for (i = 0; i<n - 1; i++)
  8964. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  8965. a = (s[i + 1] - s[i]) / (6 * h[i]);
  8966. b = s[i] / 2;
  8967. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  8968. d = f[i];
  8969. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  8970. }
  8971. return sum;
  8972. }
  8973. #ifdef PINDA_THERMISTOR
  8974. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  8975. {
  8976. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  8977. if (!calibration_status_pinda()) return 0;
  8978. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  8979. }
  8980. #endif //PINDA_THERMISTOR
  8981. void long_pause() //long pause print
  8982. {
  8983. st_synchronize();
  8984. start_pause_print = _millis();
  8985. // Stop heaters
  8986. heating_status = HeatingStatus::NO_HEATING;
  8987. setAllTargetHotends(0);
  8988. // Lift z
  8989. raise_z_above(current_position[Z_AXIS] + Z_PAUSE_LIFT, true);
  8990. // Move XY to side
  8991. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  8992. current_position[X_AXIS] = X_PAUSE_POS;
  8993. current_position[Y_AXIS] = Y_PAUSE_POS;
  8994. plan_buffer_line_curposXYZE(50);
  8995. }
  8996. // did we come here from a thermal error?
  8997. if(get_temp_error()) {
  8998. // time to stop the error beep
  8999. WRITE(BEEPER, LOW);
  9000. } else {
  9001. // Turn off the print fan
  9002. fanSpeed = 0;
  9003. }
  9004. }
  9005. void serialecho_temperatures() {
  9006. float tt = degHotend(active_extruder);
  9007. SERIAL_PROTOCOLPGM("T:");
  9008. SERIAL_PROTOCOL(tt);
  9009. SERIAL_PROTOCOLPGM(" E:");
  9010. SERIAL_PROTOCOL((int)active_extruder);
  9011. SERIAL_PROTOCOLPGM(" B:");
  9012. SERIAL_PROTOCOL_F(degBed(), 1);
  9013. SERIAL_PROTOCOLLN();
  9014. }
  9015. #ifdef UVLO_SUPPORT
  9016. void uvlo_drain_reset()
  9017. {
  9018. // burn all that residual power
  9019. wdt_enable(WDTO_1S);
  9020. WRITE(BEEPER,HIGH);
  9021. lcd_clear();
  9022. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9023. while(1);
  9024. }
  9025. void uvlo_()
  9026. {
  9027. unsigned long time_start = _millis();
  9028. bool sd_print = card.sdprinting;
  9029. // Conserve power as soon as possible.
  9030. #ifdef LCD_BL_PIN
  9031. backlightMode = BACKLIGHT_MODE_DIM;
  9032. backlightLevel_LOW = 0;
  9033. backlight_update();
  9034. #endif //LCD_BL_PIN
  9035. disable_x();
  9036. disable_y();
  9037. #ifdef TMC2130
  9038. tmc2130_set_current_h(Z_AXIS, 20);
  9039. tmc2130_set_current_r(Z_AXIS, 20);
  9040. tmc2130_set_current_h(E_AXIS, 20);
  9041. tmc2130_set_current_r(E_AXIS, 20);
  9042. #endif //TMC2130
  9043. // Stop all heaters
  9044. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9045. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9046. setAllTargetHotends(0);
  9047. setTargetBed(0);
  9048. // Calculate the file position, from which to resume this print.
  9049. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9050. {
  9051. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9052. sd_position -= sdlen_planner;
  9053. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9054. sd_position -= sdlen_cmdqueue;
  9055. if (sd_position < 0) sd_position = 0;
  9056. }
  9057. // save the global state at planning time
  9058. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9059. uint16_t feedrate_bckp;
  9060. if (current_block && !pos_invalid)
  9061. {
  9062. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9063. feedrate_bckp = current_block->gcode_feedrate;
  9064. saved_segment_idx = current_block->segment_idx;
  9065. }
  9066. else
  9067. {
  9068. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9069. feedrate_bckp = feedrate;
  9070. saved_segment_idx = 0;
  9071. }
  9072. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9073. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9074. // get the physical Z for further manipulation.
  9075. bool mbl_was_active = mbl.active;
  9076. mbl.active = false;
  9077. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9078. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9079. // are in action.
  9080. planner_abort_hard();
  9081. // Store the print logical Z position, which we need to recover (a slight error here would be
  9082. // recovered on the next Gcode instruction, while a physical location error would not)
  9083. float logical_z = current_position[Z_AXIS];
  9084. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9085. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9086. // Store the print E position before we lose track
  9087. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9088. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9089. // Clean the input command queue, inhibit serial processing using saved_printing
  9090. cmdqueue_reset();
  9091. card.sdprinting = false;
  9092. saved_printing = true;
  9093. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9094. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9095. planner_aborted = false;
  9096. sei();
  9097. // Retract
  9098. current_position[E_AXIS] -= default_retraction;
  9099. plan_buffer_line_curposXYZE(95);
  9100. st_synchronize();
  9101. disable_e0();
  9102. // Read out the current Z motor microstep counter to move the axis up towards
  9103. // a full step before powering off. NOTE: we need to ensure to schedule more
  9104. // than "dropsegments" steps in order to move (this is always the case here
  9105. // due to UVLO_Z_AXIS_SHIFT being used)
  9106. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9107. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9108. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9109. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9110. + UVLO_Z_AXIS_SHIFT;
  9111. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9112. st_synchronize();
  9113. poweroff_z();
  9114. // Write the file position.
  9115. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9116. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9117. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9118. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9119. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9120. // Scale the z value to 1u resolution.
  9121. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9122. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9123. }
  9124. // Write the _final_ Z position and motor microstep counter (unused).
  9125. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9126. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9127. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9128. // Store the current position.
  9129. if (pos_invalid)
  9130. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9131. else
  9132. {
  9133. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9134. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9135. }
  9136. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9137. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9138. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9139. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9140. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9141. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9142. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9143. #if EXTRUDERS > 1
  9144. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9145. #if EXTRUDERS > 2
  9146. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9147. #endif
  9148. #endif
  9149. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9150. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9151. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9152. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9153. // Store the saved target
  9154. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9155. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9156. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9157. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9158. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9159. #ifdef LIN_ADVANCE
  9160. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9161. #endif
  9162. // Finaly store the "power outage" flag.
  9163. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9164. // Increment power failure counter
  9165. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9166. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9167. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9168. WRITE(BEEPER,HIGH);
  9169. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9170. poweron_z();
  9171. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9172. plan_buffer_line_curposXYZE(500);
  9173. st_synchronize();
  9174. wdt_enable(WDTO_1S);
  9175. while(1);
  9176. }
  9177. void uvlo_tiny()
  9178. {
  9179. unsigned long time_start = _millis();
  9180. // Conserve power as soon as possible.
  9181. disable_x();
  9182. disable_y();
  9183. disable_e0();
  9184. #ifdef TMC2130
  9185. tmc2130_set_current_h(Z_AXIS, 20);
  9186. tmc2130_set_current_r(Z_AXIS, 20);
  9187. #endif //TMC2130
  9188. // Stop all heaters
  9189. setAllTargetHotends(0);
  9190. setTargetBed(0);
  9191. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9192. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9193. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9194. // Disable MBL (if not already) to work with physical coordinates.
  9195. mbl.active = false;
  9196. planner_abort_hard();
  9197. // Allow for small roundoffs to be ignored
  9198. 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])
  9199. {
  9200. // Clean the input command queue, inhibit serial processing using saved_printing
  9201. cmdqueue_reset();
  9202. card.sdprinting = false;
  9203. saved_printing = true;
  9204. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9205. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9206. planner_aborted = false;
  9207. sei();
  9208. // The axis was moved: adjust Z as done on a regular UVLO.
  9209. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9210. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9211. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9212. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9213. + UVLO_TINY_Z_AXIS_SHIFT;
  9214. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9215. st_synchronize();
  9216. poweroff_z();
  9217. // Update Z position
  9218. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9219. // Update the _final_ Z motor microstep counter (unused).
  9220. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9221. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9222. }
  9223. // Update the the "power outage" flag.
  9224. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9225. // Increment power failure counter
  9226. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9227. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9228. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9229. uvlo_drain_reset();
  9230. }
  9231. #endif //UVLO_SUPPORT
  9232. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9233. void setup_fan_interrupt() {
  9234. //INT7
  9235. DDRE &= ~(1 << 7); //input pin
  9236. PORTE &= ~(1 << 7); //no internal pull-up
  9237. //start with sensing rising edge
  9238. EICRB &= ~(1 << 6);
  9239. EICRB |= (1 << 7);
  9240. //enable INT7 interrupt
  9241. EIMSK |= (1 << 7);
  9242. }
  9243. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9244. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9245. ISR(INT7_vect) {
  9246. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9247. #ifdef FAN_SOFT_PWM
  9248. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9249. #else //FAN_SOFT_PWM
  9250. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9251. #endif //FAN_SOFT_PWM
  9252. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9253. t_fan_rising_edge = millis_nc();
  9254. }
  9255. else { //interrupt was triggered by falling edge
  9256. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9257. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9258. }
  9259. }
  9260. EICRB ^= (1 << 6); //change edge
  9261. }
  9262. #endif
  9263. #ifdef UVLO_SUPPORT
  9264. void setup_uvlo_interrupt() {
  9265. DDRE &= ~(1 << 4); //input pin
  9266. PORTE &= ~(1 << 4); //no internal pull-up
  9267. // sensing falling edge
  9268. EICRB |= (1 << 0);
  9269. EICRB &= ~(1 << 1);
  9270. // enable INT4 interrupt
  9271. EIMSK |= (1 << 4);
  9272. // check if power was lost before we armed the interrupt
  9273. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9274. {
  9275. SERIAL_ECHOLNPGM("INT4");
  9276. uvlo_drain_reset();
  9277. }
  9278. }
  9279. ISR(INT4_vect) {
  9280. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9281. SERIAL_ECHOLNPGM("INT4");
  9282. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9283. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9284. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9285. }
  9286. void recover_print(uint8_t automatic) {
  9287. char cmd[30];
  9288. lcd_update_enable(true);
  9289. lcd_update(2);
  9290. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9291. // Recover position, temperatures and extrude_multipliers
  9292. bool mbl_was_active = recover_machine_state_after_power_panic();
  9293. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9294. // and second also so one may remove the excess priming material.
  9295. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9296. {
  9297. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9298. enquecommand(cmd);
  9299. }
  9300. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9301. // transformation status. G28 will not touch Z when MBL is off.
  9302. enquecommand_P(PSTR("G28 X Y"));
  9303. // Set the target bed and nozzle temperatures and wait.
  9304. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9305. enquecommand(cmd);
  9306. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9307. enquecommand(cmd);
  9308. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9309. enquecommand(cmd);
  9310. enquecommand_P(PSTR("M83")); //E axis relative mode
  9311. // If not automatically recoreverd (long power loss)
  9312. if(automatic == 0){
  9313. //Extrude some filament to stabilize the pressure
  9314. enquecommand_P(PSTR("G1 E5 F120"));
  9315. // Retract to be consistent with a short pause
  9316. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9317. enquecommand(cmd);
  9318. }
  9319. 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]);
  9320. // Restart the print.
  9321. restore_print_from_eeprom(mbl_was_active);
  9322. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9323. }
  9324. bool recover_machine_state_after_power_panic()
  9325. {
  9326. // 1) Preset some dummy values for the XY axes
  9327. current_position[X_AXIS] = 0;
  9328. current_position[Y_AXIS] = 0;
  9329. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9330. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9331. bool mbl_was_active = false;
  9332. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9333. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9334. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9335. // Scale the z value to 10u resolution.
  9336. int16_t v;
  9337. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9338. if (v != 0)
  9339. mbl_was_active = true;
  9340. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9341. }
  9342. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9343. // The current position after power panic is moved to the next closest 0th full step.
  9344. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9345. // Recover last E axis position
  9346. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9347. // 3) Initialize the logical to physical coordinate system transformation.
  9348. world2machine_initialize();
  9349. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9350. // print_mesh_bed_leveling_table();
  9351. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9352. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9353. babystep_load();
  9354. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9355. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9356. clamp_to_software_endstops(current_position);
  9357. set_destination_to_current();
  9358. plan_set_position_curposXYZE();
  9359. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9360. print_world_coordinates();
  9361. // 6) Power up the Z motors, mark their positions as known.
  9362. axis_known_position[Z_AXIS] = true;
  9363. enable_z();
  9364. // 7) Recover the target temperatures.
  9365. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9366. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9367. // 8) Recover extruder multipilers
  9368. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9369. #if EXTRUDERS > 1
  9370. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9371. #if EXTRUDERS > 2
  9372. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9373. #endif
  9374. #endif
  9375. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9376. // 9) Recover the saved target
  9377. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9378. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9379. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9380. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9381. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9382. #ifdef LIN_ADVANCE
  9383. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9384. #endif
  9385. return mbl_was_active;
  9386. }
  9387. void restore_print_from_eeprom(bool mbl_was_active) {
  9388. int feedrate_rec;
  9389. int feedmultiply_rec;
  9390. uint8_t fan_speed_rec;
  9391. char cmd[48];
  9392. char filename[FILENAME_LENGTH];
  9393. uint8_t depth = 0;
  9394. char dir_name[9];
  9395. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9396. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9397. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9398. SERIAL_ECHOPGM("Feedrate:");
  9399. MYSERIAL.print(feedrate_rec);
  9400. SERIAL_ECHOPGM(", feedmultiply:");
  9401. MYSERIAL.println(feedmultiply_rec);
  9402. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9403. MYSERIAL.println(int(depth));
  9404. for (uint8_t i = 0; i < depth; i++) {
  9405. for (uint8_t j = 0; j < 8; j++) {
  9406. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9407. }
  9408. dir_name[8] = '\0';
  9409. MYSERIAL.println(dir_name);
  9410. // strcpy(card.dir_names[i], dir_name);
  9411. card.chdir(dir_name, false);
  9412. }
  9413. for (uint8_t i = 0; i < 8; i++) {
  9414. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9415. }
  9416. filename[8] = '\0';
  9417. MYSERIAL.print(filename);
  9418. strcat_P(filename, PSTR(".gco"));
  9419. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9420. enquecommand(cmd);
  9421. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9422. SERIAL_ECHOPGM("Position read from eeprom:");
  9423. MYSERIAL.println(position);
  9424. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9425. // without shifting Z along the way. This requires performing the move without mbl.
  9426. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9427. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9428. if (pos_x != X_COORD_INVALID)
  9429. {
  9430. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9431. enquecommand(cmd);
  9432. }
  9433. // Enable MBL and switch to logical positioning
  9434. if (mbl_was_active)
  9435. enquecommand_P(PSTR("PRUSA MBL V1"));
  9436. // Move the Z axis down to the print, in logical coordinates.
  9437. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9438. enquecommand(cmd);
  9439. // Restore acceleration settings
  9440. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9441. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9442. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9443. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9444. enquecommand(cmd);
  9445. // Unretract.
  9446. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9447. enquecommand(cmd);
  9448. // Recover final E axis position and mode
  9449. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9450. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9451. enquecommand(cmd);
  9452. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9453. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9454. // Set the feedrates saved at the power panic.
  9455. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9456. enquecommand(cmd);
  9457. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9458. enquecommand(cmd);
  9459. // Set the fan speed saved at the power panic.
  9460. strcpy_P(cmd, PSTR("M106 S"));
  9461. strcat(cmd, itostr3(int(fan_speed_rec)));
  9462. enquecommand(cmd);
  9463. // Set a position in the file.
  9464. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9465. enquecommand(cmd);
  9466. enquecommand_P(PSTR("G4 S0"));
  9467. enquecommand_P(PSTR("PRUSA uvlo"));
  9468. }
  9469. #endif //UVLO_SUPPORT
  9470. //! @brief Immediately stop print moves
  9471. //!
  9472. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9473. //! If printing from sd card, position in file is saved.
  9474. //! If printing from USB, line number is saved.
  9475. //!
  9476. //! @param z_move
  9477. //! @param e_move
  9478. void stop_and_save_print_to_ram(float z_move, float e_move)
  9479. {
  9480. if (saved_printing) return;
  9481. #if 0
  9482. unsigned char nplanner_blocks;
  9483. #endif
  9484. unsigned char nlines;
  9485. uint16_t sdlen_planner;
  9486. uint16_t sdlen_cmdqueue;
  9487. cli();
  9488. if (card.sdprinting) {
  9489. #if 0
  9490. nplanner_blocks = number_of_blocks();
  9491. #endif
  9492. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9493. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9494. saved_sdpos -= sdlen_planner;
  9495. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9496. saved_sdpos -= sdlen_cmdqueue;
  9497. saved_printing_type = PRINTING_TYPE_SD;
  9498. }
  9499. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9500. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9501. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9502. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9503. saved_sdpos -= nlines;
  9504. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9505. saved_printing_type = PRINTING_TYPE_USB;
  9506. }
  9507. else {
  9508. saved_printing_type = PRINTING_TYPE_NONE;
  9509. //not sd printing nor usb printing
  9510. }
  9511. #if 0
  9512. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9513. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9514. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9515. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9516. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9517. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9518. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9519. {
  9520. card.setIndex(saved_sdpos);
  9521. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9522. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9523. MYSERIAL.print(char(card.get()));
  9524. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9525. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9526. MYSERIAL.print(char(card.get()));
  9527. SERIAL_ECHOLNPGM("End of command buffer");
  9528. }
  9529. {
  9530. // Print the content of the planner buffer, line by line:
  9531. card.setIndex(saved_sdpos);
  9532. int8_t iline = 0;
  9533. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9534. SERIAL_ECHOPGM("Planner line (from file): ");
  9535. MYSERIAL.print(int(iline), DEC);
  9536. SERIAL_ECHOPGM(", length: ");
  9537. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9538. SERIAL_ECHOPGM(", steps: (");
  9539. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9540. SERIAL_ECHOPGM(",");
  9541. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9542. SERIAL_ECHOPGM(",");
  9543. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9544. SERIAL_ECHOPGM(",");
  9545. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9546. SERIAL_ECHOPGM("), events: ");
  9547. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9548. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9549. MYSERIAL.print(char(card.get()));
  9550. }
  9551. }
  9552. {
  9553. // Print the content of the command buffer, line by line:
  9554. int8_t iline = 0;
  9555. union {
  9556. struct {
  9557. char lo;
  9558. char hi;
  9559. } lohi;
  9560. uint16_t value;
  9561. } sdlen_single;
  9562. int _bufindr = bufindr;
  9563. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9564. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9565. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9566. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9567. }
  9568. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9569. MYSERIAL.print(int(iline), DEC);
  9570. SERIAL_ECHOPGM(", type: ");
  9571. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9572. SERIAL_ECHOPGM(", len: ");
  9573. MYSERIAL.println(sdlen_single.value, DEC);
  9574. // Print the content of the buffer line.
  9575. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9576. SERIAL_ECHOPGM("Buffer line (from file): ");
  9577. MYSERIAL.println(int(iline), DEC);
  9578. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9579. MYSERIAL.print(char(card.get()));
  9580. if (-- _buflen == 0)
  9581. break;
  9582. // First skip the current command ID and iterate up to the end of the string.
  9583. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9584. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9585. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9586. // If the end of the buffer was empty,
  9587. if (_bufindr == sizeof(cmdbuffer)) {
  9588. // skip to the start and find the nonzero command.
  9589. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9590. }
  9591. }
  9592. }
  9593. #endif
  9594. // save the global state at planning time
  9595. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9596. if (current_block && !pos_invalid)
  9597. {
  9598. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9599. saved_feedrate2 = current_block->gcode_feedrate;
  9600. saved_segment_idx = current_block->segment_idx;
  9601. // 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);
  9602. }
  9603. else
  9604. {
  9605. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9606. saved_feedrate2 = feedrate;
  9607. saved_segment_idx = 0;
  9608. }
  9609. planner_abort_hard(); //abort printing
  9610. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9611. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9612. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9613. saved_active_extruder = active_extruder; //save active_extruder
  9614. saved_extruder_temperature = degTargetHotend(active_extruder);
  9615. saved_bed_temperature = degTargetBed();
  9616. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9617. saved_fan_speed = fanSpeed;
  9618. cmdqueue_reset(); //empty cmdqueue
  9619. card.sdprinting = false;
  9620. // card.closefile();
  9621. saved_printing = true;
  9622. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9623. st_reset_timer();
  9624. sei();
  9625. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9626. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9627. // the caller can continue processing. This is used during powerpanic to save the state as we
  9628. // move away from the print.
  9629. char buf[48];
  9630. if(e_move)
  9631. {
  9632. // First unretract (relative extrusion)
  9633. if(!saved_extruder_relative_mode){
  9634. enquecommand(PSTR("M83"), true);
  9635. }
  9636. //retract 45mm/s
  9637. // A single sprintf may not be faster, but is definitely 20B shorter
  9638. // than a sequence of commands building the string piece by piece
  9639. // A snprintf would have been a safer call, but since it is not used
  9640. // in the whole program, its implementation would bring more bytes to the total size
  9641. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9642. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9643. enquecommand(buf, false);
  9644. }
  9645. if(z_move)
  9646. {
  9647. // Then lift Z axis
  9648. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9649. enquecommand(buf, false);
  9650. }
  9651. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9652. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9653. repeatcommand_front();
  9654. }
  9655. }
  9656. //! @brief Restore print from ram
  9657. //!
  9658. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9659. //! print fan speed, waits for extruder temperature restore, then restores
  9660. //! position and continues print moves.
  9661. //!
  9662. //! Internally lcd_update() is called by wait_for_heater().
  9663. //!
  9664. //! @param e_move
  9665. void restore_print_from_ram_and_continue(float e_move)
  9666. {
  9667. if (!saved_printing) return;
  9668. #ifdef FANCHECK
  9669. // Do not allow resume printing if fans are still not ok
  9670. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9671. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9672. #endif
  9673. // restore bed temperature (bed can be disabled during a thermal warning)
  9674. if (degBed() != saved_bed_temperature)
  9675. setTargetBed(saved_bed_temperature);
  9676. // restore active_extruder
  9677. active_extruder = saved_active_extruder;
  9678. fanSpeed = saved_fan_speed;
  9679. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  9680. {
  9681. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  9682. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9683. wait_for_heater(_millis(), saved_active_extruder);
  9684. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9685. }
  9686. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9687. float e = saved_pos[E_AXIS] - e_move;
  9688. plan_set_e_position(e);
  9689. #ifdef FANCHECK
  9690. fans_check_enabled = false;
  9691. #endif
  9692. // do not restore XY for commands that do not require that
  9693. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9694. {
  9695. saved_pos[X_AXIS] = current_position[X_AXIS];
  9696. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9697. }
  9698. //first move print head in XY to the saved position:
  9699. 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);
  9700. //then move Z
  9701. 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);
  9702. //and finaly unretract (35mm/s)
  9703. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9704. st_synchronize();
  9705. #ifdef FANCHECK
  9706. fans_check_enabled = true;
  9707. #endif
  9708. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9709. feedrate = saved_feedrate2;
  9710. feedmultiply = saved_feedmultiply2;
  9711. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9712. set_destination_to_current();
  9713. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9714. card.setIndex(saved_sdpos);
  9715. sdpos_atomic = saved_sdpos;
  9716. card.sdprinting = true;
  9717. }
  9718. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9719. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9720. serial_count = 0;
  9721. FlushSerialRequestResend();
  9722. }
  9723. else {
  9724. //not sd printing nor usb printing
  9725. }
  9726. lcd_setstatuspgm(MSG_WELCOME);
  9727. saved_printing_type = PRINTING_TYPE_NONE;
  9728. saved_printing = false;
  9729. planner_aborted = true; // unroll the stack
  9730. }
  9731. // Cancel the state related to a currently saved print
  9732. void cancel_saved_printing()
  9733. {
  9734. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9735. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9736. saved_printing_type = PRINTING_TYPE_NONE;
  9737. saved_printing = false;
  9738. }
  9739. void print_world_coordinates()
  9740. {
  9741. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9742. }
  9743. void print_physical_coordinates()
  9744. {
  9745. 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));
  9746. }
  9747. void print_mesh_bed_leveling_table()
  9748. {
  9749. SERIAL_ECHOPGM("mesh bed leveling: ");
  9750. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9751. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9752. MYSERIAL.print(mbl.z_values[y][x], 3);
  9753. SERIAL_ECHO(' ');
  9754. }
  9755. SERIAL_ECHOLN();
  9756. }
  9757. uint8_t calc_percent_done()
  9758. {
  9759. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9760. uint8_t percent_done = 0;
  9761. #ifdef TMC2130
  9762. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9763. {
  9764. percent_done = print_percent_done_normal;
  9765. }
  9766. else if (print_percent_done_silent <= 100)
  9767. {
  9768. percent_done = print_percent_done_silent;
  9769. }
  9770. #else
  9771. if (print_percent_done_normal <= 100)
  9772. {
  9773. percent_done = print_percent_done_normal;
  9774. }
  9775. #endif //TMC2130
  9776. else
  9777. {
  9778. percent_done = card.percentDone();
  9779. }
  9780. return percent_done;
  9781. }
  9782. static void print_time_remaining_init()
  9783. {
  9784. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9785. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9786. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9787. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9788. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9789. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9790. }
  9791. void load_filament_final_feed()
  9792. {
  9793. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9794. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9795. }
  9796. //! @brief Wait for user to check the state
  9797. //! @par nozzle_temp nozzle temperature to load filament
  9798. void M600_check_state(float nozzle_temp)
  9799. {
  9800. lcd_change_fil_state = 0;
  9801. while (lcd_change_fil_state != 1)
  9802. {
  9803. lcd_change_fil_state = 0;
  9804. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9805. lcd_alright();
  9806. KEEPALIVE_STATE(IN_HANDLER);
  9807. switch(lcd_change_fil_state)
  9808. {
  9809. // Filament failed to load so load it again
  9810. case 2:
  9811. if (MMU2::mmu2.Enabled()){
  9812. //@@TODO mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  9813. } else {
  9814. M600_load_filament_movements();
  9815. }
  9816. break;
  9817. // Filament loaded properly but color is not clear
  9818. case 3:
  9819. st_synchronize();
  9820. load_filament_final_feed();
  9821. lcd_loading_color();
  9822. st_synchronize();
  9823. break;
  9824. // Everything good
  9825. default:
  9826. lcd_change_success();
  9827. break;
  9828. }
  9829. }
  9830. }
  9831. //! @brief Wait for user action
  9832. //!
  9833. //! Beep, manage nozzle heater and wait for user to start unload filament
  9834. //! If times out, active extruder temperature is set to 0.
  9835. //!
  9836. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9837. void M600_wait_for_user(float HotendTempBckp) {
  9838. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9839. int counterBeep = 0;
  9840. unsigned long waiting_start_time = _millis();
  9841. uint8_t wait_for_user_state = 0;
  9842. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9843. bool bFirst=true;
  9844. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9845. manage_heater();
  9846. manage_inactivity(true);
  9847. #if BEEPER > 0
  9848. if (counterBeep == 500) {
  9849. counterBeep = 0;
  9850. }
  9851. SET_OUTPUT(BEEPER);
  9852. if (counterBeep == 0) {
  9853. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9854. {
  9855. bFirst=false;
  9856. WRITE(BEEPER, HIGH);
  9857. }
  9858. }
  9859. if (counterBeep == 20) {
  9860. WRITE(BEEPER, LOW);
  9861. }
  9862. counterBeep++;
  9863. #endif //BEEPER > 0
  9864. switch (wait_for_user_state) {
  9865. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9866. delay_keep_alive(4);
  9867. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9868. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9869. wait_for_user_state = 1;
  9870. setAllTargetHotends(0);
  9871. st_synchronize();
  9872. disable_e0();
  9873. disable_e1();
  9874. disable_e2();
  9875. }
  9876. break;
  9877. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9878. delay_keep_alive(4);
  9879. if (lcd_clicked()) {
  9880. setTargetHotend(HotendTempBckp, active_extruder);
  9881. lcd_wait_for_heater();
  9882. wait_for_user_state = 2;
  9883. }
  9884. break;
  9885. case 2: //waiting for nozzle to reach target temperature
  9886. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9887. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9888. waiting_start_time = _millis();
  9889. wait_for_user_state = 0;
  9890. }
  9891. else {
  9892. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9893. lcd_set_cursor(1, 4);
  9894. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  9895. }
  9896. break;
  9897. }
  9898. }
  9899. WRITE(BEEPER, LOW);
  9900. }
  9901. void M600_load_filament_movements()
  9902. {
  9903. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  9904. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  9905. load_filament_final_feed();
  9906. lcd_loading_filament();
  9907. st_synchronize();
  9908. }
  9909. void M600_load_filament() {
  9910. //load filament for single material and MMU
  9911. lcd_wait_interact();
  9912. //load_filament_time = _millis();
  9913. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9914. while(!lcd_clicked())
  9915. {
  9916. manage_heater();
  9917. manage_inactivity(true);
  9918. #ifdef FILAMENT_SENSOR
  9919. if (fsensor.getFilamentLoadEvent()) {
  9920. Sound_MakeCustom(50,1000,false);
  9921. break;
  9922. }
  9923. #endif //FILAMENT_SENSOR
  9924. }
  9925. KEEPALIVE_STATE(IN_HANDLER);
  9926. M600_load_filament_movements();
  9927. Sound_MakeCustom(50,1000,false);
  9928. lcd_update_enable(false);
  9929. }
  9930. //! @brief Wait for click
  9931. //!
  9932. //! Set
  9933. void marlin_wait_for_click()
  9934. {
  9935. int8_t busy_state_backup = busy_state;
  9936. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9937. lcd_consume_click();
  9938. while(!lcd_clicked())
  9939. {
  9940. manage_heater();
  9941. manage_inactivity(true);
  9942. lcd_update(0);
  9943. }
  9944. KEEPALIVE_STATE(busy_state_backup);
  9945. }
  9946. #define FIL_LOAD_LENGTH 60
  9947. #ifdef PSU_Delta
  9948. bool bEnableForce_z;
  9949. void init_force_z()
  9950. {
  9951. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  9952. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  9953. disable_force_z();
  9954. }
  9955. void check_force_z()
  9956. {
  9957. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  9958. init_force_z(); // causes enforced switching into disable-state
  9959. }
  9960. void disable_force_z()
  9961. {
  9962. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  9963. bEnableForce_z=false;
  9964. // switching to silent mode
  9965. #ifdef TMC2130
  9966. tmc2130_mode=TMC2130_MODE_SILENT;
  9967. update_mode_profile();
  9968. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  9969. #endif // TMC2130
  9970. }
  9971. void enable_force_z()
  9972. {
  9973. if(bEnableForce_z)
  9974. return; // motor already enabled (may be ;-p )
  9975. bEnableForce_z=true;
  9976. // mode recovering
  9977. #ifdef TMC2130
  9978. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  9979. update_mode_profile();
  9980. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  9981. #endif // TMC2130
  9982. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  9983. }
  9984. #endif // PSU_Delta