Marlin_main.cpp 392 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744
  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. int fanSpeed=0;
  195. uint8_t newFanSpeed = 0;
  196. #ifdef FWRETRACT
  197. bool retracted[EXTRUDERS]={false
  198. #if EXTRUDERS > 1
  199. , false
  200. #if EXTRUDERS > 2
  201. , false
  202. #endif
  203. #endif
  204. };
  205. bool retracted_swap[EXTRUDERS]={false
  206. #if EXTRUDERS > 1
  207. , false
  208. #if EXTRUDERS > 2
  209. , false
  210. #endif
  211. #endif
  212. };
  213. float retract_length_swap = RETRACT_LENGTH_SWAP;
  214. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  215. #endif
  216. #ifdef PS_DEFAULT_OFF
  217. bool powersupply = false;
  218. #else
  219. bool powersupply = true;
  220. #endif
  221. bool cancel_heatup = false;
  222. int8_t busy_state = NOT_BUSY;
  223. static long prev_busy_signal_ms = -1;
  224. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  225. const char errormagic[] PROGMEM = "Error:";
  226. const char echomagic[] PROGMEM = "echo:";
  227. const char G28W0[] PROGMEM = "G28 W0";
  228. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  229. // that they can be used later for various logical checks
  230. #define X_COORD_INVALID (X_MIN_POS-1)
  231. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  232. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  233. uint16_t saved_segment_idx = 0;
  234. // storing estimated time to end of print counted by slicer
  235. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  236. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  237. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  238. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  239. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  240. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  241. uint32_t IP_address = 0;
  242. //===========================================================================
  243. //=============================Private Variables=============================
  244. //===========================================================================
  245. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  246. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  247. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  248. // For tracing an arc
  249. static float offset[3] = {0.0, 0.0, 0.0};
  250. // Current feedrate
  251. float feedrate = 1500.0;
  252. // Feedrate for the next move
  253. static float next_feedrate;
  254. // Original feedrate saved during homing moves
  255. static float saved_feedrate;
  256. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  257. //static float tt = 0;
  258. //static float bt = 0;
  259. //Inactivity shutdown variables
  260. static LongTimer previous_millis_cmd;
  261. unsigned long max_inactive_time = 0;
  262. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  263. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  264. unsigned long starttime=0;
  265. unsigned long stoptime=0;
  266. ShortTimer usb_timer;
  267. bool Stopped=false;
  268. #if NUM_SERVOS > 0
  269. Servo servos[NUM_SERVOS];
  270. #endif
  271. bool target_direction;
  272. //Insert variables if CHDK is defined
  273. #ifdef CHDK
  274. unsigned long chdkHigh = 0;
  275. bool chdkActive = false;
  276. #endif
  277. //! @name RAM save/restore printing
  278. //! @{
  279. bool saved_printing = false; //!< Print is paused and saved in RAM
  280. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  281. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  282. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  283. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  284. static int saved_feedmultiply2 = 0;
  285. static float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  286. static bool saved_extruder_relative_mode = false;
  287. int saved_fan_speed = 0; //!< Print fan speed
  288. //! @}
  289. static int saved_feedmultiply_mm = 100;
  290. class AutoReportFeatures {
  291. union {
  292. struct {
  293. uint8_t temp : 1; //Temperature flag
  294. uint8_t fans : 1; //Fans flag
  295. uint8_t pos: 1; //Position flag
  296. uint8_t ar4 : 1; //Unused
  297. uint8_t ar5 : 1; //Unused
  298. uint8_t ar6 : 1; //Unused
  299. uint8_t ar7 : 1; //Unused
  300. } __attribute__((packed)) bits;
  301. uint8_t byte;
  302. } arFunctionsActive;
  303. uint8_t auto_report_period;
  304. public:
  305. LongTimer auto_report_timer;
  306. AutoReportFeatures():auto_report_period(0){
  307. #if defined(AUTO_REPORT)
  308. arFunctionsActive.byte = 0xff;
  309. #else
  310. arFunctionsActive.byte = 0;
  311. #endif //AUTO_REPORT
  312. }
  313. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  314. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  315. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  316. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  317. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  318. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  319. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  320. /// sets the autoreporting timer's period
  321. /// setting it to zero stops the timer
  322. void SetPeriod(uint8_t p){
  323. auto_report_period = p;
  324. if (auto_report_period != 0){
  325. auto_report_timer.start();
  326. } else{
  327. auto_report_timer.stop();
  328. }
  329. }
  330. inline void TimerStart() { auto_report_timer.start(); }
  331. inline bool TimerRunning()const { return auto_report_timer.running(); }
  332. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  333. };
  334. AutoReportFeatures autoReportFeatures;
  335. //===========================================================================
  336. //=============================Routines======================================
  337. //===========================================================================
  338. static bool setTargetedHotend(int code, uint8_t &extruder);
  339. static void print_time_remaining_init();
  340. static void wait_for_heater(long codenum, uint8_t extruder);
  341. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  342. static void gcode_M105(uint8_t extruder);
  343. #ifndef PINDA_THERMISTOR
  344. static void temp_compensation_start();
  345. static void temp_compensation_apply();
  346. #endif
  347. #ifdef PRUSA_SN_SUPPORT
  348. static uint8_t get_PRUSA_SN(char* SN);
  349. #endif //PRUSA_SN_SUPPORT
  350. uint16_t gcode_in_progress = 0;
  351. uint16_t mcode_in_progress = 0;
  352. void serial_echopair_P(const char *s_P, float v)
  353. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  354. void serial_echopair_P(const char *s_P, double v)
  355. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  356. void serial_echopair_P(const char *s_P, unsigned long v)
  357. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  358. void serialprintPGM(const char *str) {
  359. while(uint8_t ch = pgm_read_byte(str)) {
  360. MYSERIAL.write((char)ch);
  361. ++str;
  362. }
  363. }
  364. void serialprintlnPGM(const char *str) {
  365. serialprintPGM(str);
  366. MYSERIAL.println();
  367. }
  368. #ifdef SDSUPPORT
  369. #include "SdFatUtil.h"
  370. int freeMemory() { return SdFatUtil::FreeRam(); }
  371. #else
  372. extern "C" {
  373. extern unsigned int __bss_end;
  374. extern unsigned int __heap_start;
  375. extern void *__brkval;
  376. int freeMemory() {
  377. int free_memory;
  378. if ((int)__brkval == 0)
  379. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  380. else
  381. free_memory = ((int)&free_memory) - ((int)__brkval);
  382. return free_memory;
  383. }
  384. }
  385. #endif //!SDSUPPORT
  386. void setup_killpin()
  387. {
  388. #if defined(KILL_PIN) && KILL_PIN > -1
  389. SET_INPUT(KILL_PIN);
  390. WRITE(KILL_PIN,HIGH);
  391. #endif
  392. }
  393. // Set home pin
  394. void setup_homepin(void)
  395. {
  396. #if defined(HOME_PIN) && HOME_PIN > -1
  397. SET_INPUT(HOME_PIN);
  398. WRITE(HOME_PIN,HIGH);
  399. #endif
  400. }
  401. void setup_photpin()
  402. {
  403. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  404. SET_OUTPUT(PHOTOGRAPH_PIN);
  405. WRITE(PHOTOGRAPH_PIN, LOW);
  406. #endif
  407. }
  408. void setup_powerhold()
  409. {
  410. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  411. SET_OUTPUT(SUICIDE_PIN);
  412. WRITE(SUICIDE_PIN, HIGH);
  413. #endif
  414. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  415. SET_OUTPUT(PS_ON_PIN);
  416. #if defined(PS_DEFAULT_OFF)
  417. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  418. #else
  419. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  420. #endif
  421. #endif
  422. }
  423. void suicide()
  424. {
  425. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  426. SET_OUTPUT(SUICIDE_PIN);
  427. WRITE(SUICIDE_PIN, LOW);
  428. #endif
  429. }
  430. void servo_init()
  431. {
  432. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  433. servos[0].attach(SERVO0_PIN);
  434. #endif
  435. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  436. servos[1].attach(SERVO1_PIN);
  437. #endif
  438. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  439. servos[2].attach(SERVO2_PIN);
  440. #endif
  441. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  442. servos[3].attach(SERVO3_PIN);
  443. #endif
  444. #if (NUM_SERVOS >= 5)
  445. #error "TODO: enter initalisation code for more servos"
  446. #endif
  447. }
  448. bool __attribute__((noinline)) printer_active() {
  449. return IS_SD_PRINTING
  450. || usb_timer.running()
  451. || isPrintPaused
  452. || (custom_message_type == CustomMsg::TempCal)
  453. || saved_printing
  454. || (lcd_commands_type == LcdCommands::Layer1Cal)
  455. || mmu_print_saved
  456. || homing_flag
  457. || mesh_bed_leveling_flag;
  458. }
  459. bool fans_check_enabled = true;
  460. #ifdef TMC2130
  461. void crashdet_stop_and_save_print()
  462. {
  463. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  464. }
  465. void crashdet_restore_print_and_continue()
  466. {
  467. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  468. // babystep_apply();
  469. }
  470. void crashdet_fmt_error(char* buf, uint8_t mask)
  471. {
  472. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  473. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  474. *buf++ = ' ';
  475. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  476. }
  477. void crashdet_detected(uint8_t mask)
  478. {
  479. st_synchronize();
  480. static uint8_t crashDet_counter = 0;
  481. static uint8_t crashDet_axes = 0;
  482. bool automatic_recovery_after_crash = true;
  483. char msg[LCD_WIDTH+1] = "";
  484. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  485. crashDet_counter = 0;
  486. }
  487. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  488. automatic_recovery_after_crash = false;
  489. }
  490. crashDetTimer.start();
  491. crashDet_axes |= mask;
  492. lcd_update_enable(true);
  493. lcd_clear();
  494. lcd_update(2);
  495. if (mask & X_AXIS_MASK)
  496. {
  497. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  498. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  499. }
  500. if (mask & Y_AXIS_MASK)
  501. {
  502. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  503. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  504. }
  505. lcd_update_enable(true);
  506. lcd_update(2);
  507. // prepare the status message with the _current_ axes status
  508. crashdet_fmt_error(msg, mask);
  509. lcd_setstatus(msg);
  510. gcode_G28(true, true, false); //home X and Y
  511. if (automatic_recovery_after_crash) {
  512. enquecommand_P(PSTR("CRASH_RECOVER"));
  513. }else{
  514. setTargetHotend(0, active_extruder);
  515. // notify the user of *all* the axes previously affected, not just the last one
  516. lcd_update_enable(false);
  517. lcd_clear();
  518. crashdet_fmt_error(msg, crashDet_axes);
  519. crashDet_axes = 0;
  520. lcd_print(msg);
  521. // ask whether to resume printing
  522. lcd_set_cursor(0, 1);
  523. lcd_puts_P(_T(MSG_RESUME_PRINT));
  524. lcd_putc('?');
  525. uint8_t yesno = lcd_show_yes_no_and_wait(false);
  526. if (yesno == LCD_LEFT_BUTTON_CHOICE)
  527. {
  528. enquecommand_P(PSTR("CRASH_RECOVER"));
  529. }
  530. else // LCD_MIDDLE_BUTTON_CHOICE
  531. {
  532. enquecommand_P(PSTR("CRASH_CANCEL"));
  533. }
  534. }
  535. }
  536. void crashdet_recover()
  537. {
  538. crashdet_restore_print_and_continue();
  539. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  540. }
  541. void crashdet_cancel()
  542. {
  543. saved_printing = false;
  544. tmc2130_sg_stop_on_crash = true;
  545. if (saved_printing_type == PRINTING_TYPE_SD) {
  546. lcd_print_stop();
  547. }else if(saved_printing_type == PRINTING_TYPE_USB){
  548. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  549. cmdqueue_reset();
  550. }
  551. }
  552. #endif //TMC2130
  553. void failstats_reset_print()
  554. {
  555. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  556. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  557. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  558. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  559. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  560. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  561. }
  562. void softReset()
  563. {
  564. cli();
  565. wdt_enable(WDTO_15MS);
  566. while(1);
  567. }
  568. #ifdef MESH_BED_LEVELING
  569. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  570. #endif
  571. static void factory_reset_stats(){
  572. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  573. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  574. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  575. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  576. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  577. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  578. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  579. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  580. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  581. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  582. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  583. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  584. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  585. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  586. }
  587. // Factory reset function
  588. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  589. // Level input parameter sets depth of reset
  590. static void factory_reset(char level)
  591. {
  592. lcd_clear();
  593. Sound_MakeCustom(100,0,false);
  594. switch (level) {
  595. case 0: // Level 0: Language reset
  596. lang_reset();
  597. break;
  598. case 1: //Level 1: Reset statistics
  599. factory_reset_stats();
  600. lcd_menu_statistics();
  601. break;
  602. case 2: // Level 2: Prepare for shipping
  603. factory_reset_stats();
  604. // FALLTHRU
  605. case 3: // Level 3: Preparation after being serviced
  606. // Force language selection at the next boot up.
  607. lang_reset();
  608. // Force the "Follow calibration flow" message at the next boot up.
  609. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  610. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  611. farm_disable();
  612. #ifdef FILAMENT_SENSOR
  613. fsensor.setEnabled(true);
  614. fsensor.setAutoLoadEnabled(true, true);
  615. fsensor.setRunoutEnabled(true, true);
  616. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  617. fsensor.setJamDetectionEnabled(true, true);
  618. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  619. #endif //FILAMENT_SENSOR
  620. break;
  621. case 4:
  622. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  623. // Erase EEPROM
  624. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  625. eeprom_update_byte((uint8_t*)i, 0xFF);
  626. menu_progressbar_update(i);
  627. }
  628. menu_progressbar_finish();
  629. softReset();
  630. break;
  631. default:
  632. break;
  633. }
  634. }
  635. extern "C" {
  636. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  637. }
  638. int uart_putchar(char c, FILE *)
  639. {
  640. MYSERIAL.write(c);
  641. return 0;
  642. }
  643. void lcd_splash()
  644. {
  645. lcd_clear(); // clears display and homes screen
  646. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  647. }
  648. void factory_reset()
  649. {
  650. KEEPALIVE_STATE(PAUSED_FOR_USER);
  651. if (!READ(BTN_ENC))
  652. {
  653. _delay_ms(1000);
  654. if (!READ(BTN_ENC))
  655. {
  656. lcd_clear();
  657. lcd_puts_P(PSTR("Factory RESET"));
  658. SET_OUTPUT(BEEPER);
  659. if(eSoundMode!=e_SOUND_MODE_SILENT)
  660. WRITE(BEEPER, HIGH);
  661. while (!READ(BTN_ENC));
  662. WRITE(BEEPER, LOW);
  663. _delay_ms(2000);
  664. char level = reset_menu();
  665. factory_reset(level);
  666. switch (level) {
  667. case 0:
  668. case 1:
  669. case 2:
  670. case 3:
  671. case 4: _delay_ms(0); break;
  672. }
  673. }
  674. }
  675. KEEPALIVE_STATE(IN_HANDLER);
  676. }
  677. void show_fw_version_warnings() {
  678. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  679. switch (FW_DEV_VERSION) {
  680. 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
  681. 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
  682. case(FW_VERSION_DEVEL):
  683. case(FW_VERSION_DEBUG):
  684. lcd_update_enable(false);
  685. lcd_clear();
  686. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  687. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  688. #else
  689. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  690. #endif
  691. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  692. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  693. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  694. lcd_wait_for_click();
  695. break;
  696. // 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
  697. }
  698. lcd_update_enable(true);
  699. }
  700. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  701. //! @brief try to check if firmware is on right type of printer
  702. static void check_if_fw_is_on_right_printer() {
  703. if (fsensor.probeOtherType()) {
  704. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  705. }
  706. }
  707. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  708. uint8_t check_printer_version()
  709. {
  710. uint8_t version_changed = 0;
  711. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  712. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  713. if (printer_type != PRINTER_TYPE) {
  714. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  715. else version_changed |= 0b10;
  716. }
  717. if (motherboard != MOTHERBOARD) {
  718. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  719. else version_changed |= 0b01;
  720. }
  721. return version_changed;
  722. }
  723. #ifdef BOOTAPP
  724. #include "bootapp.h" //bootloader support
  725. #endif //BOOTAPP
  726. #if (LANG_MODE != 0) //secondary language support
  727. #ifdef XFLASH
  728. // language update from external flash
  729. #define LANGBOOT_BLOCKSIZE 0x1000u
  730. #define LANGBOOT_RAMBUFFER 0x0800
  731. void update_sec_lang_from_external_flash()
  732. {
  733. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  734. {
  735. uint8_t lang = boot_reserved >> 3;
  736. uint8_t state = boot_reserved & 0x07;
  737. lang_table_header_t header;
  738. uint32_t src_addr;
  739. if (lang_get_header(lang, &header, &src_addr))
  740. {
  741. lcd_puts_at_P(1,3,PSTR("Language update."));
  742. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  743. _delay(100);
  744. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  745. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  746. {
  747. cli();
  748. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  749. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  750. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  751. if (state == 0)
  752. {
  753. //TODO - check header integrity
  754. }
  755. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  756. }
  757. else
  758. {
  759. //TODO - check sec lang data integrity
  760. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  761. }
  762. }
  763. }
  764. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  765. }
  766. #ifdef DEBUG_XFLASH
  767. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  768. {
  769. lang_table_header_t header;
  770. uint8_t count = 0;
  771. uint32_t addr = 0x00000;
  772. while (1)
  773. {
  774. printf_P(_n("LANGTABLE%d:"), count);
  775. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  776. if (header.magic != LANG_MAGIC)
  777. {
  778. puts_P(_n("NG!"));
  779. break;
  780. }
  781. puts_P(_n("OK"));
  782. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  783. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  784. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  785. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  786. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  787. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  788. addr += header.size;
  789. codes[count] = header.code;
  790. count ++;
  791. }
  792. return count;
  793. }
  794. void list_sec_lang_from_external_flash()
  795. {
  796. uint16_t codes[8];
  797. uint8_t count = lang_xflash_enum_codes(codes);
  798. printf_P(_n("XFlash lang count = %hhd\n"), count);
  799. }
  800. #endif //DEBUG_XFLASH
  801. #endif //XFLASH
  802. #endif //(LANG_MODE != 0)
  803. static void fw_crash_init()
  804. {
  805. #ifdef XFLASH_DUMP
  806. dump_crash_reason crash_reason;
  807. if(xfdump_check_state(&crash_reason))
  808. {
  809. // always signal to the host that a dump is available for retrieval
  810. puts_P(_N("// action:dump_available"));
  811. #ifdef EMERGENCY_DUMP
  812. if(crash_reason != dump_crash_reason::manual &&
  813. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  814. {
  815. lcd_show_fullscreen_message_and_wait_P(
  816. _n("FW crash detected! "
  817. "You can continue printing. "
  818. "Debug data available for analysis. "
  819. "Contact support to submit details."));
  820. }
  821. #endif
  822. }
  823. #else //XFLASH_DUMP
  824. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  825. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  826. {
  827. lcd_beeper_quick_feedback();
  828. lcd_clear();
  829. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  830. switch(crash_reason)
  831. {
  832. case dump_crash_reason::stack_error:
  833. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  834. break;
  835. case dump_crash_reason::watchdog:
  836. lcd_puts_P(_n("Watchdog timeout"));
  837. break;
  838. case dump_crash_reason::bad_isr:
  839. lcd_puts_P(_n("Bad interrupt"));
  840. break;
  841. default:
  842. lcd_print((uint8_t)crash_reason);
  843. break;
  844. }
  845. lcd_wait_for_click();
  846. }
  847. #endif //XFLASH_DUMP
  848. // prevent crash prompts to reappear once acknowledged
  849. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  850. }
  851. static void xflash_err_msg()
  852. {
  853. puts_P(_n("XFLASH not responding."));
  854. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  855. }
  856. // "Setup" function is called by the Arduino framework on startup.
  857. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  858. // are initialized by the main() routine provided by the Arduino framework.
  859. void setup()
  860. {
  861. timer2_init(); // enables functional millis
  862. ultralcd_init();
  863. spi_init();
  864. lcd_splash();
  865. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  866. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  867. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  868. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  869. MYSERIAL.begin(BAUDRATE);
  870. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  871. stdout = uartout;
  872. #ifdef XFLASH
  873. bool xflash_success = xflash_init();
  874. uint8_t optiboot_status = 1;
  875. if (xflash_success)
  876. {
  877. optiboot_status = optiboot_xflash_enter();
  878. #if (LANG_MODE != 0) //secondary language support
  879. update_sec_lang_from_external_flash();
  880. #endif //(LANG_MODE != 0)
  881. }
  882. #else
  883. const bool xflash_success = true;
  884. #endif //XFLASH
  885. setup_killpin();
  886. setup_powerhold();
  887. farm_mode_init();
  888. #ifdef TMC2130
  889. if( FarmOrUserECool() ){
  890. //increased extruder current (PFW363)
  891. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  892. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  893. }
  894. #endif //TMC2130
  895. #ifdef PRUSA_SN_SUPPORT
  896. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  897. //SN is valid only if it is NULL terminated and starts with "CZPX".
  898. {
  899. char SN[20];
  900. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  901. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  902. {
  903. if (!get_PRUSA_SN(SN))
  904. {
  905. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  906. puts_P(PSTR("SN updated"));
  907. }
  908. else
  909. puts_P(PSTR("SN update failed"));
  910. }
  911. }
  912. #endif //PRUSA_SN_SUPPORT
  913. #ifndef XFLASH
  914. SERIAL_PROTOCOLLNPGM("start");
  915. #else
  916. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  917. SERIAL_PROTOCOLLNPGM("start");
  918. #endif
  919. SERIAL_ECHO_START;
  920. puts_P(PSTR(" " FW_VERSION_FULL));
  921. if (eeprom_read_byte((uint8_t *)EEPROM_MMU_ENABLED)) {
  922. MMU2::mmu2.Start();
  923. }
  924. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  925. #ifdef DEBUG_SEC_LANG
  926. lang_table_header_t header;
  927. uint32_t src_addr = 0x00000;
  928. if (lang_get_header(1, &header, &src_addr))
  929. {
  930. printf_P(
  931. _n(
  932. " _src_addr = 0x%08lx\n"
  933. " _lt_magic = 0x%08lx %S\n"
  934. " _lt_size = 0x%04x (%d)\n"
  935. " _lt_count = 0x%04x (%d)\n"
  936. " _lt_chsum = 0x%04x\n"
  937. " _lt_code = 0x%04x (%c%c)\n"
  938. " _lt_resv1 = 0x%08lx\n"
  939. ),
  940. src_addr,
  941. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  942. header.size, header.size,
  943. header.count, header.count,
  944. header.checksum,
  945. header.code, header.code >> 8, header.code & 0xff,
  946. header.signature
  947. );
  948. #if 0
  949. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  950. for (uint16_t i = 0; i < 1024; i++)
  951. {
  952. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  953. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  954. if ((i % 16) == 15) putchar('\n');
  955. }
  956. #endif
  957. uint16_t sum = 0;
  958. for (uint16_t i = 0; i < header.size; i++)
  959. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  960. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  961. sum -= header.checksum; //subtract checksum
  962. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  963. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  964. if (sum == header.checksum)
  965. puts_P(_n("Checksum OK"));
  966. else
  967. puts_P(_n("Checksum NG"));
  968. }
  969. else
  970. puts_P(_n("lang_get_header failed!"));
  971. #if 0
  972. for (uint16_t i = 0; i < 1024*10; i++)
  973. {
  974. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  975. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  976. if ((i % 16) == 15) putchar('\n');
  977. }
  978. #endif
  979. #if 0
  980. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  981. for (int i = 0; i < 4096; ++i) {
  982. int b = eeprom_read_byte((unsigned char*)i);
  983. if (b != 255) {
  984. SERIAL_ECHO(i);
  985. SERIAL_ECHO(":");
  986. SERIAL_ECHO(b);
  987. SERIAL_ECHOLN("");
  988. }
  989. }
  990. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  991. #endif
  992. #endif //DEBUG_SEC_LANG
  993. // Check startup - does nothing if bootloader sets MCUSR to 0
  994. byte mcu = MCUSR;
  995. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  996. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  997. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  998. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  999. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1000. if (mcu & 1) puts_P(MSG_POWERUP);
  1001. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1002. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1003. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1004. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1005. MCUSR = 0;
  1006. //SERIAL_ECHORPGM(MSG_MARLIN);
  1007. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1008. #ifdef STRING_VERSION_CONFIG_H
  1009. #ifdef STRING_CONFIG_H_AUTHOR
  1010. SERIAL_ECHO_START;
  1011. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1012. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1013. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1014. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1015. SERIAL_ECHOPGM("Compiled: ");
  1016. SERIAL_ECHOLNPGM(__DATE__);
  1017. #endif
  1018. #endif
  1019. SERIAL_ECHO_START;
  1020. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1021. SERIAL_ECHO(freeMemory());
  1022. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1023. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1024. //lcd_update_enable(false); // why do we need this?? - andre
  1025. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1026. bool previous_settings_retrieved = false;
  1027. uint8_t hw_changed = check_printer_version();
  1028. 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
  1029. previous_settings_retrieved = Config_RetrieveSettings();
  1030. }
  1031. else { //printer version was changed so use default settings
  1032. Config_ResetDefault();
  1033. }
  1034. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1035. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1036. // performed inside the soft_pwm_isr)
  1037. SdFatUtil::set_stack_guard();
  1038. // Initialize pwm/temperature loops
  1039. soft_pwm_init();
  1040. temp_mgr_init();
  1041. #ifdef EXTRUDER_ALTFAN_DETECT
  1042. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1043. if (extruder_altfan_detect())
  1044. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1045. else
  1046. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1047. #endif //EXTRUDER_ALTFAN_DETECT
  1048. plan_init(); // Initialize planner;
  1049. factory_reset();
  1050. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1051. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1052. {
  1053. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1054. // where all the EEPROM entries are set to 0x0ff.
  1055. // Once a firmware boots up, it forces at least a language selection, which changes
  1056. // EEPROM_LANG to number lower than 0x0ff.
  1057. // 1) Set a high power mode.
  1058. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1059. #ifdef TMC2130
  1060. tmc2130_mode = TMC2130_MODE_NORMAL;
  1061. #endif //TMC2130
  1062. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1063. }
  1064. lcd_encoder_diff=0;
  1065. #ifdef TMC2130
  1066. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1067. if (silentMode == 0xff) silentMode = 0;
  1068. tmc2130_mode = TMC2130_MODE_NORMAL;
  1069. if (lcd_crash_detect_enabled() && !farm_mode)
  1070. {
  1071. lcd_crash_detect_enable();
  1072. puts_P(_N("CrashDetect ENABLED!"));
  1073. }
  1074. else
  1075. {
  1076. lcd_crash_detect_disable();
  1077. puts_P(_N("CrashDetect DISABLED"));
  1078. }
  1079. #ifdef TMC2130_LINEARITY_CORRECTION
  1080. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1081. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1082. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1083. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1084. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1085. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1086. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1087. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1088. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1089. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1090. #endif //TMC2130_LINEARITY_CORRECTION
  1091. #ifdef TMC2130_VARIABLE_RESOLUTION
  1092. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1093. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1094. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1095. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1096. #else //TMC2130_VARIABLE_RESOLUTION
  1097. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1098. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1099. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1100. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1101. #endif //TMC2130_VARIABLE_RESOLUTION
  1102. #endif //TMC2130
  1103. st_init(); // Initialize stepper, this enables interrupts!
  1104. #ifdef TMC2130
  1105. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1106. update_mode_profile();
  1107. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1108. #endif //TMC2130
  1109. #ifdef PSU_Delta
  1110. init_force_z(); // ! important for correct Z-axis initialization
  1111. #endif // PSU_Delta
  1112. setup_photpin();
  1113. #if 0
  1114. servo_init();
  1115. #endif
  1116. // Reset the machine correction matrix.
  1117. // It does not make sense to load the correction matrix until the machine is homed.
  1118. world2machine_reset();
  1119. // Initialize current_position accounting for software endstops to
  1120. // avoid unexpected initial shifts on the first move
  1121. clamp_to_software_endstops(current_position);
  1122. plan_set_position_curposXYZE();
  1123. // Show the xflash error message now that serial, lcd and encoder are available
  1124. if (!xflash_success)
  1125. xflash_err_msg();
  1126. #ifdef FILAMENT_SENSOR
  1127. fsensor.init();
  1128. #endif //FILAMENT_SENSOR
  1129. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1130. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1131. #endif
  1132. setup_homepin();
  1133. #if defined(Z_AXIS_ALWAYS_ON)
  1134. enable_z();
  1135. #endif
  1136. // The farm monitoring SW may accidentally expect
  1137. // 2 messages of "printer started" to consider a printer working.
  1138. prusa_statistics(8);
  1139. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1140. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1141. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1142. // but this times out if a blocking dialog is shown in setup().
  1143. card.initsd();
  1144. #ifdef DEBUG_SD_SPEED_TEST
  1145. if (card.cardOK)
  1146. {
  1147. uint8_t* buff = (uint8_t*)block_buffer;
  1148. uint32_t block = 0;
  1149. uint32_t sumr = 0;
  1150. uint32_t sumw = 0;
  1151. for (int i = 0; i < 1024; i++)
  1152. {
  1153. uint32_t u = _micros();
  1154. bool res = card.card.readBlock(i, buff);
  1155. u = _micros() - u;
  1156. if (res)
  1157. {
  1158. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1159. sumr += u;
  1160. u = _micros();
  1161. res = card.card.writeBlock(i, buff);
  1162. u = _micros() - u;
  1163. if (res)
  1164. {
  1165. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1166. sumw += u;
  1167. }
  1168. else
  1169. {
  1170. printf_P(PSTR("writeBlock %4d error\n"), i);
  1171. break;
  1172. }
  1173. }
  1174. else
  1175. {
  1176. printf_P(PSTR("readBlock %4d error\n"), i);
  1177. break;
  1178. }
  1179. }
  1180. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1181. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1182. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1183. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1184. }
  1185. else
  1186. printf_P(PSTR("Card NG!\n"));
  1187. #endif //DEBUG_SD_SPEED_TEST
  1188. eeprom_init();
  1189. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1190. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1191. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1192. #if (LANG_MODE != 0) //secondary language support
  1193. #ifdef DEBUG_XFLASH
  1194. XFLASH_SPI_ENTER();
  1195. uint8_t uid[8]; // 64bit unique id
  1196. xflash_rd_uid(uid);
  1197. puts_P(_n("XFLASH UID="));
  1198. for (uint8_t i = 0; i < 8; i ++)
  1199. printf_P(PSTR("%02x"), uid[i]);
  1200. putchar('\n');
  1201. list_sec_lang_from_external_flash();
  1202. #endif //DEBUG_XFLASH
  1203. // lang_reset();
  1204. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1205. lcd_language();
  1206. #ifdef DEBUG_SEC_LANG
  1207. uint16_t sec_lang_code = lang_get_code(1);
  1208. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1209. 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);
  1210. lang_print_sec_lang(uartout);
  1211. #endif //DEBUG_SEC_LANG
  1212. #endif //(LANG_MODE != 0)
  1213. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1214. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1215. }
  1216. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1217. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1218. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1219. int16_t z_shift = 0;
  1220. for (uint8_t i = 0; i < 5; i++) {
  1221. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1222. }
  1223. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1224. }
  1225. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1226. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1227. }
  1228. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1229. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1230. }
  1231. //mbl_mode_init();
  1232. mbl_settings_init();
  1233. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1234. if (SilentModeMenu_MMU == 255) {
  1235. SilentModeMenu_MMU = 1;
  1236. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1237. }
  1238. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1239. setup_fan_interrupt();
  1240. #endif //DEBUG_DISABLE_FANCHECK
  1241. #ifndef DEBUG_DISABLE_STARTMSGS
  1242. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1243. if (!farm_mode) {
  1244. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1245. check_if_fw_is_on_right_printer();
  1246. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1247. show_fw_version_warnings();
  1248. }
  1249. switch (hw_changed) {
  1250. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1251. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1252. case(0b01):
  1253. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1254. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1255. break;
  1256. case(0b10):
  1257. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1258. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1259. break;
  1260. case(0b11):
  1261. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1262. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1263. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1264. break;
  1265. default: break; //no change, show no message
  1266. }
  1267. if (!previous_settings_retrieved) {
  1268. 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
  1269. Config_StoreSettings();
  1270. }
  1271. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1272. lcd_wizard(WizState::Run);
  1273. }
  1274. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1275. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1276. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1277. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1278. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1279. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1280. // Show the message.
  1281. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1282. }
  1283. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1284. // Show the message.
  1285. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1286. lcd_update_enable(true);
  1287. }
  1288. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1289. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1290. lcd_update_enable(true);
  1291. }
  1292. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1293. // Show the message.
  1294. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1295. }
  1296. }
  1297. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1298. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1299. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1300. update_current_firmware_version_to_eeprom();
  1301. lcd_selftest();
  1302. }
  1303. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1304. KEEPALIVE_STATE(IN_PROCESS);
  1305. #endif //DEBUG_DISABLE_STARTMSGS
  1306. lcd_update_enable(true);
  1307. lcd_clear();
  1308. lcd_update(2);
  1309. // Store the currently running firmware into an eeprom,
  1310. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1311. update_current_firmware_version_to_eeprom();
  1312. #ifdef TMC2130
  1313. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1314. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1315. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1316. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1317. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1318. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1319. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1320. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1321. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1322. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1323. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1324. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1325. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1326. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1327. #endif //TMC2130
  1328. // report crash failures
  1329. fw_crash_init();
  1330. #ifdef UVLO_SUPPORT
  1331. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1332. /*
  1333. if (!lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1334. else {
  1335. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1336. lcd_update_enable(true);
  1337. lcd_update(2);
  1338. lcd_setstatuspgm(MSG_WELCOME);
  1339. }
  1340. */
  1341. manage_heater(); // Update temperatures
  1342. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1343. 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));
  1344. #endif
  1345. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1346. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1347. puts_P(_N("Automatic recovery!"));
  1348. #endif
  1349. recover_print(1);
  1350. }
  1351. else{
  1352. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1353. puts_P(_N("Normal recovery!"));
  1354. #endif
  1355. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) == LCD_LEFT_BUTTON_CHOICE) {
  1356. recover_print(0);
  1357. } else {
  1358. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1359. lcd_update_enable(true);
  1360. lcd_update(2);
  1361. lcd_setstatuspgm(MSG_WELCOME);
  1362. }
  1363. }
  1364. }
  1365. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1366. // the entire state machine initialized.
  1367. setup_uvlo_interrupt();
  1368. #endif //UVLO_SUPPORT
  1369. fCheckModeInit();
  1370. KEEPALIVE_STATE(NOT_BUSY);
  1371. #ifdef WATCHDOG
  1372. wdt_enable(WDTO_4S);
  1373. #ifdef EMERGENCY_HANDLERS
  1374. WDTCSR |= (1 << WDIE);
  1375. #endif //EMERGENCY_HANDLERS
  1376. #endif //WATCHDOG
  1377. }
  1378. static inline void crash_and_burn(dump_crash_reason reason)
  1379. {
  1380. WRITE(BEEPER, HIGH);
  1381. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1382. #ifdef EMERGENCY_DUMP
  1383. xfdump_full_dump_and_reset(reason);
  1384. #elif defined(EMERGENCY_SERIAL_DUMP)
  1385. if(emergency_serial_dump)
  1386. serial_dump_and_reset(reason);
  1387. #endif
  1388. softReset();
  1389. }
  1390. #ifdef EMERGENCY_HANDLERS
  1391. #ifdef WATCHDOG
  1392. ISR(WDT_vect)
  1393. {
  1394. crash_and_burn(dump_crash_reason::watchdog);
  1395. }
  1396. #endif
  1397. ISR(BADISR_vect)
  1398. {
  1399. crash_and_burn(dump_crash_reason::bad_isr);
  1400. }
  1401. #endif //EMERGENCY_HANDLERS
  1402. void stack_error() {
  1403. crash_and_burn(dump_crash_reason::stack_error);
  1404. }
  1405. /**
  1406. * Output autoreport values according to features requested in M155
  1407. */
  1408. #if defined(AUTO_REPORT)
  1409. void host_autoreport()
  1410. {
  1411. if (autoReportFeatures.TimerExpired())
  1412. {
  1413. if(autoReportFeatures.Temp()){
  1414. gcode_M105(active_extruder);
  1415. }
  1416. if(autoReportFeatures.Pos()){
  1417. gcode_M114();
  1418. }
  1419. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1420. if(autoReportFeatures.Fans()){
  1421. gcode_M123();
  1422. }
  1423. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1424. autoReportFeatures.TimerStart();
  1425. }
  1426. }
  1427. #endif //AUTO_REPORT
  1428. /**
  1429. * Output a "busy" message at regular intervals
  1430. * while the machine is not accepting commands.
  1431. */
  1432. void host_keepalive() {
  1433. #ifndef HOST_KEEPALIVE_FEATURE
  1434. return;
  1435. #endif //HOST_KEEPALIVE_FEATURE
  1436. if (farm_mode) return;
  1437. long ms = _millis();
  1438. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1439. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1440. switch (busy_state) {
  1441. case IN_HANDLER:
  1442. case IN_PROCESS:
  1443. SERIAL_ECHO_START;
  1444. SERIAL_ECHOLNPGM("busy: processing");
  1445. break;
  1446. case PAUSED_FOR_USER:
  1447. SERIAL_ECHO_START;
  1448. SERIAL_ECHOLNPGM("busy: paused for user");
  1449. break;
  1450. case PAUSED_FOR_INPUT:
  1451. SERIAL_ECHO_START;
  1452. SERIAL_ECHOLNPGM("busy: paused for input");
  1453. break;
  1454. default:
  1455. break;
  1456. }
  1457. }
  1458. prev_busy_signal_ms = ms;
  1459. }
  1460. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1461. // Before loop(), the setup() function is called by the main() routine.
  1462. void loop()
  1463. {
  1464. // Reset a previously aborted command, we can now start processing motion again
  1465. planner_aborted = false;
  1466. if(Stopped) {
  1467. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1468. // Signal to the host that we're currently busy waiting for supervision.
  1469. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1470. } else {
  1471. // Printer is available for processing, reset state
  1472. KEEPALIVE_STATE(NOT_BUSY);
  1473. }
  1474. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1475. usb_timer.start();
  1476. }
  1477. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1478. ;
  1479. }
  1480. #ifdef PRUSA_M28
  1481. if (prusa_sd_card_upload)
  1482. {
  1483. //we read byte-by byte
  1484. serial_read_stream();
  1485. }
  1486. else
  1487. #endif
  1488. {
  1489. get_command();
  1490. #ifdef SDSUPPORT
  1491. card.checkautostart(false);
  1492. #endif
  1493. if(buflen)
  1494. {
  1495. cmdbuffer_front_already_processed = false;
  1496. #ifdef SDSUPPORT
  1497. if(card.saving)
  1498. {
  1499. // Saving a G-code file onto an SD-card is in progress.
  1500. // Saving starts with M28, saving until M29 is seen.
  1501. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1502. card.write_command(CMDBUFFER_CURRENT_STRING);
  1503. if(card.logging)
  1504. process_commands();
  1505. else
  1506. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1507. } else {
  1508. card.closefile();
  1509. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1510. }
  1511. } else {
  1512. process_commands();
  1513. }
  1514. #else
  1515. process_commands();
  1516. #endif //SDSUPPORT
  1517. if (! cmdbuffer_front_already_processed && buflen)
  1518. {
  1519. // ptr points to the start of the block currently being processed.
  1520. // The first character in the block is the block type.
  1521. char *ptr = cmdbuffer + bufindr;
  1522. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1523. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1524. union {
  1525. struct {
  1526. char lo;
  1527. char hi;
  1528. } lohi;
  1529. uint16_t value;
  1530. } sdlen;
  1531. sdlen.value = 0;
  1532. {
  1533. // This block locks the interrupts globally for 3.25 us,
  1534. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1535. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1536. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1537. cli();
  1538. // Reset the command to something, which will be ignored by the power panic routine,
  1539. // so this buffer length will not be counted twice.
  1540. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1541. // Extract the current buffer length.
  1542. sdlen.lohi.lo = *ptr ++;
  1543. sdlen.lohi.hi = *ptr;
  1544. // and pass it to the planner queue.
  1545. planner_add_sd_length(sdlen.value);
  1546. sei();
  1547. }
  1548. }
  1549. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1550. cli();
  1551. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1552. // and one for each command to previous block in the planner queue.
  1553. planner_add_sd_length(1);
  1554. sei();
  1555. }
  1556. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1557. // this block's SD card length will not be counted twice as its command type has been replaced
  1558. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1559. cmdqueue_pop_front();
  1560. }
  1561. host_keepalive();
  1562. }
  1563. }
  1564. //check heater every n milliseconds
  1565. manage_heater();
  1566. manage_inactivity(isPrintPaused);
  1567. checkHitEndstops();
  1568. lcd_update(0);
  1569. #ifdef TMC2130
  1570. tmc2130_check_overtemp();
  1571. if (tmc2130_sg_crash)
  1572. {
  1573. uint8_t crash = tmc2130_sg_crash;
  1574. tmc2130_sg_crash = 0;
  1575. // crashdet_stop_and_save_print();
  1576. switch (crash)
  1577. {
  1578. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1579. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1580. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1581. }
  1582. }
  1583. #endif //TMC2130
  1584. MMU2::mmu2.mmu_loop();
  1585. }
  1586. #define DEFINE_PGM_READ_ANY(type, reader) \
  1587. static inline type pgm_read_any(const type *p) \
  1588. { return pgm_read_##reader##_near(p); }
  1589. DEFINE_PGM_READ_ANY(float, float);
  1590. DEFINE_PGM_READ_ANY(signed char, byte);
  1591. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1592. static const PROGMEM type array##_P[3] = \
  1593. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1594. static inline type array(uint8_t axis) \
  1595. { return pgm_read_any(&array##_P[axis]); } \
  1596. type array##_ext(uint8_t axis) \
  1597. { return pgm_read_any(&array##_P[axis]); }
  1598. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1599. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1600. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1601. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1602. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1603. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1604. static void axis_is_at_home(uint8_t axis) {
  1605. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1606. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1607. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1608. }
  1609. //! @return original feedmultiply
  1610. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1611. saved_feedrate = feedrate;
  1612. int l_feedmultiply = feedmultiply;
  1613. feedmultiply = 100;
  1614. previous_millis_cmd.start();
  1615. enable_endstops(enable_endstops_now);
  1616. return l_feedmultiply;
  1617. }
  1618. //! @param original_feedmultiply feedmultiply to restore
  1619. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1620. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1621. enable_endstops(false);
  1622. #endif
  1623. feedrate = saved_feedrate;
  1624. feedmultiply = original_feedmultiply;
  1625. previous_millis_cmd.start();
  1626. }
  1627. #ifdef ENABLE_AUTO_BED_LEVELING
  1628. #ifdef AUTO_BED_LEVELING_GRID
  1629. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1630. {
  1631. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1632. planeNormal.debug("planeNormal");
  1633. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1634. //bedLevel.debug("bedLevel");
  1635. //plan_bed_level_matrix.debug("bed level before");
  1636. //vector_3 uncorrected_position = plan_get_position_mm();
  1637. //uncorrected_position.debug("position before");
  1638. vector_3 corrected_position = plan_get_position();
  1639. // corrected_position.debug("position after");
  1640. current_position[X_AXIS] = corrected_position.x;
  1641. current_position[Y_AXIS] = corrected_position.y;
  1642. current_position[Z_AXIS] = corrected_position.z;
  1643. // put the bed at 0 so we don't go below it.
  1644. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1645. plan_set_position_curposXYZE();
  1646. }
  1647. #else // not AUTO_BED_LEVELING_GRID
  1648. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1649. plan_bed_level_matrix.set_to_identity();
  1650. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1651. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1652. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1653. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1654. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1655. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1656. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1657. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1658. vector_3 corrected_position = plan_get_position();
  1659. current_position[X_AXIS] = corrected_position.x;
  1660. current_position[Y_AXIS] = corrected_position.y;
  1661. current_position[Z_AXIS] = corrected_position.z;
  1662. // put the bed at 0 so we don't go below it.
  1663. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1664. plan_set_position_curposXYZE();
  1665. }
  1666. #endif // AUTO_BED_LEVELING_GRID
  1667. static void run_z_probe() {
  1668. plan_bed_level_matrix.set_to_identity();
  1669. feedrate = homing_feedrate[Z_AXIS];
  1670. // move down until you find the bed
  1671. float zPosition = -10;
  1672. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1673. st_synchronize();
  1674. // we have to let the planner know where we are right now as it is not where we said to go.
  1675. zPosition = st_get_position_mm(Z_AXIS);
  1676. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1677. // move up the retract distance
  1678. zPosition += home_retract_mm(Z_AXIS);
  1679. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1680. st_synchronize();
  1681. // move back down slowly to find bed
  1682. feedrate = homing_feedrate[Z_AXIS]/4;
  1683. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1684. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1685. st_synchronize();
  1686. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1687. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1688. plan_set_position_curposXYZE();
  1689. }
  1690. static void do_blocking_move_to(float x, float y, float z) {
  1691. float oldFeedRate = feedrate;
  1692. feedrate = homing_feedrate[Z_AXIS];
  1693. current_position[Z_AXIS] = z;
  1694. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1695. st_synchronize();
  1696. feedrate = XY_TRAVEL_SPEED;
  1697. current_position[X_AXIS] = x;
  1698. current_position[Y_AXIS] = y;
  1699. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1700. st_synchronize();
  1701. feedrate = oldFeedRate;
  1702. }
  1703. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1704. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1705. }
  1706. /// Probe bed height at position (x,y), returns the measured z value
  1707. static float probe_pt(float x, float y, float z_before) {
  1708. // move to right place
  1709. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1710. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1711. run_z_probe();
  1712. float measured_z = current_position[Z_AXIS];
  1713. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1714. SERIAL_PROTOCOLPGM(" x: ");
  1715. SERIAL_PROTOCOL(x);
  1716. SERIAL_PROTOCOLPGM(" y: ");
  1717. SERIAL_PROTOCOL(y);
  1718. SERIAL_PROTOCOLPGM(" z: ");
  1719. SERIAL_PROTOCOL(measured_z);
  1720. SERIAL_PROTOCOLPGM("\n");
  1721. return measured_z;
  1722. }
  1723. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1724. #ifdef LIN_ADVANCE
  1725. /**
  1726. * M900: Set and/or Get advance K factor
  1727. *
  1728. * K<factor> Set advance K factor
  1729. */
  1730. inline void gcode_M900() {
  1731. float newK = code_seen('K') ? code_value_float() : -2;
  1732. #ifdef LA_NOCOMPAT
  1733. if (newK >= 0 && newK < LA_K_MAX)
  1734. extruder_advance_K = newK;
  1735. else
  1736. SERIAL_ECHOLNPGM("K out of allowed range!");
  1737. #else
  1738. if (newK == 0)
  1739. {
  1740. extruder_advance_K = 0;
  1741. la10c_reset();
  1742. }
  1743. else
  1744. {
  1745. newK = la10c_value(newK);
  1746. if (newK < 0)
  1747. SERIAL_ECHOLNPGM("K out of allowed range!");
  1748. else
  1749. extruder_advance_K = newK;
  1750. }
  1751. #endif
  1752. SERIAL_ECHO_START;
  1753. SERIAL_ECHOPGM("Advance K=");
  1754. SERIAL_ECHOLN(extruder_advance_K);
  1755. }
  1756. #endif // LIN_ADVANCE
  1757. bool check_commands() {
  1758. bool end_command_found = false;
  1759. while (buflen)
  1760. {
  1761. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1762. if (!cmdbuffer_front_already_processed)
  1763. cmdqueue_pop_front();
  1764. cmdbuffer_front_already_processed = false;
  1765. }
  1766. return end_command_found;
  1767. }
  1768. /// @brief Safely move Z-axis by distance delta (mm)
  1769. /// @param delta travel distance in mm
  1770. /// @returns The actual travel distance in mm. Endstop may limit the requested move.
  1771. float raise_z(float delta)
  1772. {
  1773. float travel_z = current_position[Z_AXIS];
  1774. // Z needs raising
  1775. current_position[Z_AXIS] = target;
  1776. clamp_to_software_endstops(current_position);
  1777. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1778. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1779. #else
  1780. bool z_min_endstop = false;
  1781. #endif
  1782. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1783. {
  1784. // current position is known or very low, it's safe to raise Z
  1785. clamp_to_software_endstops(current_position);
  1786. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1787. st_synchronize();
  1788. // Get the final travel distance
  1789. travel_z = current_position[Z_AXIS] - travel_z;
  1790. } else {
  1791. // ensure Z is powered in normal mode to overcome initial load
  1792. enable_z();
  1793. st_synchronize();
  1794. // rely on crashguard to limit damage
  1795. bool z_endstop_enabled = enable_z_endstop(true);
  1796. #ifdef TMC2130
  1797. tmc2130_home_enter(Z_AXIS_MASK);
  1798. #endif //TMC2130
  1799. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1800. st_synchronize();
  1801. // Get the final travel distance
  1802. travel_z = st_get_position_mm(Z_AXIS) - travel_z;
  1803. #ifdef TMC2130
  1804. if (endstop_z_hit_on_purpose())
  1805. {
  1806. // not necessarily exact, but will avoid further vertical moves
  1807. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1808. plan_set_position_curposXYZE();
  1809. }
  1810. tmc2130_home_exit();
  1811. #endif //TMC2130
  1812. enable_z_endstop(z_endstop_enabled);
  1813. }
  1814. return travel_z;
  1815. }
  1816. // raise_z_above: slowly raise Z to the requested height
  1817. //
  1818. // contrarily to a simple move, this function will carefully plan a move
  1819. // when the current Z position is unknown. In such cases, stallguard is
  1820. // enabled and will prevent prolonged pushing against the Z tops
  1821. void raise_z_above(float target)
  1822. {
  1823. if (current_position[Z_AXIS] >= target)
  1824. return;
  1825. // Use absolute value in case the current position is unknown
  1826. raise_z(fabs(current_position[Z_AXIS] - target));
  1827. }
  1828. #ifdef TMC2130
  1829. bool calibrate_z_auto()
  1830. {
  1831. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1832. lcd_clear();
  1833. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1834. bool endstops_enabled = enable_endstops(true);
  1835. int axis_up_dir = -home_dir(Z_AXIS);
  1836. tmc2130_home_enter(Z_AXIS_MASK);
  1837. current_position[Z_AXIS] = 0;
  1838. plan_set_position_curposXYZE();
  1839. set_destination_to_current();
  1840. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1841. feedrate = homing_feedrate[Z_AXIS];
  1842. plan_buffer_line_destinationXYZE(feedrate / 60);
  1843. st_synchronize();
  1844. // current_position[axis] = 0;
  1845. // plan_set_position_curposXYZE();
  1846. tmc2130_home_exit();
  1847. enable_endstops(false);
  1848. current_position[Z_AXIS] = 0;
  1849. plan_set_position_curposXYZE();
  1850. set_destination_to_current();
  1851. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1852. feedrate = homing_feedrate[Z_AXIS] / 2;
  1853. plan_buffer_line_destinationXYZE(feedrate / 60);
  1854. st_synchronize();
  1855. enable_endstops(endstops_enabled);
  1856. if (PRINTER_TYPE == PRINTER_MK3) {
  1857. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1858. }
  1859. else {
  1860. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1861. }
  1862. plan_set_position_curposXYZE();
  1863. return true;
  1864. }
  1865. #endif //TMC2130
  1866. #ifdef TMC2130
  1867. static void check_Z_crash(void)
  1868. {
  1869. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1870. FORCE_HIGH_POWER_END;
  1871. current_position[Z_AXIS] = 0;
  1872. plan_set_position_curposXYZE();
  1873. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1874. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1875. st_synchronize();
  1876. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1877. }
  1878. }
  1879. #endif //TMC2130
  1880. #ifdef TMC2130
  1881. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1882. #else
  1883. void homeaxis(uint8_t axis, uint8_t cnt)
  1884. #endif //TMC2130
  1885. {
  1886. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1887. #define HOMEAXIS_DO(LETTER) \
  1888. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1889. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1890. {
  1891. int axis_home_dir = home_dir(axis);
  1892. feedrate = homing_feedrate[axis];
  1893. #ifdef TMC2130
  1894. tmc2130_home_enter(X_AXIS_MASK << axis);
  1895. #endif //TMC2130
  1896. // Move away a bit, so that the print head does not touch the end position,
  1897. // and the following movement to endstop has a chance to achieve the required velocity
  1898. // for the stall guard to work.
  1899. current_position[axis] = 0;
  1900. plan_set_position_curposXYZE();
  1901. set_destination_to_current();
  1902. // destination[axis] = 11.f;
  1903. destination[axis] = -3.f * axis_home_dir;
  1904. plan_buffer_line_destinationXYZE(feedrate/60);
  1905. st_synchronize();
  1906. // Move away from the possible collision with opposite endstop 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] = 1. * axis_home_dir;
  1912. plan_buffer_line_destinationXYZE(feedrate/60);
  1913. st_synchronize();
  1914. // Now continue to move up to the left end stop with the collision detection enabled.
  1915. enable_endstops(true);
  1916. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1917. plan_buffer_line_destinationXYZE(feedrate/60);
  1918. st_synchronize();
  1919. for (uint8_t i = 0; i < cnt; i++)
  1920. {
  1921. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1922. endstops_hit_on_purpose();
  1923. enable_endstops(false);
  1924. current_position[axis] = 0;
  1925. plan_set_position_curposXYZE();
  1926. destination[axis] = -10.f * axis_home_dir;
  1927. plan_buffer_line_destinationXYZE(feedrate/60);
  1928. st_synchronize();
  1929. endstops_hit_on_purpose();
  1930. // Now move left up to the collision, this time with a repeatable velocity.
  1931. enable_endstops(true);
  1932. destination[axis] = 11.f * axis_home_dir;
  1933. #ifdef TMC2130
  1934. feedrate = homing_feedrate[axis];
  1935. #else //TMC2130
  1936. feedrate = homing_feedrate[axis] / 2;
  1937. #endif //TMC2130
  1938. plan_buffer_line_destinationXYZE(feedrate/60);
  1939. st_synchronize();
  1940. #ifdef TMC2130
  1941. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1942. if (pstep) pstep[i] = mscnt >> 4;
  1943. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1944. #endif //TMC2130
  1945. }
  1946. endstops_hit_on_purpose();
  1947. enable_endstops(false);
  1948. #ifdef TMC2130
  1949. uint8_t orig = tmc2130_home_origin[axis];
  1950. uint8_t back = tmc2130_home_bsteps[axis];
  1951. if (tmc2130_home_enabled && (orig <= 63))
  1952. {
  1953. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1954. if (back > 0)
  1955. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1956. }
  1957. else
  1958. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1959. tmc2130_home_exit();
  1960. #endif //TMC2130
  1961. axis_is_at_home(axis);
  1962. axis_known_position[axis] = true;
  1963. // Move from minimum
  1964. #ifdef TMC2130
  1965. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1966. #else //TMC2130
  1967. float dist = - axis_home_dir * 0.01f * 64;
  1968. #endif //TMC2130
  1969. current_position[axis] -= dist;
  1970. plan_set_position_curposXYZE();
  1971. current_position[axis] += dist;
  1972. destination[axis] = current_position[axis];
  1973. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1974. st_synchronize();
  1975. feedrate = 0.0;
  1976. }
  1977. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1978. {
  1979. #ifdef TMC2130
  1980. FORCE_HIGH_POWER_START;
  1981. #endif
  1982. int axis_home_dir = home_dir(axis);
  1983. current_position[axis] = 0;
  1984. plan_set_position_curposXYZE();
  1985. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1986. feedrate = homing_feedrate[axis];
  1987. plan_buffer_line_destinationXYZE(feedrate/60);
  1988. st_synchronize();
  1989. #ifdef TMC2130
  1990. check_Z_crash();
  1991. #endif //TMC2130
  1992. current_position[axis] = 0;
  1993. plan_set_position_curposXYZE();
  1994. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1995. plan_buffer_line_destinationXYZE(feedrate/60);
  1996. st_synchronize();
  1997. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1998. feedrate = homing_feedrate[axis]/2 ;
  1999. plan_buffer_line_destinationXYZE(feedrate/60);
  2000. st_synchronize();
  2001. #ifdef TMC2130
  2002. check_Z_crash();
  2003. #endif //TMC2130
  2004. axis_is_at_home(axis);
  2005. destination[axis] = current_position[axis];
  2006. feedrate = 0.0;
  2007. endstops_hit_on_purpose();
  2008. axis_known_position[axis] = true;
  2009. #ifdef TMC2130
  2010. FORCE_HIGH_POWER_END;
  2011. #endif
  2012. }
  2013. enable_endstops(endstops_enabled);
  2014. }
  2015. /**/
  2016. void home_xy()
  2017. {
  2018. set_destination_to_current();
  2019. homeaxis(X_AXIS);
  2020. homeaxis(Y_AXIS);
  2021. plan_set_position_curposXYZE();
  2022. endstops_hit_on_purpose();
  2023. }
  2024. void refresh_cmd_timeout(void)
  2025. {
  2026. previous_millis_cmd.start();
  2027. }
  2028. #ifdef FWRETRACT
  2029. void retract(bool retracting, bool swapretract = false) {
  2030. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2031. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2032. // position, which requires a sync
  2033. if(retracting && !retracted[active_extruder]) {
  2034. st_synchronize();
  2035. set_destination_to_current();
  2036. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2037. plan_set_e_position(current_position[E_AXIS]);
  2038. float oldFeedrate = feedrate;
  2039. feedrate=cs.retract_feedrate*60;
  2040. retracted[active_extruder]=true;
  2041. prepare_move();
  2042. if(cs.retract_zlift) {
  2043. st_synchronize();
  2044. current_position[Z_AXIS]-=cs.retract_zlift;
  2045. plan_set_position_curposXYZE();
  2046. prepare_move();
  2047. }
  2048. feedrate = oldFeedrate;
  2049. } else if(!retracting && retracted[active_extruder]) {
  2050. st_synchronize();
  2051. set_destination_to_current();
  2052. float oldFeedrate = feedrate;
  2053. feedrate=cs.retract_recover_feedrate*60;
  2054. if(cs.retract_zlift) {
  2055. current_position[Z_AXIS]+=cs.retract_zlift;
  2056. plan_set_position_curposXYZE();
  2057. prepare_move();
  2058. st_synchronize();
  2059. }
  2060. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2061. plan_set_e_position(current_position[E_AXIS]);
  2062. retracted[active_extruder]=false;
  2063. prepare_move();
  2064. feedrate = oldFeedrate;
  2065. }
  2066. } //retract
  2067. #endif //FWRETRACT
  2068. #ifdef TMC2130
  2069. void force_high_power_mode(bool start_high_power_section) {
  2070. #ifdef PSU_Delta
  2071. if (start_high_power_section == true) enable_force_z();
  2072. #endif //PSU_Delta
  2073. uint8_t silent;
  2074. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2075. if (silent == 1) {
  2076. //we are in silent mode, set to normal mode to enable crash detection
  2077. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2078. st_synchronize();
  2079. cli();
  2080. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2081. update_mode_profile();
  2082. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2083. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2084. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2085. st_reset_timer();
  2086. sei();
  2087. }
  2088. }
  2089. #endif //TMC2130
  2090. void gcode_M105(uint8_t extruder)
  2091. {
  2092. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2093. SERIAL_PROTOCOLPGM("T:");
  2094. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2095. SERIAL_PROTOCOLPGM(" /");
  2096. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2097. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2098. SERIAL_PROTOCOLPGM(" B:");
  2099. SERIAL_PROTOCOL_F(degBed(),1);
  2100. SERIAL_PROTOCOLPGM(" /");
  2101. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2102. #endif //TEMP_BED_PIN
  2103. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2104. SERIAL_PROTOCOLPGM(" T");
  2105. SERIAL_PROTOCOL(cur_extruder);
  2106. SERIAL_PROTOCOL(':');
  2107. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2108. SERIAL_PROTOCOLPGM(" /");
  2109. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2110. }
  2111. #else
  2112. SERIAL_ERROR_START;
  2113. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2114. #endif
  2115. SERIAL_PROTOCOLPGM(" @:");
  2116. #ifdef EXTRUDER_WATTS
  2117. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2118. SERIAL_PROTOCOLPGM("W");
  2119. #else
  2120. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2121. #endif
  2122. SERIAL_PROTOCOLPGM(" B@:");
  2123. #ifdef BED_WATTS
  2124. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2125. SERIAL_PROTOCOLPGM("W");
  2126. #else
  2127. SERIAL_PROTOCOL(getHeaterPower(-1));
  2128. #endif
  2129. #ifdef PINDA_THERMISTOR
  2130. SERIAL_PROTOCOLPGM(" P:");
  2131. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2132. #endif //PINDA_THERMISTOR
  2133. #ifdef AMBIENT_THERMISTOR
  2134. SERIAL_PROTOCOLPGM(" A:");
  2135. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2136. #endif //AMBIENT_THERMISTOR
  2137. #ifdef SHOW_TEMP_ADC_VALUES
  2138. {
  2139. float raw = 0.0;
  2140. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2141. SERIAL_PROTOCOLPGM(" ADC B:");
  2142. SERIAL_PROTOCOL_F(degBed(),1);
  2143. SERIAL_PROTOCOLPGM("C->");
  2144. raw = rawBedTemp();
  2145. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2146. SERIAL_PROTOCOLPGM(" Rb->");
  2147. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2148. SERIAL_PROTOCOLPGM(" Rxb->");
  2149. SERIAL_PROTOCOL_F(raw, 5);
  2150. #endif
  2151. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2152. SERIAL_PROTOCOLPGM(" T");
  2153. SERIAL_PROTOCOL(cur_extruder);
  2154. SERIAL_PROTOCOLPGM(":");
  2155. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2156. SERIAL_PROTOCOLPGM("C->");
  2157. raw = rawHotendTemp(cur_extruder);
  2158. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2159. SERIAL_PROTOCOLPGM(" Rt");
  2160. SERIAL_PROTOCOL(cur_extruder);
  2161. SERIAL_PROTOCOLPGM("->");
  2162. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2163. SERIAL_PROTOCOLPGM(" Rx");
  2164. SERIAL_PROTOCOL(cur_extruder);
  2165. SERIAL_PROTOCOLPGM("->");
  2166. SERIAL_PROTOCOL_F(raw, 5);
  2167. }
  2168. }
  2169. #endif
  2170. SERIAL_PROTOCOLLN();
  2171. }
  2172. #ifdef TMC2130
  2173. 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)
  2174. #else
  2175. 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)
  2176. #endif //TMC2130
  2177. {
  2178. // Flag for the display update routine and to disable the print cancelation during homing.
  2179. st_synchronize();
  2180. homing_flag = true;
  2181. #if 0
  2182. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2183. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2184. #endif
  2185. // Which axes should be homed?
  2186. bool home_x = home_x_axis;
  2187. bool home_y = home_y_axis;
  2188. bool home_z = home_z_axis;
  2189. // Either all X,Y,Z codes are present, or none of them.
  2190. bool home_all_axes = home_x == home_y && home_x == home_z;
  2191. if (home_all_axes)
  2192. // No X/Y/Z code provided means to home all axes.
  2193. home_x = home_y = home_z = true;
  2194. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2195. if (home_all_axes) {
  2196. raise_z_above(MESH_HOME_Z_SEARCH);
  2197. }
  2198. #ifdef ENABLE_AUTO_BED_LEVELING
  2199. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2200. #endif //ENABLE_AUTO_BED_LEVELING
  2201. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2202. // the planner will not perform any adjustments in the XY plane.
  2203. // Wait for the motors to stop and update the current position with the absolute values.
  2204. world2machine_revert_to_uncorrected();
  2205. // For mesh bed leveling deactivate the matrix temporarily.
  2206. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2207. // in a single axis only.
  2208. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2209. #ifdef MESH_BED_LEVELING
  2210. uint8_t mbl_was_active = mbl.active;
  2211. mbl.active = 0;
  2212. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2213. #endif
  2214. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2215. if (home_z)
  2216. babystep_undo();
  2217. int l_feedmultiply = setup_for_endstop_move();
  2218. set_destination_to_current();
  2219. feedrate = 0.0;
  2220. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2221. if(home_z)
  2222. homeaxis(Z_AXIS);
  2223. #endif
  2224. #ifdef QUICK_HOME
  2225. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2226. if(home_x && home_y) //first diagonal move
  2227. {
  2228. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2229. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2230. plan_set_position_curposXYZE();
  2231. 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);
  2232. feedrate = homing_feedrate[X_AXIS];
  2233. if(homing_feedrate[Y_AXIS]<feedrate)
  2234. feedrate = homing_feedrate[Y_AXIS];
  2235. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2236. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2237. } else {
  2238. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2239. }
  2240. plan_buffer_line_destinationXYZE(feedrate/60);
  2241. st_synchronize();
  2242. axis_is_at_home(X_AXIS);
  2243. axis_is_at_home(Y_AXIS);
  2244. plan_set_position_curposXYZE();
  2245. destination[X_AXIS] = current_position[X_AXIS];
  2246. destination[Y_AXIS] = current_position[Y_AXIS];
  2247. plan_buffer_line_destinationXYZE(feedrate/60);
  2248. feedrate = 0.0;
  2249. st_synchronize();
  2250. endstops_hit_on_purpose();
  2251. current_position[X_AXIS] = destination[X_AXIS];
  2252. current_position[Y_AXIS] = destination[Y_AXIS];
  2253. current_position[Z_AXIS] = destination[Z_AXIS];
  2254. }
  2255. #endif /* QUICK_HOME */
  2256. #ifdef TMC2130
  2257. if(home_x)
  2258. {
  2259. if (!calib)
  2260. homeaxis(X_AXIS);
  2261. else
  2262. tmc2130_home_calibrate(X_AXIS);
  2263. }
  2264. if(home_y)
  2265. {
  2266. if (!calib)
  2267. homeaxis(Y_AXIS);
  2268. else
  2269. tmc2130_home_calibrate(Y_AXIS);
  2270. }
  2271. #else //TMC2130
  2272. if(home_x) homeaxis(X_AXIS);
  2273. if(home_y) homeaxis(Y_AXIS);
  2274. #endif //TMC2130
  2275. if(home_x_axis && home_x_value != 0)
  2276. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2277. if(home_y_axis && home_y_value != 0)
  2278. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2279. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2280. #ifndef Z_SAFE_HOMING
  2281. if(home_z) {
  2282. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2283. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2284. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2285. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2286. raise_z_above(MESH_HOME_Z_SEARCH);
  2287. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2288. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2289. // 1st mesh bed leveling measurement point, corrected.
  2290. world2machine_initialize();
  2291. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2292. world2machine_reset();
  2293. if (destination[Y_AXIS] < Y_MIN_POS)
  2294. destination[Y_AXIS] = Y_MIN_POS;
  2295. feedrate = homing_feedrate[X_AXIS] / 20;
  2296. enable_endstops(false);
  2297. #ifdef DEBUG_BUILD
  2298. SERIAL_ECHOLNPGM("plan_set_position()");
  2299. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2300. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2301. #endif
  2302. plan_set_position_curposXYZE();
  2303. #ifdef DEBUG_BUILD
  2304. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2305. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2306. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2307. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2308. #endif
  2309. plan_buffer_line_destinationXYZE(feedrate);
  2310. st_synchronize();
  2311. current_position[X_AXIS] = destination[X_AXIS];
  2312. current_position[Y_AXIS] = destination[Y_AXIS];
  2313. enable_endstops(true);
  2314. endstops_hit_on_purpose();
  2315. homeaxis(Z_AXIS);
  2316. #else // MESH_BED_LEVELING
  2317. homeaxis(Z_AXIS);
  2318. #endif // MESH_BED_LEVELING
  2319. }
  2320. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2321. if(home_all_axes) {
  2322. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2323. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2324. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2325. feedrate = XY_TRAVEL_SPEED/60;
  2326. current_position[Z_AXIS] = 0;
  2327. plan_set_position_curposXYZE();
  2328. plan_buffer_line_destinationXYZE(feedrate);
  2329. st_synchronize();
  2330. current_position[X_AXIS] = destination[X_AXIS];
  2331. current_position[Y_AXIS] = destination[Y_AXIS];
  2332. homeaxis(Z_AXIS);
  2333. }
  2334. // Let's see if X and Y are homed and probe is inside bed area.
  2335. if(home_z) {
  2336. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2337. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2338. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2339. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2340. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2341. current_position[Z_AXIS] = 0;
  2342. plan_set_position_curposXYZE();
  2343. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2344. feedrate = max_feedrate[Z_AXIS];
  2345. plan_buffer_line_destinationXYZE(feedrate);
  2346. st_synchronize();
  2347. homeaxis(Z_AXIS);
  2348. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2349. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2350. SERIAL_ECHO_START;
  2351. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2352. } else {
  2353. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2354. SERIAL_ECHO_START;
  2355. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2356. }
  2357. }
  2358. #endif // Z_SAFE_HOMING
  2359. #endif // Z_HOME_DIR < 0
  2360. if(home_z_axis && home_z_value != 0)
  2361. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2362. #ifdef ENABLE_AUTO_BED_LEVELING
  2363. if(home_z)
  2364. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2365. #endif
  2366. // Set the planner and stepper routine positions.
  2367. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2368. // contains the machine coordinates.
  2369. plan_set_position_curposXYZE();
  2370. clean_up_after_endstop_move(l_feedmultiply);
  2371. endstops_hit_on_purpose();
  2372. #ifndef MESH_BED_LEVELING
  2373. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2374. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2375. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2376. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2377. lcd_adjust_z();
  2378. #endif
  2379. // Load the machine correction matrix
  2380. world2machine_initialize();
  2381. // and correct the current_position XY axes to match the transformed coordinate system.
  2382. world2machine_update_current();
  2383. #ifdef MESH_BED_LEVELING
  2384. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2385. {
  2386. if (! home_z && mbl_was_active) {
  2387. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2388. mbl.active = true;
  2389. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2390. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2391. }
  2392. }
  2393. #endif
  2394. prusa_statistics(20);
  2395. st_synchronize();
  2396. homing_flag = false;
  2397. #if 0
  2398. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2399. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2400. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2401. #endif
  2402. }
  2403. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2404. {
  2405. #ifdef TMC2130
  2406. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2407. #else
  2408. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2409. #endif //TMC2130
  2410. }
  2411. // G80 - Automatic mesh bed leveling
  2412. static void gcode_G80()
  2413. {
  2414. st_synchronize();
  2415. if (planner_aborted)
  2416. return;
  2417. mesh_bed_leveling_flag = true;
  2418. #ifndef PINDA_THERMISTOR
  2419. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2420. #endif // ndef PINDA_THERMISTOR
  2421. #ifdef SUPPORT_VERBOSITY
  2422. int8_t verbosity_level = 0;
  2423. if (code_seen('V')) {
  2424. // Just 'V' without a number counts as V1.
  2425. char c = strchr_pointer[1];
  2426. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2427. }
  2428. #endif //SUPPORT_VERBOSITY
  2429. // Firstly check if we know where we are
  2430. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2431. // We don't know where we are! HOME!
  2432. // Push the commands to the front of the message queue in the reverse order!
  2433. // There shall be always enough space reserved for these commands.
  2434. repeatcommand_front(); // repeat G80 with all its parameters
  2435. enquecommand_front_P(G28W0);
  2436. return;
  2437. }
  2438. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2439. if (code_seen('N')) {
  2440. nMeasPoints = code_value_uint8();
  2441. if (nMeasPoints != 7) {
  2442. nMeasPoints = 3;
  2443. }
  2444. }
  2445. else {
  2446. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2447. }
  2448. uint8_t nProbeRetry = 3;
  2449. if (code_seen('R')) {
  2450. nProbeRetry = code_value_uint8();
  2451. if (nProbeRetry > 10) {
  2452. nProbeRetry = 10;
  2453. }
  2454. }
  2455. else {
  2456. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2457. }
  2458. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2459. #ifndef PINDA_THERMISTOR
  2460. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2461. {
  2462. temp_compensation_start();
  2463. run = true;
  2464. repeatcommand_front(); // repeat G80 with all its parameters
  2465. enquecommand_front_P(G28W0);
  2466. break;
  2467. }
  2468. run = false;
  2469. #endif //PINDA_THERMISTOR
  2470. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2471. CustomMsg custom_message_type_old = custom_message_type;
  2472. uint8_t custom_message_state_old = custom_message_state;
  2473. custom_message_type = CustomMsg::MeshBedLeveling;
  2474. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2475. lcd_update(1);
  2476. mbl.reset(); //reset mesh bed leveling
  2477. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2478. babystep_undo();
  2479. // Cycle through all points and probe them
  2480. // First move up. During this first movement, the babystepping will be reverted.
  2481. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2482. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2483. // The move to the first calibration point.
  2484. current_position[X_AXIS] = BED_X0;
  2485. current_position[Y_AXIS] = BED_Y0;
  2486. #ifdef SUPPORT_VERBOSITY
  2487. if (verbosity_level >= 1)
  2488. {
  2489. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2490. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2491. }
  2492. #else //SUPPORT_VERBOSITY
  2493. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2494. #endif //SUPPORT_VERBOSITY
  2495. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2496. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2497. // Wait until the move is finished.
  2498. st_synchronize();
  2499. if (planner_aborted)
  2500. {
  2501. custom_message_type = custom_message_type_old;
  2502. custom_message_state = custom_message_state_old;
  2503. return;
  2504. }
  2505. uint8_t mesh_point = 0; //index number of calibration point
  2506. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2507. 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)
  2508. #ifdef SUPPORT_VERBOSITY
  2509. if (verbosity_level >= 1) {
  2510. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2511. }
  2512. #endif // SUPPORT_VERBOSITY
  2513. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2514. while (mesh_point != nMeasPoints * nMeasPoints) {
  2515. // Get coords of a measuring point.
  2516. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2517. uint8_t iy = mesh_point / nMeasPoints;
  2518. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2519. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2520. custom_message_state--;
  2521. mesh_point++;
  2522. continue; //skip
  2523. }*/
  2524. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2525. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2526. {
  2527. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2528. }
  2529. float z0 = 0.f;
  2530. if (has_z && (mesh_point > 0)) {
  2531. uint16_t z_offset_u = 0;
  2532. if (nMeasPoints == 7) {
  2533. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2534. }
  2535. else {
  2536. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2537. }
  2538. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2539. #ifdef SUPPORT_VERBOSITY
  2540. if (verbosity_level >= 1) {
  2541. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2542. }
  2543. #endif // SUPPORT_VERBOSITY
  2544. }
  2545. // Move Z up to MESH_HOME_Z_SEARCH.
  2546. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2547. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2548. float init_z_bckp = current_position[Z_AXIS];
  2549. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2550. st_synchronize();
  2551. // Move to XY position of the sensor point.
  2552. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2553. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2554. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2555. #ifdef SUPPORT_VERBOSITY
  2556. if (verbosity_level >= 1) {
  2557. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2558. SERIAL_PROTOCOL(mesh_point);
  2559. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2560. }
  2561. #else //SUPPORT_VERBOSITY
  2562. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2563. #endif // SUPPORT_VERBOSITY
  2564. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2565. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2566. st_synchronize();
  2567. if (planner_aborted)
  2568. {
  2569. custom_message_type = custom_message_type_old;
  2570. custom_message_state = custom_message_state_old;
  2571. return;
  2572. }
  2573. // Go down until endstop is hit
  2574. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2575. 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
  2576. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2577. break;
  2578. }
  2579. 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.
  2580. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2581. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2582. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2583. st_synchronize();
  2584. 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
  2585. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2586. break;
  2587. }
  2588. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2589. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2590. break;
  2591. }
  2592. }
  2593. 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
  2594. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2595. break;
  2596. }
  2597. #ifdef SUPPORT_VERBOSITY
  2598. if (verbosity_level >= 10) {
  2599. SERIAL_ECHOPGM("X: ");
  2600. MYSERIAL.print(current_position[X_AXIS], 5);
  2601. SERIAL_ECHOLNPGM("");
  2602. SERIAL_ECHOPGM("Y: ");
  2603. MYSERIAL.print(current_position[Y_AXIS], 5);
  2604. SERIAL_PROTOCOLPGM("\n");
  2605. }
  2606. #endif // SUPPORT_VERBOSITY
  2607. float offset_z = 0;
  2608. #ifdef PINDA_THERMISTOR
  2609. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2610. #endif //PINDA_THERMISTOR
  2611. // #ifdef SUPPORT_VERBOSITY
  2612. /* if (verbosity_level >= 1)
  2613. {
  2614. SERIAL_ECHOPGM("mesh bed leveling: ");
  2615. MYSERIAL.print(current_position[Z_AXIS], 5);
  2616. SERIAL_ECHOPGM(" offset: ");
  2617. MYSERIAL.print(offset_z, 5);
  2618. SERIAL_ECHOLNPGM("");
  2619. }*/
  2620. // #endif // SUPPORT_VERBOSITY
  2621. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2622. custom_message_state--;
  2623. mesh_point++;
  2624. lcd_update(1);
  2625. }
  2626. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2627. #ifdef SUPPORT_VERBOSITY
  2628. if (verbosity_level >= 20) {
  2629. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2630. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2631. MYSERIAL.print(current_position[Z_AXIS], 5);
  2632. }
  2633. #endif // SUPPORT_VERBOSITY
  2634. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2635. st_synchronize();
  2636. if (mesh_point != nMeasPoints * nMeasPoints) {
  2637. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2638. bool bState;
  2639. do { // repeat until Z-leveling o.k.
  2640. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2641. #ifdef TMC2130
  2642. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2643. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2644. #else // TMC2130
  2645. lcd_wait_for_click_delay(0); // ~ no timeout
  2646. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2647. #endif // TMC2130
  2648. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2649. bState=enable_z_endstop(false);
  2650. current_position[Z_AXIS] -= 1;
  2651. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2652. st_synchronize();
  2653. enable_z_endstop(true);
  2654. #ifdef TMC2130
  2655. tmc2130_home_enter(Z_AXIS_MASK);
  2656. #endif // TMC2130
  2657. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2658. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2659. st_synchronize();
  2660. #ifdef TMC2130
  2661. tmc2130_home_exit();
  2662. #endif // TMC2130
  2663. enable_z_endstop(bState);
  2664. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2665. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2666. custom_message_type = custom_message_type_old;
  2667. custom_message_state = custom_message_state_old;
  2668. lcd_update_enable(true); // display / status-line recovery
  2669. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2670. repeatcommand_front(); // re-run (i.e. of "G80")
  2671. return;
  2672. }
  2673. clean_up_after_endstop_move(l_feedmultiply);
  2674. // SERIAL_ECHOLNPGM("clean up finished ");
  2675. #ifndef PINDA_THERMISTOR
  2676. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2677. #endif
  2678. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2679. // SERIAL_ECHOLNPGM("babystep applied");
  2680. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2681. #ifdef SUPPORT_VERBOSITY
  2682. if (verbosity_level >= 1) {
  2683. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2684. }
  2685. #endif // SUPPORT_VERBOSITY
  2686. for (uint8_t i = 0; i < 4; ++i) {
  2687. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2688. long correction = 0;
  2689. if (code_seen(codes[i]))
  2690. correction = code_value_long();
  2691. else if (eeprom_bed_correction_valid) {
  2692. unsigned char *addr = (i < 2) ?
  2693. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2694. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2695. correction = eeprom_read_int8(addr);
  2696. }
  2697. if (correction == 0)
  2698. continue;
  2699. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2700. SERIAL_ERROR_START;
  2701. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2702. SERIAL_ECHO(correction);
  2703. SERIAL_ECHOLNPGM(" microns");
  2704. }
  2705. else {
  2706. float offset = float(correction) * 0.001f;
  2707. switch (i) {
  2708. case 0:
  2709. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2710. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2711. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2712. }
  2713. }
  2714. break;
  2715. case 1:
  2716. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2717. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2718. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2719. }
  2720. }
  2721. break;
  2722. case 2:
  2723. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2724. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2725. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2726. }
  2727. }
  2728. break;
  2729. case 3:
  2730. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2731. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2732. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2733. }
  2734. }
  2735. break;
  2736. }
  2737. }
  2738. }
  2739. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2740. if (nMeasPoints == 3) {
  2741. 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)
  2742. }
  2743. /*
  2744. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2745. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2746. SERIAL_PROTOCOLPGM(",");
  2747. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2748. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2749. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2750. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2751. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2752. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2753. SERIAL_PROTOCOLPGM(" ");
  2754. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2755. }
  2756. SERIAL_PROTOCOLPGM("\n");
  2757. }
  2758. */
  2759. if (nMeasPoints == 7 && magnet_elimination) {
  2760. mbl_interpolation(nMeasPoints);
  2761. }
  2762. /*
  2763. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2764. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2765. SERIAL_PROTOCOLPGM(",");
  2766. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2767. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2768. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2769. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2770. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2771. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2772. SERIAL_PROTOCOLPGM(" ");
  2773. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2774. }
  2775. SERIAL_PROTOCOLPGM("\n");
  2776. }
  2777. */
  2778. // SERIAL_ECHOLNPGM("Upsample finished");
  2779. mbl.active = 1; //activate mesh bed leveling
  2780. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2781. go_home_with_z_lift();
  2782. // SERIAL_ECHOLNPGM("Go home finished");
  2783. //unretract (after PINDA preheat retraction)
  2784. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2785. current_position[E_AXIS] += default_retraction;
  2786. plan_buffer_line_curposXYZE(400);
  2787. }
  2788. KEEPALIVE_STATE(NOT_BUSY);
  2789. // Restore custom message state
  2790. lcd_setstatuspgm(MSG_WELCOME);
  2791. custom_message_type = custom_message_type_old;
  2792. custom_message_state = custom_message_state_old;
  2793. lcd_update(2);
  2794. st_synchronize();
  2795. mesh_bed_leveling_flag = false;
  2796. }
  2797. void adjust_bed_reset()
  2798. {
  2799. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2800. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2801. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2802. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2803. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2804. }
  2805. //! @brief Calibrate XYZ
  2806. //! @param onlyZ if true, calibrate only Z axis
  2807. //! @param verbosity_level
  2808. //! @retval true Succeeded
  2809. //! @retval false Failed
  2810. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2811. {
  2812. bool final_result = false;
  2813. #ifdef TMC2130
  2814. FORCE_HIGH_POWER_START;
  2815. #endif // TMC2130
  2816. FORCE_BL_ON_START;
  2817. // Only Z calibration?
  2818. if (!onlyZ)
  2819. {
  2820. setTargetBed(0);
  2821. setAllTargetHotends(0);
  2822. adjust_bed_reset(); //reset bed level correction
  2823. }
  2824. // Disable the default update procedure of the display. We will do a modal dialog.
  2825. lcd_update_enable(false);
  2826. // Let the planner use the uncorrected coordinates.
  2827. mbl.reset();
  2828. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2829. // the planner will not perform any adjustments in the XY plane.
  2830. // Wait for the motors to stop and update the current position with the absolute values.
  2831. world2machine_revert_to_uncorrected();
  2832. // Reset the baby step value applied without moving the axes.
  2833. babystep_reset();
  2834. // Mark all axes as in a need for homing.
  2835. memset(axis_known_position, 0, sizeof(axis_known_position));
  2836. // Home in the XY plane.
  2837. //set_destination_to_current();
  2838. int l_feedmultiply = setup_for_endstop_move();
  2839. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2840. raise_z_above(MESH_HOME_Z_SEARCH);
  2841. home_xy();
  2842. enable_endstops(false);
  2843. current_position[X_AXIS] += 5;
  2844. current_position[Y_AXIS] += 5;
  2845. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2846. st_synchronize();
  2847. // Let the user move the Z axes up to the end stoppers.
  2848. #ifdef TMC2130
  2849. if (calibrate_z_auto())
  2850. {
  2851. #else //TMC2130
  2852. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2853. {
  2854. #endif //TMC2130
  2855. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2856. if(onlyZ){
  2857. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2858. lcd_puts_at_P(0,3,_n("1/9"));
  2859. }else{
  2860. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2861. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2862. lcd_puts_at_P(0,3,_n("1/4"));
  2863. }
  2864. refresh_cmd_timeout();
  2865. #ifndef STEEL_SHEET
  2866. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2867. {
  2868. lcd_wait_for_cool_down();
  2869. }
  2870. #endif //STEEL_SHEET
  2871. if(!onlyZ)
  2872. {
  2873. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2874. #ifdef STEEL_SHEET
  2875. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  2876. if(result == LCD_LEFT_BUTTON_CHOICE) {
  2877. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2878. }
  2879. #endif //STEEL_SHEET
  2880. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2881. KEEPALIVE_STATE(IN_HANDLER);
  2882. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2883. lcd_puts_at_P(0,3,_n("1/4"));
  2884. }
  2885. bool endstops_enabled = enable_endstops(false);
  2886. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2887. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2888. st_synchronize();
  2889. // Move the print head close to the bed.
  2890. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2891. enable_endstops(true);
  2892. #ifdef TMC2130
  2893. tmc2130_home_enter(Z_AXIS_MASK);
  2894. #endif //TMC2130
  2895. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2896. st_synchronize();
  2897. #ifdef TMC2130
  2898. tmc2130_home_exit();
  2899. #endif //TMC2130
  2900. enable_endstops(endstops_enabled);
  2901. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2902. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2903. {
  2904. if (onlyZ)
  2905. {
  2906. clean_up_after_endstop_move(l_feedmultiply);
  2907. // Z only calibration.
  2908. // Load the machine correction matrix
  2909. world2machine_initialize();
  2910. // and correct the current_position to match the transformed coordinate system.
  2911. world2machine_update_current();
  2912. //FIXME
  2913. bool result = sample_mesh_and_store_reference();
  2914. if (result)
  2915. {
  2916. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2917. {
  2918. // Shipped, the nozzle height has been set already. The user can start printing now.
  2919. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2920. }
  2921. final_result = true;
  2922. // babystep_apply();
  2923. }
  2924. }
  2925. else
  2926. {
  2927. // Reset the baby step value and the baby step applied flag.
  2928. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2929. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2930. // Complete XYZ calibration.
  2931. uint8_t point_too_far_mask = 0;
  2932. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2933. clean_up_after_endstop_move(l_feedmultiply);
  2934. // Print head up.
  2935. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2936. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2937. st_synchronize();
  2938. //#ifndef NEW_XYZCAL
  2939. if (result >= 0)
  2940. {
  2941. #ifdef HEATBED_V2
  2942. sample_z();
  2943. #else //HEATBED_V2
  2944. point_too_far_mask = 0;
  2945. // Second half: The fine adjustment.
  2946. // Let the planner use the uncorrected coordinates.
  2947. mbl.reset();
  2948. world2machine_reset();
  2949. // Home in the XY plane.
  2950. int l_feedmultiply = setup_for_endstop_move();
  2951. home_xy();
  2952. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2953. clean_up_after_endstop_move(l_feedmultiply);
  2954. // Print head up.
  2955. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2956. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2957. st_synchronize();
  2958. // if (result >= 0) babystep_apply();
  2959. #endif //HEATBED_V2
  2960. }
  2961. //#endif //NEW_XYZCAL
  2962. lcd_update_enable(true);
  2963. lcd_update(2);
  2964. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2965. if (result >= 0)
  2966. {
  2967. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2968. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2969. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2970. final_result = true;
  2971. }
  2972. }
  2973. #ifdef TMC2130
  2974. tmc2130_home_exit();
  2975. #endif
  2976. }
  2977. else
  2978. {
  2979. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2980. final_result = false;
  2981. }
  2982. }
  2983. else
  2984. {
  2985. // Timeouted.
  2986. }
  2987. lcd_update_enable(true);
  2988. #ifdef TMC2130
  2989. FORCE_HIGH_POWER_END;
  2990. #endif // TMC2130
  2991. FORCE_BL_ON_END;
  2992. return final_result;
  2993. }
  2994. void gcode_M114()
  2995. {
  2996. SERIAL_PROTOCOLPGM("X:");
  2997. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2998. SERIAL_PROTOCOLPGM(" Y:");
  2999. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3000. SERIAL_PROTOCOLPGM(" Z:");
  3001. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3002. SERIAL_PROTOCOLPGM(" E:");
  3003. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3004. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  3005. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  3006. SERIAL_PROTOCOLPGM(" Y:");
  3007. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  3008. SERIAL_PROTOCOLPGM(" Z:");
  3009. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  3010. SERIAL_PROTOCOLPGM(" E:");
  3011. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3012. }
  3013. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3014. void gcode_M123()
  3015. {
  3016. 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);
  3017. }
  3018. #endif //FANCHECK and TACH_0 or TACH_1
  3019. static void mmu_M600_wait_and_beep() {
  3020. // Beep and wait for user to remove old filament and prepare new filament for load
  3021. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3022. int counterBeep = 0;
  3023. 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
  3024. bool bFirst = true;
  3025. while (!lcd_clicked()) {
  3026. manage_heater();
  3027. manage_inactivity(true);
  3028. #if BEEPER > 0
  3029. if (counterBeep == 500) {
  3030. counterBeep = 0;
  3031. }
  3032. SET_OUTPUT(BEEPER);
  3033. if (counterBeep == 0) {
  3034. if ((eSoundMode == e_SOUND_MODE_BLIND) || (eSoundMode == e_SOUND_MODE_LOUD) || ((eSoundMode == e_SOUND_MODE_ONCE) && bFirst)) {
  3035. bFirst = false;
  3036. WRITE(BEEPER, HIGH);
  3037. }
  3038. }
  3039. if (counterBeep == 20) {
  3040. WRITE(BEEPER, LOW);
  3041. }
  3042. counterBeep++;
  3043. #endif // BEEPER > 0
  3044. delay_keep_alive(4);
  3045. }
  3046. WRITE(BEEPER, LOW);
  3047. }
  3048. /**
  3049. * @brief Handling of unload when using MMU with M600
  3050. * A fullscreen message showing "Unloading Filament x"
  3051. * should be shown on the LCD and LCD updates should be
  3052. * are disabled in the meantime.
  3053. */
  3054. static void mmu_M600_unload_filament() {
  3055. uint8_t tmp_extruder = MMU2::mmu2.get_current_tool();
  3056. lcd_update_enable(false);
  3057. lcd_clear();
  3058. lcd_puts_at_P(0, 1, _T(MSG_UNLOADING_FILAMENT));
  3059. lcd_print(' ');
  3060. lcd_print(tmp_extruder + 1);
  3061. // unload just current filament for multimaterial printers (used also in M702)
  3062. MMU2::mmu2.unload();
  3063. lcd_update_enable(true);
  3064. }
  3065. /// @brief load filament for mmu v2
  3066. /// @par nozzle_temp nozzle temperature to load filament
  3067. static void mmu_M600_load_filament(bool automatic, float nozzle_temp) {
  3068. uint8_t tmp_extruder = MMU2::mmu2.get_previous_tool();
  3069. // TODO SpoolJoin
  3070. /*if (automatic) {
  3071. tmp_extruder = ad_getAlternative(tmp_extruder);
  3072. }*/
  3073. lcd_update_enable(false);
  3074. lcd_clear();
  3075. lcd_puts_at_P(0, 1, _T(MSG_LOADING_FILAMENT));
  3076. lcd_print(' ');
  3077. lcd_print(tmp_extruder + 1);
  3078. // printf_P(PSTR("T code: %d \n"), tmp_extruder);
  3079. setTargetHotend(nozzle_temp, active_extruder);
  3080. MMU2::mmu2.load_filament_to_nozzle(tmp_extruder);
  3081. load_filament_final_feed(); // @@TODO verify
  3082. st_synchronize();
  3083. }
  3084. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3085. st_synchronize();
  3086. float lastpos[4];
  3087. prusa_statistics(22);
  3088. //First backup current position and settings
  3089. int feedmultiplyBckp = feedmultiply;
  3090. float HotendTempBckp = degTargetHotend(active_extruder);
  3091. int fanSpeedBckp = fanSpeed;
  3092. lastpos[X_AXIS] = current_position[X_AXIS];
  3093. lastpos[Y_AXIS] = current_position[Y_AXIS];
  3094. lastpos[Z_AXIS] = current_position[Z_AXIS];
  3095. lastpos[E_AXIS] = current_position[E_AXIS];
  3096. // Retract E
  3097. current_position[E_AXIS] += e_shift;
  3098. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3099. st_synchronize();
  3100. // Raise the Z axis
  3101. float delta = raise_z(z_shift);
  3102. // Move XY to side
  3103. current_position[X_AXIS] = x_position;
  3104. current_position[Y_AXIS] = y_position;
  3105. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3106. st_synchronize();
  3107. // Beep, manage nozzle heater and wait for user to start unload filament
  3108. if (!MMU2::mmu2.Enabled())
  3109. M600_wait_for_user(HotendTempBckp);
  3110. lcd_change_fil_state = 0;
  3111. // Unload filament
  3112. if (MMU2::mmu2.Enabled())
  3113. mmu_M600_unload_filament();
  3114. else
  3115. unload_filament(FILAMENTCHANGE_FINALRETRACT, 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. // TODO: Move the Z-axis after XY, not before. Currently this does not work
  3160. // and raise_z seems to have no affect after XY move for unknown reasons.
  3161. // This needs to be looked into.
  3162. // Recover Z axis
  3163. raise_z(-delta);
  3164. // Move XY back
  3165. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3166. st_synchronize();
  3167. // Set E position to original
  3168. plan_set_e_position(lastpos[E_AXIS]);
  3169. memcpy(current_position, lastpos, sizeof(lastpos));
  3170. set_destination_to_current();
  3171. // Recover feed rate
  3172. feedmultiply = feedmultiplyBckp;
  3173. char cmd[9];
  3174. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3175. enquecommand(cmd);
  3176. }
  3177. lcd_setstatuspgm(MSG_WELCOME);
  3178. custom_message_type = CustomMsg::Status;
  3179. }
  3180. void gcode_M701(float fastLoadLength, uint8_t mmuSlotIndex){
  3181. FSensorBlockRunout fsBlockRunout;
  3182. prusa_statistics(22);
  3183. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3184. MMU2::mmu2.load_filament_to_nozzle(mmuSlotIndex);
  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. loading_flag = false;
  3207. custom_message_type = CustomMsg::Status;
  3208. }
  3209. eFilamentAction = FilamentAction::None;
  3210. }
  3211. // Common gcode shared by the gcodes. This saves some flash memory
  3212. static void gcodes_M704_M705_M706(uint16_t gcode)
  3213. {
  3214. uint8_t mmuSlotIndex = 0xffU;
  3215. if (MMU2::mmu2.Enabled() && code_seen('P'))
  3216. {
  3217. mmuSlotIndex = code_value_uint8();
  3218. if (mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3219. switch (gcode)
  3220. {
  3221. case 704:
  3222. MMU2::mmu2.load_filament(mmuSlotIndex);
  3223. break;
  3224. case 705:
  3225. MMU2::mmu2.eject_filament(mmuSlotIndex, false);
  3226. break;
  3227. case 706:
  3228. MMU2::mmu2.cut_filament(mmuSlotIndex);
  3229. break;
  3230. default:
  3231. break;
  3232. }
  3233. }
  3234. }
  3235. }
  3236. /**
  3237. * @brief Get serial number from 32U2 processor
  3238. *
  3239. * Typical format of S/N is:CZPX0917X003XC13518
  3240. *
  3241. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3242. * reply is stored in *SN.
  3243. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3244. * and returns a general failure flag.
  3245. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3246. * In that case the value that is stored in the EEPROM should be used instead.
  3247. *
  3248. * @return 0 on success
  3249. * @return 1 on general failure
  3250. */
  3251. #ifdef PRUSA_SN_SUPPORT
  3252. static uint8_t get_PRUSA_SN(char* SN)
  3253. {
  3254. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3255. uint8_t rxIndex;
  3256. bool SN_valid = false;
  3257. ShortTimer timeout;
  3258. selectedSerialPort = 0;
  3259. timeout.start();
  3260. while (!SN_valid)
  3261. {
  3262. rxIndex = 0;
  3263. _delay(50);
  3264. MYSERIAL.flush(); //clear RX buffer
  3265. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3266. while (rxIndex < 19)
  3267. {
  3268. if (timeout.expired(250u))
  3269. goto exit;
  3270. if (MYSERIAL.available() > 0)
  3271. {
  3272. SN[rxIndex] = MYSERIAL.read();
  3273. rxIndex++;
  3274. }
  3275. }
  3276. SN[rxIndex] = 0;
  3277. // printf_P(PSTR("SN:%s\n"), SN);
  3278. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3279. }
  3280. exit:
  3281. selectedSerialPort = selectedSerialPort_bak;
  3282. return !SN_valid;
  3283. }
  3284. #endif //PRUSA_SN_SUPPORT
  3285. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3286. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3287. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3288. //! it may even interfere with other functions of the printer! You have been warned!
  3289. //! The test idea is to measure the time necessary to charge the capacitor.
  3290. //! So the algorithm is as follows:
  3291. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3292. //! 2. Wait a few ms
  3293. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3294. //! Repeat 1.-3. several times
  3295. //! Good RAMBo's times are in the range of approx. 260-320 us
  3296. //! Bad RAMBo's times are approx. 260-1200 us
  3297. //! So basically we are interested in maximum time, the minima are mostly the same.
  3298. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3299. static void gcode_PRUSA_BadRAMBoFanTest(){
  3300. //printf_P(PSTR("Enter fan pin test\n"));
  3301. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3302. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3303. unsigned long tach1max = 0;
  3304. uint8_t tach1cntr = 0;
  3305. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3306. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3307. SET_OUTPUT(TACH_1);
  3308. WRITE(TACH_1, LOW);
  3309. _delay(20); // the delay may be lower
  3310. unsigned long tachMeasure = _micros();
  3311. cli();
  3312. SET_INPUT(TACH_1);
  3313. // just wait brutally in an endless cycle until we reach HIGH
  3314. // if this becomes a problem it may be improved to non-endless cycle
  3315. while( READ(TACH_1) == 0 ) ;
  3316. sei();
  3317. tachMeasure = _micros() - tachMeasure;
  3318. if( tach1max < tachMeasure )
  3319. tach1max = tachMeasure;
  3320. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3321. }
  3322. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3323. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3324. if( tach1max > 500 ){
  3325. // bad RAMBo
  3326. SERIAL_PROTOCOLLNPGM("BAD");
  3327. } else {
  3328. SERIAL_PROTOCOLLNPGM("OK");
  3329. }
  3330. // cleanup after the test function
  3331. SET_INPUT(TACH_1);
  3332. WRITE(TACH_1, HIGH);
  3333. #endif
  3334. }
  3335. // G92 - Set current position to coordinates given
  3336. static void gcode_G92()
  3337. {
  3338. bool codes[NUM_AXIS];
  3339. float values[NUM_AXIS];
  3340. // Check which axes need to be set
  3341. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3342. {
  3343. codes[i] = code_seen(axis_codes[i]);
  3344. if(codes[i])
  3345. values[i] = code_value();
  3346. }
  3347. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3348. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3349. {
  3350. // As a special optimization, when _just_ clearing the E position
  3351. // we schedule a flag asynchronously along with the next block to
  3352. // reset the starting E position instead of stopping the planner
  3353. current_position[E_AXIS] = 0;
  3354. plan_reset_next_e();
  3355. }
  3356. else
  3357. {
  3358. // In any other case we're forced to synchronize
  3359. st_synchronize();
  3360. for(uint8_t i = 0; i < 3; ++i)
  3361. {
  3362. if(codes[i])
  3363. current_position[i] = values[i] + cs.add_homing[i];
  3364. }
  3365. if(codes[E_AXIS])
  3366. current_position[E_AXIS] = values[E_AXIS];
  3367. // Set all at once
  3368. plan_set_position_curposXYZE();
  3369. }
  3370. }
  3371. #ifdef EXTENDED_CAPABILITIES_REPORT
  3372. static void cap_line(const char* name, bool ena = false) {
  3373. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3374. }
  3375. static void extended_capabilities_report()
  3376. {
  3377. // AUTOREPORT_TEMP (M155)
  3378. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3379. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3380. // AUTOREPORT_FANS (M123)
  3381. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3382. #endif //FANCHECK and TACH_0 or TACH_1
  3383. // AUTOREPORT_POSITION (M114)
  3384. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3385. // EXTENDED_M20 (support for L and T parameters)
  3386. cap_line(PSTR("EXTENDED_M20"), 1);
  3387. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3388. }
  3389. #endif //EXTENDED_CAPABILITIES_REPORT
  3390. #ifdef BACKLASH_X
  3391. extern uint8_t st_backlash_x;
  3392. #endif //BACKLASH_X
  3393. #ifdef BACKLASH_Y
  3394. extern uint8_t st_backlash_y;
  3395. #endif //BACKLASH_Y
  3396. //! \ingroup marlin_main
  3397. //! @brief Parse and process commands
  3398. //!
  3399. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3400. //!
  3401. //!
  3402. //! Implemented Codes
  3403. //! -------------------
  3404. //!
  3405. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3406. //!
  3407. //!@n PRUSA CODES
  3408. //!@n P F - Returns FW versions
  3409. //!@n P R - Returns revision of printer
  3410. //!
  3411. //!@n G0 -> G1
  3412. //!@n G1 - Coordinated Movement X Y Z E
  3413. //!@n G2 - CW ARC
  3414. //!@n G3 - CCW ARC
  3415. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3416. //!@n G10 - retract filament according to settings of M207
  3417. //!@n G11 - retract recover filament according to settings of M208
  3418. //!@n G28 - Home all Axes
  3419. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3420. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3421. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3422. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3423. //!@n G80 - Automatic mesh bed leveling
  3424. //!@n G81 - Print bed profile
  3425. //!@n G90 - Use Absolute Coordinates
  3426. //!@n G91 - Use Relative Coordinates
  3427. //!@n G92 - Set current position to coordinates given
  3428. //!
  3429. //!@n M Codes
  3430. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3431. //!@n M1 - Same as M0
  3432. //!@n M17 - Enable/Power all stepper motors
  3433. //!@n M18 - Disable all stepper motors; same as M84
  3434. //!@n M20 - List SD card
  3435. //!@n M21 - Init SD card
  3436. //!@n M22 - Release SD card
  3437. //!@n M23 - Select SD file (M23 filename.g)
  3438. //!@n M24 - Start/resume SD print
  3439. //!@n M25 - Pause SD print
  3440. //!@n M26 - Set SD position in bytes (M26 S12345)
  3441. //!@n M27 - Report SD print status
  3442. //!@n M28 - Start SD write (M28 filename.g)
  3443. //!@n M29 - Stop SD write
  3444. //!@n M30 - Delete file from SD (M30 filename.g)
  3445. //!@n M31 - Output time since last M109 or SD card start to serial
  3446. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3447. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3448. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3449. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3450. //!@n M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used.
  3451. //!@n M73 - Show percent done and print time remaining
  3452. //!@n M80 - Turn on Power Supply
  3453. //!@n M81 - Turn off Power Supply
  3454. //!@n M82 - Set E codes absolute (default)
  3455. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3456. //!@n M84 - Disable steppers until next move,
  3457. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3458. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3459. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3460. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3461. //!@n M104 - Set extruder target temp
  3462. //!@n M105 - Read current temp
  3463. //!@n M106 - Fan on
  3464. //!@n M107 - Fan off
  3465. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3466. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3467. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3468. //!@n M112 - Emergency stop
  3469. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3470. //!@n M114 - Output current position to serial port
  3471. //!@n M115 - Capabilities string
  3472. //!@n M117 - display message
  3473. //!@n M119 - Output Endstop status to serial port
  3474. //!@n M123 - Tachometer value
  3475. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3476. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3477. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3478. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3479. //!@n M140 - Set bed target temp
  3480. //!@n M150 - Set BlinkM Color Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work.
  3481. //!@n M155 - Automatically send temperatures, fan speeds, position
  3482. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3483. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3484. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3485. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3486. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3487. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3488. //!@n M204 - Set default acceleration: S normal moves T filament only moves (M204 S3000 T7000) in mm/sec^2 also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  3489. //!@n M205 - advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk, E=maximum E jerk
  3490. //!@n M206 - set additional homing offset
  3491. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3492. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3493. //!@n M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  3494. //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  3495. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3496. //!@n M220 S<factor in percent>- set speed factor override percentage
  3497. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3498. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3499. //!@n M240 - Trigger a camera to take a photograph
  3500. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3501. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3502. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3503. //!@n M301 - Set PID parameters P I and D
  3504. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3505. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3506. //!@n M304 - Set bed PID parameters P I and D
  3507. //!@n M310 - Temperature model settings
  3508. //!@n M400 - Finish all moves
  3509. //!@n M401 - Lower z-probe if present
  3510. //!@n M402 - Raise z-probe if present
  3511. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3512. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3513. //!@n M406 - Turn off Filament Sensor extrusion control
  3514. //!@n M407 - Displays measured filament diameter
  3515. //!@n M500 - stores parameters in EEPROM
  3516. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3517. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3518. //!@n M503 - print the current settings (from memory not from EEPROM)
  3519. //!@n M509 - force language selection on next restart
  3520. //!@n M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  3521. //!@n M552 - Set IP address
  3522. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3523. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3524. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3525. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3526. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3527. //!@n M907 - Set digital trimpot motor current using axis codes.
  3528. //!@n M908 - Control digital trimpot directly.
  3529. //!@n M350 - Set microstepping mode.
  3530. //!@n M351 - Toggle MS1 MS2 pins directly.
  3531. //!
  3532. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3533. //!@n M999 - Restart after being stopped by error
  3534. //! <br><br>
  3535. /** @defgroup marlin_main Marlin main */
  3536. /** \ingroup GCodes */
  3537. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3538. /**
  3539. They are shown in order of appearance in the code.
  3540. There are reasons why some G Codes aren't in numerical order.
  3541. */
  3542. void process_commands()
  3543. {
  3544. if (!buflen) return; //empty command
  3545. #ifdef CMDBUFFER_DEBUG
  3546. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3547. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3548. SERIAL_ECHOLNPGM("");
  3549. SERIAL_ECHOPGM("In cmdqueue: ");
  3550. SERIAL_ECHO(buflen);
  3551. SERIAL_ECHOLNPGM("");
  3552. #endif /* CMDBUFFER_DEBUG */
  3553. unsigned long codenum; //throw away variable
  3554. char *starpos = NULL;
  3555. #ifdef ENABLE_AUTO_BED_LEVELING
  3556. float x_tmp, y_tmp, z_tmp, real_z;
  3557. #endif
  3558. // PRUSA GCODES
  3559. KEEPALIVE_STATE(IN_HANDLER);
  3560. /*!
  3561. ---------------------------------------------------------------------------------
  3562. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3563. This causes the given message to be shown in the status line on an attached LCD.
  3564. It is processed early as to allow printing messages that contain G, M, N or T.
  3565. ---------------------------------------------------------------------------------
  3566. ### Special internal commands
  3567. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3568. They are processed early as the commands are complex (strings).
  3569. These are only available on the MK3(S) as these require TMC2130 drivers:
  3570. - CRASH DETECTED
  3571. - CRASH RECOVER
  3572. - CRASH_CANCEL
  3573. - TMC_SET_WAVE
  3574. - TMC_SET_STEP
  3575. - TMC_SET_CHOP
  3576. */
  3577. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3578. {
  3579. starpos = (strchr(strchr_pointer + 5, '*'));
  3580. if (starpos != NULL)
  3581. *(starpos) = '\0';
  3582. lcd_setstatus(strchr_pointer + 5);
  3583. custom_message_type = CustomMsg::M117;
  3584. }
  3585. /*!
  3586. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3587. #### Usage
  3588. M0 [P<ms<] [S<sec>] [string]
  3589. M1 [P<ms>] [S<sec>] [string]
  3590. #### Parameters
  3591. - `P<ms>` - Expire time, in milliseconds
  3592. - `S<sec>` - Expire time, in seconds
  3593. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3594. */
  3595. else if (code_seen_P(PSTR("M0")) || code_seen_P(PSTR("M1 "))) {// M0 and M1 - (Un)conditional stop - Wait for user button press on LCD
  3596. const char *src = strchr_pointer + 2;
  3597. codenum = 0;
  3598. bool hasP = false, hasS = false;
  3599. if (code_seen('P')) {
  3600. codenum = code_value_long(); // milliseconds to wait
  3601. hasP = codenum > 0;
  3602. }
  3603. if (code_seen('S')) {
  3604. codenum = code_value_long() * 1000; // seconds to wait
  3605. hasS = codenum > 0;
  3606. }
  3607. starpos = strchr(src, '*');
  3608. if (starpos != NULL) *(starpos) = '\0';
  3609. while (*src == ' ') ++src;
  3610. custom_message_type = CustomMsg::M0Wait;
  3611. if (!hasP && !hasS && *src != '\0') {
  3612. lcd_setstatus(src);
  3613. } else {
  3614. // farmers want to abuse a bug from the previous firmware releases
  3615. // - they need to see the filename on the status screen instead of "Wait for user..."
  3616. // So we won't update the message in farm mode...
  3617. if( ! farm_mode){
  3618. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3619. } else {
  3620. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3621. }
  3622. }
  3623. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3624. st_synchronize();
  3625. previous_millis_cmd.start();
  3626. if (codenum > 0 ) {
  3627. codenum += _millis(); // keep track of when we started waiting
  3628. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3629. while(_millis() < codenum && !lcd_clicked()) {
  3630. manage_heater();
  3631. manage_inactivity(true);
  3632. lcd_update(0);
  3633. }
  3634. KEEPALIVE_STATE(IN_HANDLER);
  3635. lcd_ignore_click(false);
  3636. } else {
  3637. marlin_wait_for_click();
  3638. }
  3639. if (IS_SD_PRINTING)
  3640. custom_message_type = CustomMsg::Status;
  3641. else
  3642. LCD_MESSAGERPGM(MSG_WELCOME);
  3643. }
  3644. #ifdef TMC2130
  3645. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3646. {
  3647. // ### CRASH_DETECTED - TMC2130
  3648. // ---------------------------------
  3649. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3650. {
  3651. uint8_t mask = 0;
  3652. if (code_seen('X')) mask |= X_AXIS_MASK;
  3653. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3654. crashdet_detected(mask);
  3655. }
  3656. // ### CRASH_RECOVER - TMC2130
  3657. // ----------------------------------
  3658. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3659. crashdet_recover();
  3660. // ### CRASH_CANCEL - TMC2130
  3661. // ----------------------------------
  3662. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3663. crashdet_cancel();
  3664. }
  3665. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3666. {
  3667. // ### TMC_SET_WAVE_
  3668. // --------------------
  3669. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3670. {
  3671. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3672. axis = (axis == 'E')?3:(axis - 'X');
  3673. if (axis < 4)
  3674. {
  3675. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3676. tmc2130_set_wave(axis, 247, fac);
  3677. }
  3678. }
  3679. // ### TMC_SET_STEP_
  3680. // ------------------
  3681. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3682. {
  3683. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3684. axis = (axis == 'E')?3:(axis - 'X');
  3685. if (axis < 4)
  3686. {
  3687. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3688. uint16_t res = tmc2130_get_res(axis);
  3689. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3690. }
  3691. }
  3692. // ### TMC_SET_CHOP_
  3693. // -------------------
  3694. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3695. {
  3696. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3697. axis = (axis == 'E')?3:(axis - 'X');
  3698. if (axis < 4)
  3699. {
  3700. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3701. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3702. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3703. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3704. char* str_end = 0;
  3705. if (CMDBUFFER_CURRENT_STRING[14])
  3706. {
  3707. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3708. if (str_end && *str_end)
  3709. {
  3710. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3711. if (str_end && *str_end)
  3712. {
  3713. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3714. if (str_end && *str_end)
  3715. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3716. }
  3717. }
  3718. }
  3719. tmc2130_chopper_config[axis].toff = chop0;
  3720. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3721. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3722. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3723. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3724. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3725. }
  3726. }
  3727. }
  3728. #ifdef BACKLASH_X
  3729. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3730. {
  3731. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3732. st_backlash_x = bl;
  3733. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3734. }
  3735. #endif //BACKLASH_X
  3736. #ifdef BACKLASH_Y
  3737. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3738. {
  3739. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3740. st_backlash_y = bl;
  3741. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3742. }
  3743. #endif //BACKLASH_Y
  3744. #endif //TMC2130
  3745. else if(code_seen_P(PSTR("PRUSA"))){
  3746. /*!
  3747. ---------------------------------------------------------------------------------
  3748. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3749. Set of internal PRUSA commands
  3750. #### Usage
  3751. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3752. #### Parameters
  3753. - `PRN` - Prints revision of the printer
  3754. - `FAN` - Prints fan details
  3755. - `thx`
  3756. - `uvlo`
  3757. - `MMURES` - Reset MMU
  3758. - `RESET` - (Careful!)
  3759. - `fv` - ?
  3760. - `M28`
  3761. - `SN`
  3762. - `Fir` - Prints firmware version
  3763. - `Rev`- Prints filament size, elelectronics, nozzle type
  3764. - `Lang` - Reset the language
  3765. - `Lz`
  3766. - `FR` - Full factory reset
  3767. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3768. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3769. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3770. */
  3771. if (farm_prusa_code_seen()) {}
  3772. else if(code_seen_P(PSTR("FANPINTST"))) {
  3773. gcode_PRUSA_BadRAMBoFanTest();
  3774. }
  3775. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3776. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3777. }
  3778. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3779. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3780. enquecommand_P(PSTR("M24"));
  3781. }
  3782. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3783. {
  3784. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  3785. }
  3786. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3787. #ifdef WATCHDOG
  3788. #if defined(XFLASH) && defined(BOOTAPP)
  3789. boot_app_magic = BOOT_APP_MAGIC;
  3790. boot_app_flags = BOOT_APP_FLG_RUN;
  3791. #endif //defined(XFLASH) && defined(BOOTAPP)
  3792. softReset();
  3793. #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.
  3794. asm volatile("jmp 0x3E000");
  3795. #endif
  3796. }
  3797. #ifdef PRUSA_SN_SUPPORT
  3798. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3799. char SN[20];
  3800. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3801. if (SN[19])
  3802. puts_P(PSTR("SN invalid"));
  3803. else
  3804. puts(SN);
  3805. }
  3806. #endif //PRUSA_SN_SUPPORT
  3807. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3808. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3809. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3810. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3811. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3812. lang_reset();
  3813. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3814. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3815. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3816. // Factory full reset
  3817. factory_reset(0);
  3818. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3819. // Change the MBL status without changing the logical Z position.
  3820. if(code_seen('V')) {
  3821. bool value = code_value_short();
  3822. st_synchronize();
  3823. if(value != mbl.active) {
  3824. mbl.active = value;
  3825. // Use plan_set_z_position to reset the physical values
  3826. plan_set_z_position(current_position[Z_AXIS]);
  3827. }
  3828. }
  3829. //-//
  3830. /*
  3831. } else if(code_seen("rrr")) {
  3832. MYSERIAL.println("=== checking ===");
  3833. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3834. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3835. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3836. MYSERIAL.println(farm_mode,DEC);
  3837. MYSERIAL.println(eCheckMode,DEC);
  3838. } else if(code_seen("www")) {
  3839. MYSERIAL.println("=== @ FF ===");
  3840. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3841. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3842. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3843. */
  3844. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3845. uint16_t nDiameter;
  3846. if(code_seen('D'))
  3847. {
  3848. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3849. nozzle_diameter_check(nDiameter);
  3850. }
  3851. else if(code_seen_P(PSTR("set")) && farm_mode)
  3852. {
  3853. strchr_pointer++; // skip 1st char (~ 's')
  3854. strchr_pointer++; // skip 2nd char (~ 'e')
  3855. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3856. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3857. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3858. }
  3859. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3860. //-// !!! SupportMenu
  3861. /*
  3862. // musi byt PRED "PRUSA model"
  3863. } else if (code_seen("smodel")) { //! PRUSA smodel
  3864. size_t nOffset;
  3865. // ! -> "l"
  3866. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3867. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3868. if(*(strchr_pointer+1+nOffset))
  3869. printer_smodel_check(strchr_pointer);
  3870. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3871. } else if (code_seen("model")) { //! PRUSA model
  3872. uint16_t nPrinterModel;
  3873. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3874. nPrinterModel=(uint16_t)code_value_long();
  3875. if(nPrinterModel!=0)
  3876. printer_model_check(nPrinterModel);
  3877. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3878. } else if (code_seen("version")) { //! PRUSA version
  3879. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3880. while(*strchr_pointer==' ') // skip leading spaces
  3881. strchr_pointer++;
  3882. if(*strchr_pointer!=0)
  3883. fw_version_check(strchr_pointer);
  3884. else SERIAL_PROTOCOLLN(FW_VERSION);
  3885. } else if (code_seen("gcode")) { //! PRUSA gcode
  3886. uint16_t nGcodeLevel;
  3887. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3888. nGcodeLevel=(uint16_t)code_value_long();
  3889. if(nGcodeLevel!=0)
  3890. gcode_level_check(nGcodeLevel);
  3891. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3892. */
  3893. }
  3894. //else if (code_seen('Cal')) {
  3895. // lcd_calibration();
  3896. // }
  3897. }
  3898. // This prevents reading files with "^" in their names.
  3899. // Since it is unclear, if there is some usage of this construct,
  3900. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3901. // else if (code_seen('^')) {
  3902. // // nothing, this is a version line
  3903. // }
  3904. else if(code_seen('G'))
  3905. {
  3906. gcode_in_progress = code_value_short();
  3907. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3908. switch (gcode_in_progress)
  3909. {
  3910. /*!
  3911. ---------------------------------------------------------------------------------
  3912. # G Codes
  3913. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3914. In Prusa Firmware G0 and G1 are the same.
  3915. #### Usage
  3916. G0 [ X | Y | Z | E | F | S ]
  3917. G1 [ X | Y | Z | E | F | S ]
  3918. #### Parameters
  3919. - `X` - The position to move to on the X axis
  3920. - `Y` - The position to move to on the Y axis
  3921. - `Z` - The position to move to on the Z axis
  3922. - `E` - The amount to extrude between the starting point and ending point
  3923. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3924. */
  3925. case 0: // G0 -> G1
  3926. case 1: // G1
  3927. {
  3928. uint16_t start_segment_idx = restore_interrupted_gcode();
  3929. get_coordinates(); // For X Y Z E F
  3930. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3931. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3932. }
  3933. #ifdef FWRETRACT
  3934. if(cs.autoretract_enabled) {
  3935. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3936. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3937. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3938. st_synchronize();
  3939. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3940. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3941. retract(!retracted[active_extruder]);
  3942. return;
  3943. }
  3944. }
  3945. }
  3946. #endif //FWRETRACT
  3947. prepare_move(start_segment_idx);
  3948. //ClearToSend();
  3949. }
  3950. break;
  3951. /*!
  3952. ### 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>
  3953. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3954. #### Usage
  3955. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3956. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3957. #### Parameters
  3958. - `X` - The position to move to on the X axis
  3959. - `Y` - The position to move to on the Y axis
  3960. - 'Z' - The position to move to on the Z axis
  3961. - `I` - The point in X space from the current X position to maintain a constant distance from
  3962. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3963. - `E` - The amount to extrude between the starting point and ending point
  3964. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3965. */
  3966. case 2:
  3967. case 3:
  3968. {
  3969. uint16_t start_segment_idx = restore_interrupted_gcode();
  3970. #ifdef SF_ARC_FIX
  3971. bool relative_mode_backup = relative_mode;
  3972. relative_mode = true;
  3973. #endif
  3974. get_coordinates(); // For X Y Z E F
  3975. #ifdef SF_ARC_FIX
  3976. relative_mode=relative_mode_backup;
  3977. #endif
  3978. offset[0] = code_seen('I') ? code_value() : 0.f;
  3979. offset[1] = code_seen('J') ? code_value() : 0.f;
  3980. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3981. } break;
  3982. /*!
  3983. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3984. Pause the machine for a period of time.
  3985. #### Usage
  3986. G4 [ P | S ]
  3987. #### Parameters
  3988. - `P` - Time to wait, in milliseconds
  3989. - `S` - Time to wait, in seconds
  3990. */
  3991. case 4:
  3992. codenum = 0;
  3993. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3994. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3995. if(codenum != 0)
  3996. {
  3997. if(custom_message_type != CustomMsg::M117)
  3998. {
  3999. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  4000. }
  4001. }
  4002. st_synchronize();
  4003. codenum += _millis(); // keep track of when we started waiting
  4004. previous_millis_cmd.start();
  4005. while(_millis() < codenum) {
  4006. manage_heater();
  4007. manage_inactivity();
  4008. lcd_update(0);
  4009. }
  4010. break;
  4011. #ifdef FWRETRACT
  4012. /*!
  4013. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  4014. Retracts filament according to settings of `M207`
  4015. */
  4016. case 10:
  4017. #if EXTRUDERS > 1
  4018. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  4019. retract(true,retracted_swap[active_extruder]);
  4020. #else
  4021. retract(true);
  4022. #endif
  4023. break;
  4024. /*!
  4025. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  4026. Unretracts/recovers filament according to settings of `M208`
  4027. */
  4028. case 11:
  4029. #if EXTRUDERS > 1
  4030. retract(false,retracted_swap[active_extruder]);
  4031. #else
  4032. retract(false);
  4033. #endif
  4034. break;
  4035. #endif //FWRETRACT
  4036. /*!
  4037. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  4038. Units are in millimeters. Prusa doesn't support inches.
  4039. */
  4040. case 21:
  4041. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  4042. /*!
  4043. ### 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>
  4044. 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).
  4045. #### Usage
  4046. G28 [ X | Y | Z | W | C ]
  4047. #### Parameters
  4048. - `X` - Flag to go back to the X axis origin
  4049. - `Y` - Flag to go back to the Y axis origin
  4050. - `Z` - Flag to go back to the Z axis origin
  4051. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  4052. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  4053. */
  4054. case 28:
  4055. {
  4056. long home_x_value = 0;
  4057. long home_y_value = 0;
  4058. long home_z_value = 0;
  4059. // Which axes should be homed?
  4060. bool home_x = code_seen(axis_codes[X_AXIS]);
  4061. if (home_x) home_x_value = code_value_long();
  4062. bool home_y = code_seen(axis_codes[Y_AXIS]);
  4063. if (home_y) home_y_value = code_value_long();
  4064. bool home_z = code_seen(axis_codes[Z_AXIS]);
  4065. if (home_z) home_z_value = code_value_long();
  4066. bool without_mbl = code_seen('W');
  4067. // calibrate?
  4068. #ifdef TMC2130
  4069. bool calib = code_seen('C');
  4070. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4071. #else
  4072. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4073. #endif //TMC2130
  4074. if ((home_x || home_y || without_mbl || home_z) == false) {
  4075. gcode_G80();
  4076. }
  4077. break;
  4078. }
  4079. #ifdef ENABLE_AUTO_BED_LEVELING
  4080. /*!
  4081. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4082. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4083. See `G81`
  4084. */
  4085. case 29:
  4086. {
  4087. #if Z_MIN_PIN == -1
  4088. #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."
  4089. #endif
  4090. // Prevent user from running a G29 without first homing in X and Y
  4091. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4092. {
  4093. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4094. SERIAL_ECHO_START;
  4095. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4096. break; // abort G29, since we don't know where we are
  4097. }
  4098. st_synchronize();
  4099. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4100. //vector_3 corrected_position = plan_get_position_mm();
  4101. //corrected_position.debug("position before G29");
  4102. plan_bed_level_matrix.set_to_identity();
  4103. vector_3 uncorrected_position = plan_get_position();
  4104. //uncorrected_position.debug("position durring G29");
  4105. current_position[X_AXIS] = uncorrected_position.x;
  4106. current_position[Y_AXIS] = uncorrected_position.y;
  4107. current_position[Z_AXIS] = uncorrected_position.z;
  4108. plan_set_position_curposXYZE();
  4109. int l_feedmultiply = setup_for_endstop_move();
  4110. feedrate = homing_feedrate[Z_AXIS];
  4111. #ifdef AUTO_BED_LEVELING_GRID
  4112. // probe at the points of a lattice grid
  4113. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4114. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4115. // solve the plane equation ax + by + d = z
  4116. // A is the matrix with rows [x y 1] for all the probed points
  4117. // B is the vector of the Z positions
  4118. // 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
  4119. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4120. // "A" matrix of the linear system of equations
  4121. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4122. // "B" vector of Z points
  4123. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4124. int probePointCounter = 0;
  4125. bool zig = true;
  4126. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4127. {
  4128. int xProbe, xInc;
  4129. if (zig)
  4130. {
  4131. xProbe = LEFT_PROBE_BED_POSITION;
  4132. //xEnd = RIGHT_PROBE_BED_POSITION;
  4133. xInc = xGridSpacing;
  4134. zig = false;
  4135. } else // zag
  4136. {
  4137. xProbe = RIGHT_PROBE_BED_POSITION;
  4138. //xEnd = LEFT_PROBE_BED_POSITION;
  4139. xInc = -xGridSpacing;
  4140. zig = true;
  4141. }
  4142. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4143. {
  4144. float z_before;
  4145. if (probePointCounter == 0)
  4146. {
  4147. // raise before probing
  4148. z_before = Z_RAISE_BEFORE_PROBING;
  4149. } else
  4150. {
  4151. // raise extruder
  4152. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4153. }
  4154. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4155. eqnBVector[probePointCounter] = measured_z;
  4156. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4157. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4158. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4159. probePointCounter++;
  4160. xProbe += xInc;
  4161. }
  4162. }
  4163. clean_up_after_endstop_move(l_feedmultiply);
  4164. // solve lsq problem
  4165. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4166. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4167. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4168. SERIAL_PROTOCOLPGM(" b: ");
  4169. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4170. SERIAL_PROTOCOLPGM(" d: ");
  4171. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4172. set_bed_level_equation_lsq(plane_equation_coefficients);
  4173. free(plane_equation_coefficients);
  4174. #else // AUTO_BED_LEVELING_GRID not defined
  4175. // Probe at 3 arbitrary points
  4176. // probe 1
  4177. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4178. // probe 2
  4179. 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);
  4180. // probe 3
  4181. 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);
  4182. clean_up_after_endstop_move(l_feedmultiply);
  4183. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4184. #endif // AUTO_BED_LEVELING_GRID
  4185. st_synchronize();
  4186. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4187. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4188. // When the bed is uneven, this height must be corrected.
  4189. 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)
  4190. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4191. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4192. z_tmp = current_position[Z_AXIS];
  4193. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4194. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4195. plan_set_position_curposXYZE();
  4196. }
  4197. break;
  4198. #ifndef Z_PROBE_SLED
  4199. /*!
  4200. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4201. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4202. */
  4203. case 30:
  4204. {
  4205. st_synchronize();
  4206. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4207. int l_feedmultiply = setup_for_endstop_move();
  4208. feedrate = homing_feedrate[Z_AXIS];
  4209. run_z_probe();
  4210. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4211. SERIAL_PROTOCOLPGM(" X: ");
  4212. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4213. SERIAL_PROTOCOLPGM(" Y: ");
  4214. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4215. SERIAL_PROTOCOLPGM(" Z: ");
  4216. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4217. SERIAL_PROTOCOLPGM("\n");
  4218. clean_up_after_endstop_move(l_feedmultiply);
  4219. }
  4220. break;
  4221. #else
  4222. /*!
  4223. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4224. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4225. */
  4226. case 31:
  4227. dock_sled(true);
  4228. break;
  4229. /*!
  4230. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4231. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4232. */
  4233. case 32:
  4234. dock_sled(false);
  4235. break;
  4236. #endif // Z_PROBE_SLED
  4237. #endif // ENABLE_AUTO_BED_LEVELING
  4238. #ifdef MESH_BED_LEVELING
  4239. /*!
  4240. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4241. Sensor must be over the bed.
  4242. The maximum travel distance before an error is triggered is 10mm.
  4243. */
  4244. case 30:
  4245. {
  4246. st_synchronize();
  4247. homing_flag = true;
  4248. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4249. int l_feedmultiply = setup_for_endstop_move();
  4250. feedrate = homing_feedrate[Z_AXIS];
  4251. find_bed_induction_sensor_point_z(-10.f, 3);
  4252. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4253. clean_up_after_endstop_move(l_feedmultiply);
  4254. homing_flag = false;
  4255. }
  4256. break;
  4257. /*!
  4258. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4259. Show/print PINDA temperature interpolating.
  4260. */
  4261. case 75:
  4262. {
  4263. for (uint8_t i = 40; i <= 110; i++)
  4264. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4265. }
  4266. break;
  4267. /*!
  4268. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4269. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4270. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4271. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4272. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4273. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4274. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4275. #### Example
  4276. ```
  4277. G76
  4278. echo PINDA probe calibration start
  4279. echo start temperature: 35.0°
  4280. echo ...
  4281. echo PINDA temperature -- Z shift (mm): 0.---
  4282. ```
  4283. */
  4284. case 76:
  4285. {
  4286. #ifdef PINDA_THERMISTOR
  4287. if (!has_temperature_compensation())
  4288. {
  4289. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4290. break;
  4291. }
  4292. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4293. //we need to know accurate position of first calibration point
  4294. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4295. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4296. break;
  4297. }
  4298. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4299. {
  4300. // We don't know where we are! HOME!
  4301. // Push the commands to the front of the message queue in the reverse order!
  4302. // There shall be always enough space reserved for these commands.
  4303. repeatcommand_front(); // repeat G76 with all its parameters
  4304. enquecommand_front_P(G28W0);
  4305. break;
  4306. }
  4307. 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
  4308. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  4309. if (result == LCD_LEFT_BUTTON_CHOICE)
  4310. {
  4311. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4312. plan_buffer_line_curposXYZE(3000 / 60);
  4313. current_position[Z_AXIS] = 50;
  4314. current_position[Y_AXIS] = 180;
  4315. plan_buffer_line_curposXYZE(3000 / 60);
  4316. st_synchronize();
  4317. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4318. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4319. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4320. plan_buffer_line_curposXYZE(3000 / 60);
  4321. st_synchronize();
  4322. gcode_G28(false, false, true);
  4323. }
  4324. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4325. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4326. current_position[Z_AXIS] = 100;
  4327. plan_buffer_line_curposXYZE(3000 / 60);
  4328. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4329. lcd_temp_cal_show_result(false);
  4330. break;
  4331. }
  4332. }
  4333. st_synchronize();
  4334. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4335. lcd_update_enable(true);
  4336. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4337. float zero_z;
  4338. int z_shift = 0; //unit: steps
  4339. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4340. if (start_temp < 35) start_temp = 35;
  4341. if (start_temp < current_temperature_pinda) start_temp += 5;
  4342. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4343. // setTargetHotend(200, 0);
  4344. setTargetBed(70 + (start_temp - 30));
  4345. custom_message_type = CustomMsg::TempCal;
  4346. custom_message_state = 1;
  4347. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4348. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4349. plan_buffer_line_curposXYZE(3000 / 60);
  4350. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4351. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4352. plan_buffer_line_curposXYZE(3000 / 60);
  4353. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4354. plan_buffer_line_curposXYZE(3000 / 60);
  4355. st_synchronize();
  4356. while (current_temperature_pinda < start_temp)
  4357. {
  4358. delay_keep_alive(1000);
  4359. serialecho_temperatures();
  4360. }
  4361. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4362. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4363. plan_buffer_line_curposXYZE(3000 / 60);
  4364. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4365. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4366. plan_buffer_line_curposXYZE(3000 / 60);
  4367. st_synchronize();
  4368. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4369. if (find_z_result == false) {
  4370. lcd_temp_cal_show_result(find_z_result);
  4371. homing_flag = false;
  4372. break;
  4373. }
  4374. zero_z = current_position[Z_AXIS];
  4375. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4376. int i = -1; for (; i < 5; i++)
  4377. {
  4378. float temp = (40 + i * 5);
  4379. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4380. if (i >= 0) {
  4381. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4382. }
  4383. if (start_temp <= temp) break;
  4384. }
  4385. for (i++; i < 5; i++)
  4386. {
  4387. float temp = (40 + i * 5);
  4388. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4389. custom_message_state = i + 2;
  4390. setTargetBed(50 + 10 * (temp - 30) / 5);
  4391. // setTargetHotend(255, 0);
  4392. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4393. plan_buffer_line_curposXYZE(3000 / 60);
  4394. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4395. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4396. plan_buffer_line_curposXYZE(3000 / 60);
  4397. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4398. plan_buffer_line_curposXYZE(3000 / 60);
  4399. st_synchronize();
  4400. while (current_temperature_pinda < temp)
  4401. {
  4402. delay_keep_alive(1000);
  4403. serialecho_temperatures();
  4404. }
  4405. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4406. plan_buffer_line_curposXYZE(3000 / 60);
  4407. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4408. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4409. plan_buffer_line_curposXYZE(3000 / 60);
  4410. st_synchronize();
  4411. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4412. if (find_z_result == false) {
  4413. lcd_temp_cal_show_result(find_z_result);
  4414. break;
  4415. }
  4416. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4417. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4418. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4419. }
  4420. lcd_temp_cal_show_result(true);
  4421. homing_flag = false;
  4422. #else //PINDA_THERMISTOR
  4423. setTargetBed(PINDA_MIN_T);
  4424. float zero_z;
  4425. int z_shift = 0; //unit: steps
  4426. int t_c; // temperature
  4427. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4428. // We don't know where we are! HOME!
  4429. // Push the commands to the front of the message queue in the reverse order!
  4430. // There shall be always enough space reserved for these commands.
  4431. repeatcommand_front(); // repeat G76 with all its parameters
  4432. enquecommand_front_P(G28W0);
  4433. break;
  4434. }
  4435. puts_P(_N("PINDA probe calibration start"));
  4436. custom_message_type = CustomMsg::TempCal;
  4437. custom_message_state = 1;
  4438. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4439. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4440. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4441. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4442. plan_buffer_line_curposXYZE(3000 / 60);
  4443. st_synchronize();
  4444. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4445. delay_keep_alive(1000);
  4446. serialecho_temperatures();
  4447. }
  4448. //enquecommand_P(PSTR("M190 S50"));
  4449. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4450. delay_keep_alive(1000);
  4451. serialecho_temperatures();
  4452. }
  4453. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4454. current_position[Z_AXIS] = 5;
  4455. plan_buffer_line_curposXYZE(3000 / 60);
  4456. current_position[X_AXIS] = BED_X0;
  4457. current_position[Y_AXIS] = BED_Y0;
  4458. plan_buffer_line_curposXYZE(3000 / 60);
  4459. st_synchronize();
  4460. find_bed_induction_sensor_point_z(-1.f);
  4461. zero_z = current_position[Z_AXIS];
  4462. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4463. for (int i = 0; i<5; i++) {
  4464. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4465. custom_message_state = i + 2;
  4466. t_c = 60 + i * 10;
  4467. setTargetBed(t_c);
  4468. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4469. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4470. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4471. plan_buffer_line_curposXYZE(3000 / 60);
  4472. st_synchronize();
  4473. while (degBed() < t_c) {
  4474. delay_keep_alive(1000);
  4475. serialecho_temperatures();
  4476. }
  4477. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4478. delay_keep_alive(1000);
  4479. serialecho_temperatures();
  4480. }
  4481. current_position[Z_AXIS] = 5;
  4482. plan_buffer_line_curposXYZE(3000 / 60);
  4483. current_position[X_AXIS] = BED_X0;
  4484. current_position[Y_AXIS] = BED_Y0;
  4485. plan_buffer_line_curposXYZE(3000 / 60);
  4486. st_synchronize();
  4487. find_bed_induction_sensor_point_z(-1.f);
  4488. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4489. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4490. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4491. }
  4492. custom_message_type = CustomMsg::Status;
  4493. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4494. puts_P(_N("Temperature calibration done."));
  4495. disable_x();
  4496. disable_y();
  4497. disable_z();
  4498. disable_e0();
  4499. disable_e1();
  4500. disable_e2();
  4501. setTargetBed(0); //set bed target temperature back to 0
  4502. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4503. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4504. lcd_update_enable(true);
  4505. lcd_update(2);
  4506. #endif //PINDA_THERMISTOR
  4507. }
  4508. break;
  4509. /*!
  4510. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4511. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4512. #### Usage
  4513. G80 [ N | R | V | L | R | F | B ]
  4514. #### Parameters
  4515. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4516. - `R` - Probe retries. Default 3 max. 10
  4517. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4518. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4519. #### Additional Parameters
  4520. - `L` - Left Bed Level correct value in um.
  4521. - `R` - Right Bed Level correct value in um.
  4522. - `F` - Front Bed Level correct value in um.
  4523. - `B` - Back Bed Level correct value in um.
  4524. */
  4525. /*
  4526. * Probes a grid and produces a mesh to compensate for variable bed height
  4527. * The S0 report the points as below
  4528. * +----> X-axis
  4529. * |
  4530. * |
  4531. * v Y-axis
  4532. */
  4533. case 80: {
  4534. gcode_G80();
  4535. }
  4536. break;
  4537. /*!
  4538. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4539. Prints mesh bed leveling status and bed profile if activated.
  4540. */
  4541. case 81:
  4542. if (mbl.active) {
  4543. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4544. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4545. SERIAL_PROTOCOL(',');
  4546. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4547. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4548. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4549. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4550. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4551. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4552. SERIAL_PROTOCOLPGM(" ");
  4553. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4554. }
  4555. SERIAL_PROTOCOLLN();
  4556. }
  4557. }
  4558. else
  4559. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4560. break;
  4561. #if 0
  4562. /*!
  4563. ### 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>
  4564. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4565. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4566. */
  4567. case 82:
  4568. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4569. int l_feedmultiply = setup_for_endstop_move();
  4570. find_bed_induction_sensor_point_z();
  4571. clean_up_after_endstop_move(l_feedmultiply);
  4572. SERIAL_PROTOCOLPGM("Bed found at: ");
  4573. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4574. SERIAL_PROTOCOLPGM("\n");
  4575. break;
  4576. /*!
  4577. ### 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>
  4578. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4579. */
  4580. case 83:
  4581. {
  4582. int babystepz = code_seen('S') ? code_value() : 0;
  4583. int BabyPosition = code_seen('P') ? code_value() : 0;
  4584. if (babystepz != 0) {
  4585. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4586. // Is the axis indexed starting with zero or one?
  4587. if (BabyPosition > 4) {
  4588. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4589. }else{
  4590. // Save it to the eeprom
  4591. babystepLoadZ = babystepz;
  4592. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4593. // adjust the Z
  4594. babystepsTodoZadd(babystepLoadZ);
  4595. }
  4596. }
  4597. }
  4598. break;
  4599. /*!
  4600. ### 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>
  4601. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4602. */
  4603. case 84:
  4604. babystepsTodoZsubtract(babystepLoadZ);
  4605. // babystepLoadZ = 0;
  4606. break;
  4607. /*!
  4608. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4609. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4610. */
  4611. case 85:
  4612. lcd_pick_babystep();
  4613. break;
  4614. #endif
  4615. /*!
  4616. ### 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>
  4617. This G-code will be performed at the start of a calibration script.
  4618. (Prusa3D specific)
  4619. */
  4620. case 86:
  4621. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4622. break;
  4623. /*!
  4624. ### 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>
  4625. This G-code will be performed at the end of a calibration script.
  4626. (Prusa3D specific)
  4627. */
  4628. case 87:
  4629. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4630. break;
  4631. /*!
  4632. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4633. Currently has no effect.
  4634. */
  4635. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4636. case 88:
  4637. break;
  4638. #endif // ENABLE_MESH_BED_LEVELING
  4639. /*!
  4640. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4641. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4642. */
  4643. case 90: {
  4644. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4645. }
  4646. break;
  4647. /*!
  4648. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4649. All coordinates from now on are relative to the last position. E axis is left intact.
  4650. */
  4651. case 91: {
  4652. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4653. }
  4654. break;
  4655. /*!
  4656. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4657. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4658. If a parameter is omitted, that axis will not be affected.
  4659. 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`).
  4660. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4661. #### Usage
  4662. G92 [ X | Y | Z | E ]
  4663. #### Parameters
  4664. - `X` - new X axis position
  4665. - `Y` - new Y axis position
  4666. - `Z` - new Z axis position
  4667. - `E` - new extruder position
  4668. */
  4669. case 92: {
  4670. gcode_G92();
  4671. }
  4672. break;
  4673. #ifdef PRUSA_FARM
  4674. /*!
  4675. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4676. Enable Prusa-specific Farm functions and g-code.
  4677. See Internal Prusa commands.
  4678. */
  4679. case 98:
  4680. farm_gcode_g98();
  4681. break;
  4682. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4683. Disables Prusa-specific Farm functions and g-code.
  4684. */
  4685. case 99:
  4686. farm_gcode_g99();
  4687. break;
  4688. #endif //PRUSA_FARM
  4689. default:
  4690. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4691. }
  4692. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4693. gcode_in_progress = 0;
  4694. } // end if(code_seen('G'))
  4695. /*!
  4696. ### End of G-Codes
  4697. */
  4698. /*!
  4699. ---------------------------------------------------------------------------------
  4700. # M Commands
  4701. */
  4702. else if(code_seen('M'))
  4703. {
  4704. int index;
  4705. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4706. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4707. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4708. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4709. } else
  4710. {
  4711. mcode_in_progress = code_value_short();
  4712. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4713. switch(mcode_in_progress)
  4714. {
  4715. /*!
  4716. ### 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>
  4717. */
  4718. case 17:
  4719. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4720. enable_x();
  4721. enable_y();
  4722. enable_z();
  4723. enable_e0();
  4724. enable_e1();
  4725. enable_e2();
  4726. break;
  4727. #ifdef SDSUPPORT
  4728. /*!
  4729. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4730. #### Usage
  4731. M20 [ L | T ]
  4732. #### Parameters
  4733. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4734. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4735. */
  4736. case 20:
  4737. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4738. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4739. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4740. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4741. break;
  4742. /*!
  4743. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4744. */
  4745. case 21:
  4746. card.initsd();
  4747. break;
  4748. /*!
  4749. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4750. */
  4751. case 22:
  4752. card.release();
  4753. break;
  4754. /*!
  4755. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4756. #### Usage
  4757. M23 [filename]
  4758. */
  4759. case 23:
  4760. starpos = (strchr(strchr_pointer + 4,'*'));
  4761. if(starpos!=NULL)
  4762. *(starpos)='\0';
  4763. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4764. break;
  4765. /*!
  4766. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4767. */
  4768. case 24:
  4769. if (isPrintPaused)
  4770. lcd_resume_print();
  4771. else
  4772. {
  4773. if (!card.get_sdpos())
  4774. {
  4775. // A new print has started from scratch, reset stats
  4776. failstats_reset_print();
  4777. sdpos_atomic = 0;
  4778. #ifndef LA_NOCOMPAT
  4779. la10c_reset();
  4780. #endif
  4781. }
  4782. card.startFileprint();
  4783. starttime=_millis();
  4784. if (MMU2::mmu2.Enabled())
  4785. {
  4786. if (MMU2::mmu2.FindaDetectsFilament() && !fsensor.getFilamentPresent())
  4787. { // Filament only half way into the PTFE. Unload the filament.
  4788. MMU2::mmu2.unload();
  4789. // Tx and Tc gcodes take care of loading the filament to the nozzle.
  4790. }
  4791. }
  4792. }
  4793. break;
  4794. /*!
  4795. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4796. Set position in SD card file to index in bytes.
  4797. This command is expected to be called after M23 and before M24.
  4798. Otherwise effect of this command is undefined.
  4799. #### Usage
  4800. M26 [ S ]
  4801. #### Parameters
  4802. - `S` - Index in bytes
  4803. */
  4804. case 26:
  4805. if(card.cardOK && code_seen('S')) {
  4806. long index = code_value_long();
  4807. card.setIndex(index);
  4808. // We don't disable interrupt during update of sdpos_atomic
  4809. // as we expect, that SD card print is not active in this moment
  4810. sdpos_atomic = index;
  4811. }
  4812. break;
  4813. /*!
  4814. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4815. #### Usage
  4816. M27 [ P ]
  4817. #### Parameters
  4818. - `P` - Show full SFN path instead of LFN only.
  4819. */
  4820. case 27:
  4821. card.getStatus(code_seen('P'));
  4822. break;
  4823. /*!
  4824. ### 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>
  4825. */
  4826. case 28:
  4827. starpos = (strchr(strchr_pointer + 4,'*'));
  4828. if(starpos != NULL){
  4829. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4830. strchr_pointer = strchr(npos,' ') + 1;
  4831. *(starpos) = '\0';
  4832. }
  4833. card.openFileWrite(strchr_pointer+4);
  4834. break;
  4835. /*! ### 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>
  4836. 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.
  4837. */
  4838. case 29:
  4839. //processed in write to file routine above
  4840. //card,saving = false;
  4841. break;
  4842. /*!
  4843. ### 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>
  4844. #### Usage
  4845. M30 [filename]
  4846. */
  4847. case 30:
  4848. if (card.cardOK){
  4849. card.closefile();
  4850. starpos = (strchr(strchr_pointer + 4,'*'));
  4851. if(starpos != NULL){
  4852. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4853. strchr_pointer = strchr(npos,' ') + 1;
  4854. *(starpos) = '\0';
  4855. }
  4856. card.removeFile(strchr_pointer + 4);
  4857. }
  4858. break;
  4859. /*!
  4860. ### 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>
  4861. @todo What are the parameters P and S for in M32?
  4862. */
  4863. case 32:
  4864. {
  4865. if(card.sdprinting) {
  4866. st_synchronize();
  4867. }
  4868. starpos = (strchr(strchr_pointer + 4,'*'));
  4869. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4870. if(namestartpos==NULL)
  4871. {
  4872. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4873. }
  4874. else
  4875. namestartpos++; //to skip the '!'
  4876. if(starpos!=NULL)
  4877. *(starpos)='\0';
  4878. bool call_procedure=(code_seen('P'));
  4879. if(strchr_pointer>namestartpos)
  4880. call_procedure=false; //false alert, 'P' found within filename
  4881. if( card.cardOK )
  4882. {
  4883. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4884. if(code_seen('S'))
  4885. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4886. card.setIndex(code_value_long());
  4887. card.startFileprint();
  4888. if(!call_procedure)
  4889. {
  4890. if(!card.get_sdpos())
  4891. {
  4892. // A new print has started from scratch, reset stats
  4893. failstats_reset_print();
  4894. sdpos_atomic = 0;
  4895. #ifndef LA_NOCOMPAT
  4896. la10c_reset();
  4897. #endif
  4898. }
  4899. starttime=_millis(); // procedure calls count as normal print time.
  4900. }
  4901. }
  4902. } break;
  4903. /*!
  4904. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4905. #### Usage
  4906. M928 [filename]
  4907. */
  4908. case 928:
  4909. starpos = (strchr(strchr_pointer + 5,'*'));
  4910. if(starpos != NULL){
  4911. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4912. strchr_pointer = strchr(npos,' ') + 1;
  4913. *(starpos) = '\0';
  4914. }
  4915. card.openLogFile(strchr_pointer+5);
  4916. break;
  4917. #endif //SDSUPPORT
  4918. /*!
  4919. ### 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>
  4920. */
  4921. case 31: //M31 take time since the start of the SD print or an M109 command
  4922. {
  4923. stoptime=_millis();
  4924. char time[30];
  4925. unsigned long t=(stoptime-starttime)/1000;
  4926. int sec,min;
  4927. min=t/60;
  4928. sec=t%60;
  4929. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4930. SERIAL_ECHO_START;
  4931. SERIAL_ECHOLN(time);
  4932. lcd_setstatus(time);
  4933. autotempShutdown();
  4934. }
  4935. break;
  4936. /*!
  4937. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4938. #### Usage
  4939. M42 [ P | S ]
  4940. #### Parameters
  4941. - `P` - Pin number.
  4942. - `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.
  4943. */
  4944. case 42:
  4945. if (code_seen('S'))
  4946. {
  4947. uint8_t pin_status = code_value_uint8();
  4948. int8_t pin_number = LED_PIN;
  4949. if (code_seen('P'))
  4950. pin_number = code_value_uint8();
  4951. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4952. {
  4953. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4954. {
  4955. pin_number = -1;
  4956. break;
  4957. }
  4958. }
  4959. #if defined(FAN_PIN) && FAN_PIN > -1
  4960. if (pin_number == FAN_PIN)
  4961. fanSpeed = pin_status;
  4962. #endif
  4963. if (pin_number > -1)
  4964. {
  4965. pinMode(pin_number, OUTPUT);
  4966. digitalWrite(pin_number, pin_status);
  4967. analogWrite(pin_number, pin_status);
  4968. }
  4969. }
  4970. break;
  4971. /*!
  4972. ### 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>
  4973. */
  4974. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4975. // Reset the baby step value and the baby step applied flag.
  4976. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4977. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4978. // Reset the skew and offset in both RAM and EEPROM.
  4979. reset_bed_offset_and_skew();
  4980. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4981. // the planner will not perform any adjustments in the XY plane.
  4982. // Wait for the motors to stop and update the current position with the absolute values.
  4983. world2machine_revert_to_uncorrected();
  4984. break;
  4985. /*!
  4986. ### 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>
  4987. #### Usage
  4988. M45 [ V ]
  4989. #### Parameters
  4990. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4991. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4992. */
  4993. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4994. {
  4995. int8_t verbosity_level = 0;
  4996. bool only_Z = code_seen('Z');
  4997. #ifdef SUPPORT_VERBOSITY
  4998. if (code_seen('V'))
  4999. {
  5000. // Just 'V' without a number counts as V1.
  5001. char c = strchr_pointer[1];
  5002. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5003. }
  5004. #endif //SUPPORT_VERBOSITY
  5005. gcode_M45(only_Z, verbosity_level);
  5006. }
  5007. break;
  5008. /*!
  5009. ### 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>
  5010. */
  5011. case 46:
  5012. {
  5013. // M46: Prusa3D: Show the assigned IP address.
  5014. if (card.ToshibaFlashAir_isEnabled()) {
  5015. uint8_t ip[4];
  5016. if (card.ToshibaFlashAir_GetIP(ip)) {
  5017. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  5018. SERIAL_PROTOCOL(uint8_t(ip[0]));
  5019. SERIAL_PROTOCOL('.');
  5020. SERIAL_PROTOCOL(uint8_t(ip[1]));
  5021. SERIAL_PROTOCOL('.');
  5022. SERIAL_PROTOCOL(uint8_t(ip[2]));
  5023. SERIAL_PROTOCOL('.');
  5024. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  5025. } else {
  5026. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  5027. }
  5028. } else {
  5029. SERIAL_PROTOCOLLNPGM("n/a");
  5030. }
  5031. break;
  5032. }
  5033. /*!
  5034. ### 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>
  5035. */
  5036. case 47:
  5037. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5038. lcd_diag_show_end_stops();
  5039. KEEPALIVE_STATE(IN_HANDLER);
  5040. break;
  5041. #if 0
  5042. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5043. {
  5044. // Disable the default update procedure of the display. We will do a modal dialog.
  5045. lcd_update_enable(false);
  5046. // Let the planner use the uncorrected coordinates.
  5047. mbl.reset();
  5048. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5049. // the planner will not perform any adjustments in the XY plane.
  5050. // Wait for the motors to stop and update the current position with the absolute values.
  5051. world2machine_revert_to_uncorrected();
  5052. // Move the print head close to the bed.
  5053. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5054. 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);
  5055. st_synchronize();
  5056. // Home in the XY plane.
  5057. set_destination_to_current();
  5058. int l_feedmultiply = setup_for_endstop_move();
  5059. home_xy();
  5060. int8_t verbosity_level = 0;
  5061. if (code_seen('V')) {
  5062. // Just 'V' without a number counts as V1.
  5063. char c = strchr_pointer[1];
  5064. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5065. }
  5066. bool success = scan_bed_induction_points(verbosity_level);
  5067. clean_up_after_endstop_move(l_feedmultiply);
  5068. // Print head up.
  5069. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5070. 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);
  5071. st_synchronize();
  5072. lcd_update_enable(true);
  5073. break;
  5074. }
  5075. #endif
  5076. #ifdef ENABLE_AUTO_BED_LEVELING
  5077. #ifdef Z_PROBE_REPEATABILITY_TEST
  5078. /*!
  5079. ### 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>
  5080. 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.
  5081. 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.
  5082. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5083. #### Usage
  5084. M48 [ n | X | Y | V | L ]
  5085. #### Parameters
  5086. - `n` - Number of samples. Valid values 4-50
  5087. - `X` - X position for samples
  5088. - `Y` - Y position for samples
  5089. - `V` - Verbose level. Valid values 1-4
  5090. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5091. */
  5092. case 48: // M48 Z-Probe repeatability
  5093. {
  5094. #if Z_MIN_PIN == -1
  5095. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5096. #endif
  5097. double sum=0.0;
  5098. double mean=0.0;
  5099. double sigma=0.0;
  5100. double sample_set[50];
  5101. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5102. double X_current, Y_current, Z_current;
  5103. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5104. if (code_seen('V') || code_seen('v')) {
  5105. verbose_level = code_value();
  5106. if (verbose_level<0 || verbose_level>4 ) {
  5107. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5108. goto Sigma_Exit;
  5109. }
  5110. }
  5111. if (verbose_level > 0) {
  5112. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5113. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5114. }
  5115. if (code_seen('n')) {
  5116. n_samples = code_value();
  5117. if (n_samples<4 || n_samples>50 ) {
  5118. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5119. goto Sigma_Exit;
  5120. }
  5121. }
  5122. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5123. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5124. Z_current = st_get_position_mm(Z_AXIS);
  5125. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5126. ext_position = st_get_position_mm(E_AXIS);
  5127. if (code_seen('X') || code_seen('x') ) {
  5128. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5129. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5130. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5131. goto Sigma_Exit;
  5132. }
  5133. }
  5134. if (code_seen('Y') || code_seen('y') ) {
  5135. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5136. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5137. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5138. goto Sigma_Exit;
  5139. }
  5140. }
  5141. if (code_seen('L') || code_seen('l') ) {
  5142. n_legs = code_value();
  5143. if ( n_legs==1 )
  5144. n_legs = 2;
  5145. if ( n_legs<0 || n_legs>15 ) {
  5146. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5147. goto Sigma_Exit;
  5148. }
  5149. }
  5150. //
  5151. // Do all the preliminary setup work. First raise the probe.
  5152. //
  5153. st_synchronize();
  5154. plan_bed_level_matrix.set_to_identity();
  5155. plan_buffer_line( X_current, Y_current, Z_start_location,
  5156. ext_position,
  5157. homing_feedrate[Z_AXIS]/60,
  5158. active_extruder);
  5159. st_synchronize();
  5160. //
  5161. // Now get everything to the specified probe point So we can safely do a probe to
  5162. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5163. // use that as a starting point for each probe.
  5164. //
  5165. if (verbose_level > 2)
  5166. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5167. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5168. ext_position,
  5169. homing_feedrate[X_AXIS]/60,
  5170. active_extruder);
  5171. st_synchronize();
  5172. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5173. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5174. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5175. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5176. //
  5177. // OK, do the inital probe to get us close to the bed.
  5178. // Then retrace the right amount and use that in subsequent probes
  5179. //
  5180. int l_feedmultiply = setup_for_endstop_move();
  5181. run_z_probe();
  5182. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5183. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5184. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5185. ext_position,
  5186. homing_feedrate[X_AXIS]/60,
  5187. active_extruder);
  5188. st_synchronize();
  5189. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5190. for( n=0; n<n_samples; n++) {
  5191. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5192. if ( n_legs) {
  5193. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5194. int rotational_direction, l;
  5195. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5196. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5197. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5198. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5199. //SERIAL_ECHOPAIR(" theta: ",theta);
  5200. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5201. //SERIAL_PROTOCOLLNPGM("");
  5202. for( l=0; l<n_legs-1; l++) {
  5203. if (rotational_direction==1)
  5204. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5205. else
  5206. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5207. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5208. if ( radius<0.0 )
  5209. radius = -radius;
  5210. X_current = X_probe_location + cos(theta) * radius;
  5211. Y_current = Y_probe_location + sin(theta) * radius;
  5212. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5213. X_current = X_MIN_POS;
  5214. if ( X_current>X_MAX_POS)
  5215. X_current = X_MAX_POS;
  5216. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5217. Y_current = Y_MIN_POS;
  5218. if ( Y_current>Y_MAX_POS)
  5219. Y_current = Y_MAX_POS;
  5220. if (verbose_level>3 ) {
  5221. SERIAL_ECHOPAIR("x: ", X_current);
  5222. SERIAL_ECHOPAIR("y: ", Y_current);
  5223. SERIAL_PROTOCOLLNPGM("");
  5224. }
  5225. do_blocking_move_to( X_current, Y_current, Z_current );
  5226. }
  5227. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5228. }
  5229. int l_feedmultiply = setup_for_endstop_move();
  5230. run_z_probe();
  5231. sample_set[n] = current_position[Z_AXIS];
  5232. //
  5233. // Get the current mean for the data points we have so far
  5234. //
  5235. sum=0.0;
  5236. for( j=0; j<=n; j++) {
  5237. sum = sum + sample_set[j];
  5238. }
  5239. mean = sum / (double (n+1));
  5240. //
  5241. // Now, use that mean to calculate the standard deviation for the
  5242. // data points we have so far
  5243. //
  5244. sum=0.0;
  5245. for( j=0; j<=n; j++) {
  5246. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5247. }
  5248. sigma = sqrt( sum / (double (n+1)) );
  5249. if (verbose_level > 1) {
  5250. SERIAL_PROTOCOL(n+1);
  5251. SERIAL_PROTOCOL(" of ");
  5252. SERIAL_PROTOCOL(n_samples);
  5253. SERIAL_PROTOCOLPGM(" z: ");
  5254. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5255. }
  5256. if (verbose_level > 2) {
  5257. SERIAL_PROTOCOL(" mean: ");
  5258. SERIAL_PROTOCOL_F(mean,6);
  5259. SERIAL_PROTOCOL(" sigma: ");
  5260. SERIAL_PROTOCOL_F(sigma,6);
  5261. }
  5262. if (verbose_level > 0)
  5263. SERIAL_PROTOCOLPGM("\n");
  5264. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5265. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5266. st_synchronize();
  5267. }
  5268. _delay(1000);
  5269. clean_up_after_endstop_move(l_feedmultiply);
  5270. // enable_endstops(true);
  5271. if (verbose_level > 0) {
  5272. SERIAL_PROTOCOLPGM("Mean: ");
  5273. SERIAL_PROTOCOL_F(mean, 6);
  5274. SERIAL_PROTOCOLPGM("\n");
  5275. }
  5276. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5277. SERIAL_PROTOCOL_F(sigma, 6);
  5278. SERIAL_PROTOCOLPGM("\n\n");
  5279. Sigma_Exit:
  5280. break;
  5281. }
  5282. #endif // Z_PROBE_REPEATABILITY_TEST
  5283. #endif // ENABLE_AUTO_BED_LEVELING
  5284. /*!
  5285. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5286. #### Usage
  5287. M73 [ P | R | Q | S | C | D ]
  5288. #### Parameters
  5289. - `P` - Percent in normal mode
  5290. - `R` - Time remaining in normal mode
  5291. - `Q` - Percent in silent mode
  5292. - `S` - Time in silent mode
  5293. - `C` - Time to change/pause/user interaction in normal mode
  5294. - `D` - Time to change/pause/user interaction in silent mode
  5295. */
  5296. case 73: //M73 show percent done, time remaining and time to change/pause
  5297. {
  5298. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5299. if(code_seen('R')) print_time_remaining_normal = code_value();
  5300. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5301. if(code_seen('S')) print_time_remaining_silent = code_value();
  5302. if(code_seen('C')){
  5303. float print_time_to_change_normal_f = code_value_float();
  5304. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5305. }
  5306. if(code_seen('D')){
  5307. float print_time_to_change_silent_f = code_value_float();
  5308. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5309. }
  5310. {
  5311. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5312. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5313. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5314. }
  5315. break;
  5316. }
  5317. /*!
  5318. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5319. #### Usage
  5320. M104 [ S ]
  5321. #### Parameters
  5322. - `S` - Target temperature
  5323. */
  5324. case 104: // M104
  5325. {
  5326. uint8_t extruder;
  5327. if(setTargetedHotend(104,extruder)){
  5328. break;
  5329. }
  5330. if (code_seen('S'))
  5331. {
  5332. setTargetHotendSafe(code_value(), extruder);
  5333. }
  5334. break;
  5335. }
  5336. /*!
  5337. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5338. It is processed much earlier as to bypass the cmdqueue.
  5339. */
  5340. case 112:
  5341. kill(MSG_M112_KILL, 3);
  5342. break;
  5343. /*!
  5344. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5345. #### Usage
  5346. M140 [ S ]
  5347. #### Parameters
  5348. - `S` - Target temperature
  5349. */
  5350. case 140:
  5351. if (code_seen('S')) setTargetBed(code_value());
  5352. break;
  5353. /*!
  5354. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5355. Prints temperatures:
  5356. - `T:` - Hotend (actual / target)
  5357. - `B:` - Bed (actual / target)
  5358. - `Tx:` - x Tool (actual / target)
  5359. - `@:` - Hotend power
  5360. - `B@:` - Bed power
  5361. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5362. - `A:` - Ambient actual (only MK3/s)
  5363. _Example:_
  5364. 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
  5365. */
  5366. case 105:
  5367. {
  5368. uint8_t extruder;
  5369. if(setTargetedHotend(105, extruder)){
  5370. break;
  5371. }
  5372. SERIAL_PROTOCOLPGM("ok ");
  5373. gcode_M105(extruder);
  5374. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5375. cmdbuffer_front_already_processed = true;
  5376. break;
  5377. }
  5378. #if defined(AUTO_REPORT)
  5379. /*!
  5380. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5381. #### Usage
  5382. M155 [ S ] [ C ]
  5383. #### Parameters
  5384. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5385. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5386. bit 0 = Auto-report temperatures
  5387. bit 1 = Auto-report fans
  5388. bit 2 = Auto-report position
  5389. bit 3 = free
  5390. bit 4 = free
  5391. bit 5 = free
  5392. bit 6 = free
  5393. bit 7 = free
  5394. */
  5395. case 155:
  5396. {
  5397. if (code_seen('S')){
  5398. autoReportFeatures.SetPeriod( code_value_uint8() );
  5399. }
  5400. if (code_seen('C')){
  5401. autoReportFeatures.SetMask(code_value_uint8());
  5402. } else{
  5403. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5404. }
  5405. }
  5406. break;
  5407. #endif //AUTO_REPORT
  5408. /*!
  5409. ### 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>
  5410. #### Usage
  5411. M104 [ B | R | S ]
  5412. #### Parameters (not mandatory)
  5413. - `S` - Set extruder temperature
  5414. - `R` - Set extruder temperature
  5415. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5416. Parameters S and R are treated identically.
  5417. Command always waits for both cool down and heat up.
  5418. If no parameters are supplied waits for previously set extruder temperature.
  5419. */
  5420. case 109:
  5421. {
  5422. uint8_t extruder;
  5423. if(setTargetedHotend(109, extruder)){
  5424. break;
  5425. }
  5426. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5427. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5428. prusa_statistics(1);
  5429. #ifdef AUTOTEMP
  5430. autotemp_enabled=false;
  5431. #endif
  5432. if (code_seen('S')) {
  5433. setTargetHotendSafe(code_value(), extruder);
  5434. } else if (code_seen('R')) {
  5435. setTargetHotendSafe(code_value(), extruder);
  5436. }
  5437. #ifdef AUTOTEMP
  5438. if (code_seen('S')) autotemp_min=code_value();
  5439. if (code_seen('B')) autotemp_max=code_value();
  5440. if (code_seen('F'))
  5441. {
  5442. autotemp_factor=code_value();
  5443. autotemp_enabled=true;
  5444. }
  5445. #endif
  5446. codenum = _millis();
  5447. /* See if we are heating up or cooling down */
  5448. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5449. cancel_heatup = false;
  5450. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5451. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5452. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5453. prusa_statistics(2);
  5454. //starttime=_millis();
  5455. previous_millis_cmd.start();
  5456. }
  5457. break;
  5458. /*!
  5459. ### 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>
  5460. #### Usage
  5461. M190 [ R | S ]
  5462. #### Parameters (not mandatory)
  5463. - `S` - Set extruder temperature and wait for heating
  5464. - `R` - Set extruder temperature and wait for heating or cooling
  5465. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5466. */
  5467. case 190:
  5468. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5469. {
  5470. bool CooldownNoWait = false;
  5471. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5472. heating_status = HeatingStatus::BED_HEATING;
  5473. prusa_statistics(1);
  5474. if (code_seen('S'))
  5475. {
  5476. setTargetBed(code_value());
  5477. CooldownNoWait = true;
  5478. }
  5479. else if (code_seen('R'))
  5480. {
  5481. setTargetBed(code_value());
  5482. }
  5483. codenum = _millis();
  5484. cancel_heatup = false;
  5485. target_direction = isHeatingBed(); // true if heating, false if cooling
  5486. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5487. {
  5488. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5489. {
  5490. if (!farm_mode) {
  5491. float tt = degHotend(active_extruder);
  5492. SERIAL_PROTOCOLPGM("T:");
  5493. SERIAL_PROTOCOL(tt);
  5494. SERIAL_PROTOCOLPGM(" E:");
  5495. SERIAL_PROTOCOL((int)active_extruder);
  5496. SERIAL_PROTOCOLPGM(" B:");
  5497. SERIAL_PROTOCOL_F(degBed(), 1);
  5498. SERIAL_PROTOCOLLN();
  5499. }
  5500. codenum = _millis();
  5501. }
  5502. manage_heater();
  5503. manage_inactivity();
  5504. lcd_update(0);
  5505. }
  5506. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5507. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5508. previous_millis_cmd.start();
  5509. }
  5510. #endif
  5511. break;
  5512. #if defined(FAN_PIN) && FAN_PIN > -1
  5513. /*!
  5514. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5515. #### Usage
  5516. M106 [ S ]
  5517. #### Parameters
  5518. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5519. */
  5520. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5521. if (code_seen('S')){
  5522. fanSpeed = code_value_uint8();
  5523. }
  5524. else {
  5525. fanSpeed = 255;
  5526. }
  5527. break;
  5528. /*!
  5529. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5530. */
  5531. case 107:
  5532. fanSpeed = 0;
  5533. break;
  5534. #endif //FAN_PIN
  5535. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5536. /*!
  5537. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5538. Only works if the firmware is compiled with PS_ON_PIN defined.
  5539. */
  5540. case 80:
  5541. SET_OUTPUT(PS_ON_PIN); //GND
  5542. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5543. // If you have a switch on suicide pin, this is useful
  5544. // if you want to start another print with suicide feature after
  5545. // a print without suicide...
  5546. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5547. SET_OUTPUT(SUICIDE_PIN);
  5548. WRITE(SUICIDE_PIN, HIGH);
  5549. #endif
  5550. powersupply = true;
  5551. LCD_MESSAGERPGM(MSG_WELCOME);
  5552. lcd_update(0);
  5553. break;
  5554. /*!
  5555. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5556. Only works if the firmware is compiled with PS_ON_PIN defined.
  5557. */
  5558. case 81:
  5559. disable_heater();
  5560. st_synchronize();
  5561. disable_e0();
  5562. disable_e1();
  5563. disable_e2();
  5564. finishAndDisableSteppers();
  5565. fanSpeed = 0;
  5566. _delay(1000); // Wait a little before to switch off
  5567. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5568. st_synchronize();
  5569. suicide();
  5570. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5571. SET_OUTPUT(PS_ON_PIN);
  5572. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5573. #endif
  5574. powersupply = false;
  5575. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5576. lcd_update(0);
  5577. break;
  5578. #endif
  5579. /*!
  5580. ### 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>
  5581. Makes the extruder interpret extrusion as absolute positions.
  5582. */
  5583. case 82:
  5584. axis_relative_modes &= ~E_AXIS_MASK;
  5585. break;
  5586. /*!
  5587. ### 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>
  5588. Makes the extruder interpret extrusion values as relative positions.
  5589. */
  5590. case 83:
  5591. axis_relative_modes |= E_AXIS_MASK;
  5592. break;
  5593. /*!
  5594. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5595. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5596. This command can be used without any additional parameters. In that case all steppers are disabled.
  5597. 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.
  5598. M84 [ S | X | Y | Z | E ]
  5599. - `S` - Seconds
  5600. - `X` - X axis
  5601. - `Y` - Y axis
  5602. - `Z` - Z axis
  5603. - `E` - Extruder
  5604. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5605. Equal to M84 (compatibility)
  5606. */
  5607. case 18: //compatibility
  5608. case 84: // M84
  5609. if(code_seen('S')){
  5610. stepper_inactive_time = code_value() * 1000;
  5611. }
  5612. else
  5613. {
  5614. 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])));
  5615. if(all_axis)
  5616. {
  5617. st_synchronize();
  5618. disable_e0();
  5619. disable_e1();
  5620. disable_e2();
  5621. finishAndDisableSteppers();
  5622. }
  5623. else
  5624. {
  5625. st_synchronize();
  5626. if (code_seen('X')) disable_x();
  5627. if (code_seen('Y')) disable_y();
  5628. if (code_seen('Z')) disable_z();
  5629. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5630. if (code_seen('E')) {
  5631. disable_e0();
  5632. disable_e1();
  5633. disable_e2();
  5634. }
  5635. #endif
  5636. }
  5637. }
  5638. break;
  5639. /*!
  5640. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5641. #### Usage
  5642. M85 [ S ]
  5643. #### Parameters
  5644. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5645. */
  5646. case 85: // M85
  5647. if(code_seen('S')) {
  5648. max_inactive_time = code_value() * 1000;
  5649. }
  5650. break;
  5651. #ifdef SAFETYTIMER
  5652. /*!
  5653. ### 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>
  5654. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5655. #### Usage
  5656. M86 [ S ]
  5657. #### Parameters
  5658. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5659. */
  5660. case 86:
  5661. if (code_seen('S')) {
  5662. safetytimer_inactive_time = code_value() * 1000;
  5663. safetyTimer.start();
  5664. }
  5665. break;
  5666. #endif
  5667. /*!
  5668. ### 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>
  5669. 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)
  5670. #### Usage
  5671. M92 [ X | Y | Z | E ]
  5672. #### Parameters
  5673. - `X` - Steps per unit for the X drive
  5674. - `Y` - Steps per unit for the Y drive
  5675. - `Z` - Steps per unit for the Z drive
  5676. - `E` - Steps per unit for the extruder drive
  5677. */
  5678. case 92:
  5679. for(int8_t i=0; i < NUM_AXIS; i++)
  5680. {
  5681. if(code_seen(axis_codes[i]))
  5682. {
  5683. if(i == E_AXIS) { // E
  5684. float value = code_value();
  5685. if(value < 20.0) {
  5686. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5687. cs.max_jerk[E_AXIS] *= factor;
  5688. max_feedrate[i] *= factor;
  5689. axis_steps_per_sqr_second[i] *= factor;
  5690. }
  5691. cs.axis_steps_per_unit[i] = value;
  5692. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5693. fsensor.init();
  5694. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5695. }
  5696. else {
  5697. cs.axis_steps_per_unit[i] = code_value();
  5698. }
  5699. }
  5700. }
  5701. reset_acceleration_rates();
  5702. break;
  5703. /*!
  5704. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5705. Sets the line number in G-code
  5706. #### Usage
  5707. M110 [ N ]
  5708. #### Parameters
  5709. - `N` - Line number
  5710. */
  5711. case 110:
  5712. if (code_seen('N'))
  5713. gcode_LastN = code_value_long();
  5714. break;
  5715. /*!
  5716. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5717. 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).
  5718. #### Usage
  5719. M113 [ S ]
  5720. #### Parameters
  5721. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5722. */
  5723. case 113:
  5724. if (code_seen('S')) {
  5725. host_keepalive_interval = code_value_uint8();
  5726. // NOMORE(host_keepalive_interval, 60);
  5727. }
  5728. else {
  5729. SERIAL_ECHO_START;
  5730. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5731. SERIAL_PROTOCOLLN();
  5732. }
  5733. break;
  5734. /*!
  5735. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5736. Print the firmware info and capabilities
  5737. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5738. `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.
  5739. _Examples:_
  5740. `M115` results:
  5741. `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`
  5742. `M115 V` results:
  5743. `3.8.1`
  5744. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5745. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5746. #### Usage
  5747. M115 [ V | U ]
  5748. #### Parameters
  5749. - V - Report current installed firmware version
  5750. - U - Firmware version provided by G-code to be compared to current one.
  5751. */
  5752. case 115: // M115
  5753. if (code_seen('V')) {
  5754. // Report the Prusa version number.
  5755. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5756. } else if (code_seen('U')) {
  5757. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5758. // pause the print for 30s and ask the user to upgrade the firmware.
  5759. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5760. } else {
  5761. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5762. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5763. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5764. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5765. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5766. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5767. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5768. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5769. SERIAL_ECHOPGM(" UUID:");
  5770. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5771. #ifdef EXTENDED_CAPABILITIES_REPORT
  5772. extended_capabilities_report();
  5773. #endif //EXTENDED_CAPABILITIES_REPORT
  5774. }
  5775. break;
  5776. /*!
  5777. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5778. */
  5779. case 114:
  5780. gcode_M114();
  5781. break;
  5782. /*
  5783. M117 moved up to get the high priority
  5784. case 117: // M117 display message
  5785. starpos = (strchr(strchr_pointer + 5,'*'));
  5786. if(starpos!=NULL)
  5787. *(starpos)='\0';
  5788. lcd_setstatus(strchr_pointer + 5);
  5789. break;*/
  5790. #ifdef M120_M121_ENABLED
  5791. /*!
  5792. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5793. */
  5794. case 120:
  5795. enable_endstops(true) ;
  5796. break;
  5797. /*!
  5798. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5799. */
  5800. case 121:
  5801. enable_endstops(false) ;
  5802. break;
  5803. #endif //M120_M121_ENABLED
  5804. /*!
  5805. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5806. 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.
  5807. */
  5808. case 119:
  5809. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5810. SERIAL_PROTOCOLLN();
  5811. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5812. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5813. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5814. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5815. }else{
  5816. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5817. }
  5818. SERIAL_PROTOCOLLN();
  5819. #endif
  5820. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5821. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5822. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5823. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5824. }else{
  5825. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5826. }
  5827. SERIAL_PROTOCOLLN();
  5828. #endif
  5829. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5830. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5831. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5832. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5833. }else{
  5834. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5835. }
  5836. SERIAL_PROTOCOLLN();
  5837. #endif
  5838. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5839. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5840. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5841. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5842. }else{
  5843. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5844. }
  5845. SERIAL_PROTOCOLLN();
  5846. #endif
  5847. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5848. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5849. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5850. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5851. }else{
  5852. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5853. }
  5854. SERIAL_PROTOCOLLN();
  5855. #endif
  5856. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5857. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5858. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5859. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5860. }else{
  5861. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5862. }
  5863. SERIAL_PROTOCOLLN();
  5864. #endif
  5865. break;
  5866. //!@todo update for all axes, use for loop
  5867. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5868. /*!
  5869. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5870. This command is used to report fan speeds and fan pwm values.
  5871. #### Usage
  5872. M123
  5873. - E0: - Hotend fan speed in RPM
  5874. - PRN1: - Part cooling fans speed in RPM
  5875. - E0@: - Hotend fan PWM value
  5876. - PRN1@: -Part cooling fan PWM value
  5877. _Example:_
  5878. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5879. */
  5880. case 123:
  5881. gcode_M123();
  5882. break;
  5883. #endif //FANCHECK and TACH_0 and TACH_1
  5884. #ifdef BLINKM
  5885. /*!
  5886. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5887. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5888. #### Usage
  5889. M150 [ R | U | B ]
  5890. #### Parameters
  5891. - `R` - Red color value
  5892. - `U` - Green color value. It is NOT `G`!
  5893. - `B` - Blue color value
  5894. */
  5895. case 150:
  5896. {
  5897. byte red;
  5898. byte grn;
  5899. byte blu;
  5900. if(code_seen('R')) red = code_value();
  5901. if(code_seen('U')) grn = code_value();
  5902. if(code_seen('B')) blu = code_value();
  5903. SendColors(red,grn,blu);
  5904. }
  5905. break;
  5906. #endif //BLINKM
  5907. /*!
  5908. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5909. #### Usage
  5910. M200 [ D | T ]
  5911. #### Parameters
  5912. - `D` - Diameter in mm
  5913. - `T` - Number of extruder (MMUs)
  5914. */
  5915. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5916. {
  5917. uint8_t extruder = active_extruder;
  5918. if(code_seen('T')) {
  5919. extruder = code_value_uint8();
  5920. if(extruder >= EXTRUDERS) {
  5921. SERIAL_ECHO_START;
  5922. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5923. break;
  5924. }
  5925. }
  5926. if(code_seen('D')) {
  5927. float diameter = code_value();
  5928. if (diameter == 0.0) {
  5929. // setting any extruder filament size disables volumetric on the assumption that
  5930. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5931. // for all extruders
  5932. cs.volumetric_enabled = false;
  5933. } else {
  5934. cs.filament_size[extruder] = code_value();
  5935. // make sure all extruders have some sane value for the filament size
  5936. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5937. #if EXTRUDERS > 1
  5938. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5939. #if EXTRUDERS > 2
  5940. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5941. #endif
  5942. #endif
  5943. cs.volumetric_enabled = true;
  5944. }
  5945. } else {
  5946. //reserved for setting filament diameter via UFID or filament measuring device
  5947. break;
  5948. }
  5949. calculate_extruder_multipliers();
  5950. }
  5951. break;
  5952. /*!
  5953. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5954. For each axis individually.
  5955. ##### Usage
  5956. M201 [ X | Y | Z | E ]
  5957. ##### Parameters
  5958. - `X` - Acceleration for X axis in units/s^2
  5959. - `Y` - Acceleration for Y axis in units/s^2
  5960. - `Z` - Acceleration for Z axis in units/s^2
  5961. - `E` - Acceleration for the active or specified extruder in units/s^2
  5962. */
  5963. case 201:
  5964. for (int8_t i = 0; i < NUM_AXIS; i++)
  5965. {
  5966. if (code_seen(axis_codes[i]))
  5967. {
  5968. unsigned long val = code_value();
  5969. #ifdef TMC2130
  5970. unsigned long val_silent = val;
  5971. if ((i == X_AXIS) || (i == Y_AXIS))
  5972. {
  5973. if (val > NORMAL_MAX_ACCEL_XY)
  5974. val = NORMAL_MAX_ACCEL_XY;
  5975. if (val_silent > SILENT_MAX_ACCEL_XY)
  5976. val_silent = SILENT_MAX_ACCEL_XY;
  5977. }
  5978. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5979. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5980. #else //TMC2130
  5981. max_acceleration_units_per_sq_second[i] = val;
  5982. #endif //TMC2130
  5983. }
  5984. }
  5985. // 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)
  5986. reset_acceleration_rates();
  5987. break;
  5988. #if 0 // Not used for Sprinter/grbl gen6
  5989. case 202: // M202
  5990. for(int8_t i=0; i < NUM_AXIS; i++) {
  5991. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5992. }
  5993. break;
  5994. #endif
  5995. /*!
  5996. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5997. For each axis individually.
  5998. ##### Usage
  5999. M203 [ X | Y | Z | E ]
  6000. ##### Parameters
  6001. - `X` - Maximum feedrate for X axis
  6002. - `Y` - Maximum feedrate for Y axis
  6003. - `Z` - Maximum feedrate for Z axis
  6004. - `E` - Maximum feedrate for extruder drives
  6005. */
  6006. case 203: // M203 max feedrate mm/sec
  6007. for (uint8_t i = 0; i < NUM_AXIS; i++)
  6008. {
  6009. if (code_seen(axis_codes[i]))
  6010. {
  6011. float val = code_value();
  6012. #ifdef TMC2130
  6013. float val_silent = val;
  6014. if ((i == X_AXIS) || (i == Y_AXIS))
  6015. {
  6016. if (val > NORMAL_MAX_FEEDRATE_XY)
  6017. val = NORMAL_MAX_FEEDRATE_XY;
  6018. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  6019. val_silent = SILENT_MAX_FEEDRATE_XY;
  6020. }
  6021. cs.max_feedrate_normal[i] = val;
  6022. cs.max_feedrate_silent[i] = val_silent;
  6023. #else //TMC2130
  6024. max_feedrate[i] = val;
  6025. #endif //TMC2130
  6026. }
  6027. }
  6028. break;
  6029. /*!
  6030. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  6031. #### Old format:
  6032. ##### Usage
  6033. M204 [ S | T ]
  6034. ##### Parameters
  6035. - `S` - normal moves
  6036. - `T` - filmanent only moves
  6037. #### New format:
  6038. ##### Usage
  6039. M204 [ P | R | T ]
  6040. ##### Parameters
  6041. - `P` - printing moves
  6042. - `R` - filmanent only moves
  6043. - `T` - travel moves (as of now T is ignored)
  6044. */
  6045. case 204:
  6046. {
  6047. if(code_seen('S')) {
  6048. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6049. // and it is also generated by Slic3r to control acceleration per extrusion type
  6050. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6051. cs.acceleration = cs.travel_acceleration = code_value();
  6052. // Interpret the T value as retract acceleration in the old Marlin format.
  6053. if(code_seen('T'))
  6054. cs.retract_acceleration = code_value();
  6055. } else {
  6056. // New acceleration format, compatible with the upstream Marlin.
  6057. if(code_seen('P'))
  6058. cs.acceleration = code_value();
  6059. if(code_seen('R'))
  6060. cs.retract_acceleration = code_value();
  6061. if(code_seen('T'))
  6062. cs.travel_acceleration = code_value();
  6063. }
  6064. }
  6065. break;
  6066. /*!
  6067. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6068. Set some advanced settings related to movement.
  6069. #### Usage
  6070. M205 [ S | T | B | X | Y | Z | E ]
  6071. #### Parameters
  6072. - `S` - Minimum feedrate for print moves (unit/s)
  6073. - `T` - Minimum feedrate for travel moves (units/s)
  6074. - `B` - Minimum segment time (us)
  6075. - `X` - Maximum X jerk (units/s)
  6076. - `Y` - Maximum Y jerk (units/s)
  6077. - `Z` - Maximum Z jerk (units/s)
  6078. - `E` - Maximum E jerk (units/s)
  6079. */
  6080. case 205:
  6081. {
  6082. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6083. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6084. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6085. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6086. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6087. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6088. if(code_seen('E'))
  6089. {
  6090. float e = code_value();
  6091. #ifndef LA_NOCOMPAT
  6092. e = la10c_jerk(e);
  6093. #endif
  6094. cs.max_jerk[E_AXIS] = e;
  6095. }
  6096. }
  6097. break;
  6098. /*!
  6099. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6100. #### Usage
  6101. M206 [ X | Y | Z ]
  6102. #### Parameters
  6103. - `X` - X axis offset
  6104. - `Y` - Y axis offset
  6105. - `Z` - Z axis offset
  6106. */
  6107. case 206:
  6108. for(uint8_t i=0; i < 3; i++)
  6109. {
  6110. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6111. }
  6112. break;
  6113. #ifdef FWRETRACT
  6114. /*!
  6115. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6116. #### Usage
  6117. M207 [ S | F | Z ]
  6118. #### Parameters
  6119. - `S` - positive length to retract, in mm
  6120. - `F` - retraction feedrate, in mm/min
  6121. - `Z` - additional zlift/hop
  6122. */
  6123. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6124. {
  6125. if(code_seen('S'))
  6126. {
  6127. cs.retract_length = code_value() ;
  6128. }
  6129. if(code_seen('F'))
  6130. {
  6131. cs.retract_feedrate = code_value()/60 ;
  6132. }
  6133. if(code_seen('Z'))
  6134. {
  6135. cs.retract_zlift = code_value() ;
  6136. }
  6137. }break;
  6138. /*!
  6139. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6140. #### Usage
  6141. M208 [ S | F ]
  6142. #### Parameters
  6143. - `S` - positive length surplus to the M207 Snnn, in mm
  6144. - `F` - feedrate, in mm/sec
  6145. */
  6146. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6147. {
  6148. if(code_seen('S'))
  6149. {
  6150. cs.retract_recover_length = code_value() ;
  6151. }
  6152. if(code_seen('F'))
  6153. {
  6154. cs.retract_recover_feedrate = code_value()/60 ;
  6155. }
  6156. }break;
  6157. /*!
  6158. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6159. 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.
  6160. #### Usage
  6161. M209 [ S ]
  6162. #### Parameters
  6163. - `S` - 1=true or 0=false
  6164. */
  6165. 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.
  6166. {
  6167. if(code_seen('S'))
  6168. {
  6169. switch(code_value_uint8())
  6170. {
  6171. case 0:
  6172. {
  6173. cs.autoretract_enabled=false;
  6174. retracted[0]=false;
  6175. #if EXTRUDERS > 1
  6176. retracted[1]=false;
  6177. #endif
  6178. #if EXTRUDERS > 2
  6179. retracted[2]=false;
  6180. #endif
  6181. }break;
  6182. case 1:
  6183. {
  6184. cs.autoretract_enabled=true;
  6185. retracted[0]=false;
  6186. #if EXTRUDERS > 1
  6187. retracted[1]=false;
  6188. #endif
  6189. #if EXTRUDERS > 2
  6190. retracted[2]=false;
  6191. #endif
  6192. }break;
  6193. default:
  6194. SERIAL_ECHO_START;
  6195. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6196. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6197. SERIAL_ECHOLNPGM("\"(1)");
  6198. }
  6199. }
  6200. }break;
  6201. #endif // FWRETRACT
  6202. /*!
  6203. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6204. #### Usage
  6205. M214 [P] [S] [N] [R] [F]
  6206. #### Parameters
  6207. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6208. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6209. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6210. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6211. except when the results in segment lengths greater than or less than the minimum
  6212. and maximum segment length. Set to 0 to disable.
  6213. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6214. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6215. */
  6216. 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>
  6217. {
  6218. // Extract all possible parameters if they appear
  6219. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6220. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6221. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6222. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6223. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6224. // 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
  6225. if (p <=0 || s < 0 || p < s)
  6226. {
  6227. // Should we display some error here?
  6228. break;
  6229. }
  6230. cs.mm_per_arc_segment = p;
  6231. cs.min_mm_per_arc_segment = s;
  6232. cs.n_arc_correction = n;
  6233. cs.min_arc_segments = r;
  6234. cs.arc_segments_per_sec = f;
  6235. }break;
  6236. #if EXTRUDERS > 1
  6237. /*!
  6238. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6239. 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.
  6240. #### Usage
  6241. M218 [ X | Y ]
  6242. #### Parameters
  6243. - `X` - X offset
  6244. - `Y` - Y offset
  6245. */
  6246. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6247. {
  6248. uint8_t extruder;
  6249. if(setTargetedHotend(218, extruder)){
  6250. break;
  6251. }
  6252. if(code_seen('X'))
  6253. {
  6254. extruder_offset[X_AXIS][extruder] = code_value();
  6255. }
  6256. if(code_seen('Y'))
  6257. {
  6258. extruder_offset[Y_AXIS][extruder] = code_value();
  6259. }
  6260. SERIAL_ECHO_START;
  6261. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6262. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6263. {
  6264. SERIAL_ECHO(" ");
  6265. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6266. SERIAL_ECHO(",");
  6267. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6268. }
  6269. SERIAL_ECHOLN("");
  6270. }break;
  6271. #endif
  6272. /*!
  6273. ### 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>
  6274. #### Usage
  6275. M220 [ B | S | R ]
  6276. #### Parameters
  6277. - `B` - Backup current speed factor
  6278. - `S` - Speed factor override percentage (0..100 or higher)
  6279. - `R` - Restore previous speed factor
  6280. */
  6281. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6282. {
  6283. bool codesWereSeen = false;
  6284. if (code_seen('B')) //backup current speed factor
  6285. {
  6286. saved_feedmultiply_mm = feedmultiply;
  6287. codesWereSeen = true;
  6288. }
  6289. if (code_seen('S'))
  6290. {
  6291. feedmultiply = code_value_short();
  6292. codesWereSeen = true;
  6293. }
  6294. if (code_seen('R')) //restore previous feedmultiply
  6295. {
  6296. feedmultiply = saved_feedmultiply_mm;
  6297. codesWereSeen = true;
  6298. }
  6299. if (!codesWereSeen)
  6300. {
  6301. printf_P(PSTR("%i%%\n"), feedmultiply);
  6302. }
  6303. }
  6304. break;
  6305. /*!
  6306. ### 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>
  6307. #### Usage
  6308. M221 [ S | T ]
  6309. #### Parameters
  6310. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6311. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6312. */
  6313. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6314. {
  6315. if (code_seen('S'))
  6316. {
  6317. int tmp_code = code_value_short();
  6318. if (code_seen('T'))
  6319. {
  6320. uint8_t extruder;
  6321. if (setTargetedHotend(221, extruder))
  6322. break;
  6323. extruder_multiply[extruder] = tmp_code;
  6324. }
  6325. else
  6326. {
  6327. extrudemultiply = tmp_code ;
  6328. }
  6329. }
  6330. else
  6331. {
  6332. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6333. }
  6334. calculate_extruder_multipliers();
  6335. }
  6336. break;
  6337. /*!
  6338. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6339. Wait until the specified pin reaches the state required
  6340. #### Usage
  6341. M226 [ P | S ]
  6342. #### Parameters
  6343. - `P` - pin number
  6344. - `S` - pin state
  6345. */
  6346. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6347. {
  6348. if(code_seen('P')){
  6349. int pin_number = code_value_short(); // pin number
  6350. int pin_state = -1; // required pin state - default is inverted
  6351. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6352. if(pin_state >= -1 && pin_state <= 1){
  6353. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6354. {
  6355. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6356. {
  6357. pin_number = -1;
  6358. break;
  6359. }
  6360. }
  6361. if (pin_number > -1)
  6362. {
  6363. int target = LOW;
  6364. st_synchronize();
  6365. pinMode(pin_number, INPUT);
  6366. switch(pin_state){
  6367. case 1:
  6368. target = HIGH;
  6369. break;
  6370. case 0:
  6371. target = LOW;
  6372. break;
  6373. case -1:
  6374. target = !digitalRead(pin_number);
  6375. break;
  6376. }
  6377. while(digitalRead(pin_number) != target){
  6378. manage_heater();
  6379. manage_inactivity();
  6380. lcd_update(0);
  6381. }
  6382. }
  6383. }
  6384. }
  6385. }
  6386. break;
  6387. #if NUM_SERVOS > 0
  6388. /*!
  6389. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6390. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6391. #### Usage
  6392. M280 [ P | S ]
  6393. #### Parameters
  6394. - `P` - Servo index (id)
  6395. - `S` - Target position
  6396. */
  6397. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6398. {
  6399. int servo_index = -1;
  6400. int servo_position = 0;
  6401. if (code_seen('P'))
  6402. servo_index = code_value();
  6403. if (code_seen('S')) {
  6404. servo_position = code_value();
  6405. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6406. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6407. servos[servo_index].attach(0);
  6408. #endif
  6409. servos[servo_index].write(servo_position);
  6410. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6411. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6412. servos[servo_index].detach();
  6413. #endif
  6414. }
  6415. else {
  6416. SERIAL_ECHO_START;
  6417. SERIAL_ECHO("Servo ");
  6418. SERIAL_ECHO(servo_index);
  6419. SERIAL_ECHOLN(" out of range");
  6420. }
  6421. }
  6422. else if (servo_index >= 0) {
  6423. SERIAL_PROTOCOL(MSG_OK);
  6424. SERIAL_PROTOCOL(" Servo ");
  6425. SERIAL_PROTOCOL(servo_index);
  6426. SERIAL_PROTOCOL(": ");
  6427. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6428. }
  6429. }
  6430. break;
  6431. #endif // NUM_SERVOS > 0
  6432. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6433. /*!
  6434. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6435. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6436. #### Usage
  6437. M300 [ S | P ]
  6438. #### Parameters
  6439. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6440. - `P` - duration in milliseconds
  6441. */
  6442. case 300: // M300
  6443. {
  6444. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6445. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6446. #if BEEPER > 0
  6447. if (beepP > 0)
  6448. Sound_MakeCustom(beepP,beepS,false);
  6449. #endif
  6450. }
  6451. break;
  6452. #endif // M300
  6453. #ifdef PIDTEMP
  6454. /*!
  6455. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6456. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6457. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6458. #### Usage
  6459. M301 [ P | I | D ]
  6460. #### Parameters
  6461. - `P` - proportional (Kp)
  6462. - `I` - integral (Ki)
  6463. - `D` - derivative (Kd)
  6464. */
  6465. case 301:
  6466. {
  6467. if(code_seen('P')) cs.Kp = code_value();
  6468. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6469. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6470. updatePID();
  6471. SERIAL_PROTOCOLRPGM(MSG_OK);
  6472. SERIAL_PROTOCOLPGM(" p:");
  6473. SERIAL_PROTOCOL(cs.Kp);
  6474. SERIAL_PROTOCOLPGM(" i:");
  6475. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6476. SERIAL_PROTOCOLPGM(" d:");
  6477. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6478. SERIAL_PROTOCOLLN();
  6479. }
  6480. break;
  6481. #endif //PIDTEMP
  6482. #ifdef PIDTEMPBED
  6483. /*!
  6484. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6485. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6486. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6487. #### Usage
  6488. M304 [ P | I | D ]
  6489. #### Parameters
  6490. - `P` - proportional (Kp)
  6491. - `I` - integral (Ki)
  6492. - `D` - derivative (Kd)
  6493. */
  6494. case 304:
  6495. {
  6496. if(code_seen('P')) cs.bedKp = code_value();
  6497. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6498. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6499. updatePID();
  6500. SERIAL_PROTOCOLRPGM(MSG_OK);
  6501. SERIAL_PROTOCOLPGM(" p:");
  6502. SERIAL_PROTOCOL(cs.bedKp);
  6503. SERIAL_PROTOCOLPGM(" i:");
  6504. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6505. SERIAL_PROTOCOLPGM(" d:");
  6506. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6507. }
  6508. break;
  6509. #endif //PIDTEMP
  6510. /*!
  6511. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6512. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6513. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6514. */
  6515. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6516. {
  6517. #ifdef CHDK
  6518. SET_OUTPUT(CHDK);
  6519. WRITE(CHDK, HIGH);
  6520. chdkHigh = _millis();
  6521. chdkActive = true;
  6522. #else
  6523. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6524. const uint8_t NUM_PULSES=16;
  6525. const float PULSE_LENGTH=0.01524;
  6526. for(int i=0; i < NUM_PULSES; i++) {
  6527. WRITE(PHOTOGRAPH_PIN, HIGH);
  6528. _delay_ms(PULSE_LENGTH);
  6529. WRITE(PHOTOGRAPH_PIN, LOW);
  6530. _delay_ms(PULSE_LENGTH);
  6531. }
  6532. _delay(7.33);
  6533. for(int i=0; i < NUM_PULSES; i++) {
  6534. WRITE(PHOTOGRAPH_PIN, HIGH);
  6535. _delay_ms(PULSE_LENGTH);
  6536. WRITE(PHOTOGRAPH_PIN, LOW);
  6537. _delay_ms(PULSE_LENGTH);
  6538. }
  6539. #endif
  6540. #endif //chdk end if
  6541. }
  6542. break;
  6543. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6544. /*!
  6545. ### 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>
  6546. 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.
  6547. #### Usage
  6548. M302 [ S ]
  6549. #### Parameters
  6550. - `S` - Cold extrude minimum temperature
  6551. */
  6552. case 302:
  6553. {
  6554. int temp = 0;
  6555. if (code_seen('S')) temp=code_value_short();
  6556. set_extrude_min_temp(temp);
  6557. }
  6558. break;
  6559. #endif
  6560. /*!
  6561. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6562. 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.
  6563. #### Usage
  6564. M303 [ E | S | C ]
  6565. #### Parameters
  6566. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6567. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6568. - `C` - Cycles, default `5`
  6569. */
  6570. case 303:
  6571. {
  6572. float temp = 150.0;
  6573. int e = 0;
  6574. int c = 5;
  6575. if (code_seen('E')) e = code_value_short();
  6576. if (e < 0)
  6577. temp = 70;
  6578. if (code_seen('S')) temp = code_value();
  6579. if (code_seen('C')) c = code_value_short();
  6580. PID_autotune(temp, e, c);
  6581. }
  6582. break;
  6583. #ifdef TEMP_MODEL
  6584. /*!
  6585. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6586. #### Usage
  6587. M310 ; report values
  6588. M310 [ A ] [ F ] ; autotune
  6589. M310 [ S ] ; set 0=disable 1=enable
  6590. M310 [ I ] [ R ] ; set resistance at index
  6591. M310 [ P | C ] ; set power, capacitance
  6592. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6593. M310 [ T ] ; set ambient temperature correction
  6594. #### Parameters
  6595. - `I` - resistance index position (0-15)
  6596. - `R` - resistance value at index (K/W; requires `I`)
  6597. - `P` - power (W)
  6598. - `C` - capacitance (J/K)
  6599. - `S` - set 0=disable 1=enable
  6600. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6601. - `E` - error threshold (K/s; default in variant)
  6602. - `W` - warning threshold (K/s; default in variant)
  6603. - `T` - ambient temperature correction (K; default in variant)
  6604. - `A` - autotune C+R values
  6605. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6606. */
  6607. case 310:
  6608. {
  6609. // parse all parameters
  6610. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6611. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6612. if(code_seen('C')) C = code_value();
  6613. if(code_seen('P')) P = code_value();
  6614. if(code_seen('I')) I = code_value_short();
  6615. if(code_seen('R')) R = code_value();
  6616. if(code_seen('S')) S = code_value_short();
  6617. if(code_seen('B')) B = code_value_short();
  6618. if(code_seen('E')) E = code_value();
  6619. if(code_seen('W')) W = code_value();
  6620. if(code_seen('T')) T = code_value();
  6621. if(code_seen('A')) A = code_value_short();
  6622. if(code_seen('F')) F = code_value_short();
  6623. // report values if nothing has been requested
  6624. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6625. temp_model_report_settings();
  6626. break;
  6627. }
  6628. // update all parameters
  6629. if(B >= 0) temp_model_set_warn_beep(B);
  6630. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6631. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6632. // enable the model last, if requested
  6633. if(S >= 0) temp_model_set_enabled(S);
  6634. // run autotune
  6635. if(A >= 0) temp_model_autotune(A, F > 0);
  6636. }
  6637. break;
  6638. #endif
  6639. /*!
  6640. ### 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>
  6641. Finishes all current moves and and thus clears the buffer.
  6642. Equivalent to `G4` with no parameters.
  6643. */
  6644. case 400:
  6645. {
  6646. st_synchronize();
  6647. }
  6648. break;
  6649. /*!
  6650. ### 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>
  6651. Currently three different materials are needed (default, flex and PVA).
  6652. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6653. #### Usage
  6654. M403 [ E | F ]
  6655. #### Parameters
  6656. - `E` - Extruder number. 0-indexed.
  6657. - `F` - Filament type
  6658. */
  6659. case 403:
  6660. {
  6661. // currently three different materials are needed (default, flex and PVA)
  6662. // add storing this information for different load/unload profiles etc. in the future
  6663. if (MMU2::mmu2.Enabled())
  6664. {
  6665. uint8_t extruder = 255;
  6666. uint8_t filament = FILAMENT_UNDEFINED;
  6667. if(code_seen('E')) extruder = code_value_uint8();
  6668. if(code_seen('F')) filament = code_value_uint8();
  6669. MMU2::mmu2.set_filament_type(extruder, filament);
  6670. }
  6671. }
  6672. break;
  6673. /*!
  6674. ### 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>
  6675. Save current parameters to EEPROM.
  6676. */
  6677. case 500:
  6678. {
  6679. Config_StoreSettings();
  6680. }
  6681. break;
  6682. /*!
  6683. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6684. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6685. */
  6686. case 501:
  6687. {
  6688. Config_RetrieveSettings();
  6689. }
  6690. break;
  6691. /*!
  6692. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6693. 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.
  6694. */
  6695. case 502:
  6696. {
  6697. Config_ResetDefault();
  6698. }
  6699. break;
  6700. /*!
  6701. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6702. 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.
  6703. */
  6704. case 503:
  6705. {
  6706. Config_PrintSettings();
  6707. }
  6708. break;
  6709. /*!
  6710. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6711. Resets the language to English.
  6712. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6713. */
  6714. case 509:
  6715. {
  6716. lang_reset();
  6717. SERIAL_ECHO_START;
  6718. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6719. }
  6720. break;
  6721. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6722. /*!
  6723. ### 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>
  6724. 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`.
  6725. #### Usage
  6726. M540 [ S ]
  6727. #### Parameters
  6728. - `S` - disabled=0, enabled=1
  6729. */
  6730. case 540:
  6731. {
  6732. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6733. }
  6734. break;
  6735. #endif
  6736. #ifdef ENABLE_AUTO_BED_LEVELING
  6737. /*!
  6738. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6739. 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.
  6740. 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.)
  6741. #### Usage
  6742. M851 [ Z ]
  6743. #### Parameters
  6744. - `Z` - Z offset probe to nozzle.
  6745. */
  6746. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6747. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6748. {
  6749. float value;
  6750. if (code_seen('Z'))
  6751. {
  6752. value = code_value();
  6753. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6754. {
  6755. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6756. SERIAL_ECHO_START;
  6757. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6758. SERIAL_PROTOCOLLN();
  6759. }
  6760. else
  6761. {
  6762. SERIAL_ECHO_START;
  6763. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6764. SERIAL_ECHORPGM(MSG_Z_MIN);
  6765. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6766. SERIAL_ECHORPGM(MSG_Z_MAX);
  6767. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6768. SERIAL_PROTOCOLLN();
  6769. }
  6770. }
  6771. else
  6772. {
  6773. SERIAL_ECHO_START;
  6774. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6775. SERIAL_ECHO(-cs.zprobe_zoffset);
  6776. SERIAL_PROTOCOLLN();
  6777. }
  6778. break;
  6779. }
  6780. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6781. #endif // ENABLE_AUTO_BED_LEVELING
  6782. /*!
  6783. ### 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>
  6784. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6785. If P is not specified nothing happens.
  6786. 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.
  6787. #### Usage
  6788. M552 [ P<IP_address> ]
  6789. #### Parameters
  6790. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6791. */
  6792. case 552:
  6793. {
  6794. if (code_seen('P'))
  6795. {
  6796. uint8_t valCnt = 0;
  6797. IP_address = 0;
  6798. do
  6799. {
  6800. *strchr_pointer = '*';
  6801. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6802. valCnt++;
  6803. } while ((valCnt < 4) && code_seen('.'));
  6804. if (valCnt != 4)
  6805. IP_address = 0;
  6806. }
  6807. } break;
  6808. #ifdef FILAMENTCHANGEENABLE
  6809. /*!
  6810. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6811. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6812. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6813. #### Usage
  6814. M600 [ X | Y | Z | E | L | AUTO ]
  6815. - `X` - X position, default 211
  6816. - `Y` - Y position, default 0
  6817. - `Z` - relative lift Z, default MIN_Z_FOR_SWAP.
  6818. - `E` - initial retract, default -2
  6819. - `L` - later retract distance for removal, default -80
  6820. - `AUTO` - Automatically (only with MMU)
  6821. */
  6822. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6823. {
  6824. st_synchronize();
  6825. float x_position = current_position[X_AXIS];
  6826. float y_position = current_position[Y_AXIS];
  6827. float z_shift = MIN_Z_FOR_SWAP;
  6828. float e_shift_init = 0;
  6829. float e_shift_late = 0;
  6830. bool automatic = false;
  6831. //Retract extruder
  6832. if(code_seen('E'))
  6833. {
  6834. e_shift_init = code_value();
  6835. }
  6836. else
  6837. {
  6838. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6839. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6840. #endif
  6841. }
  6842. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6843. if (code_seen('L'))
  6844. {
  6845. e_shift_late = code_value();
  6846. }
  6847. else
  6848. {
  6849. #ifdef FILAMENTCHANGE_FINALRETRACT
  6850. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6851. #endif
  6852. }
  6853. // Z lift. For safety only allow positive values
  6854. if (code_seen('Z')) z_shift = fabs(code_value());
  6855. //Move XY to side
  6856. if(code_seen('X'))
  6857. {
  6858. x_position = code_value();
  6859. }
  6860. else
  6861. {
  6862. #ifdef FILAMENTCHANGE_XPOS
  6863. x_position = FILAMENTCHANGE_XPOS;
  6864. #endif
  6865. }
  6866. if(code_seen('Y'))
  6867. {
  6868. y_position = code_value();
  6869. }
  6870. else
  6871. {
  6872. #ifdef FILAMENTCHANGE_YPOS
  6873. y_position = FILAMENTCHANGE_YPOS ;
  6874. #endif
  6875. }
  6876. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6877. automatic = true;
  6878. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6879. }
  6880. break;
  6881. #endif //FILAMENTCHANGEENABLE
  6882. /*!
  6883. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6884. */
  6885. /*!
  6886. ### M125 - Pause print (TODO: not implemented)
  6887. */
  6888. /*!
  6889. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6890. */
  6891. case 25:
  6892. case 601:
  6893. {
  6894. if (!isPrintPaused) {
  6895. st_synchronize();
  6896. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6897. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6898. lcd_pause_print();
  6899. }
  6900. }
  6901. break;
  6902. /*!
  6903. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6904. */
  6905. case 602:
  6906. {
  6907. if (isPrintPaused) lcd_resume_print();
  6908. }
  6909. break;
  6910. /*!
  6911. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6912. */
  6913. case 603: {
  6914. lcd_print_stop();
  6915. }
  6916. break;
  6917. #ifdef PINDA_THERMISTOR
  6918. /*!
  6919. ### 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>
  6920. Wait for PINDA thermistor to reach target temperature
  6921. #### Usage
  6922. M860 [ S ]
  6923. #### Parameters
  6924. - `S` - Target temperature
  6925. */
  6926. case 860:
  6927. {
  6928. int set_target_pinda = 0;
  6929. if (code_seen('S')) {
  6930. set_target_pinda = code_value_short();
  6931. }
  6932. else {
  6933. break;
  6934. }
  6935. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6936. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6937. SERIAL_PROTOCOLLN(set_target_pinda);
  6938. codenum = _millis();
  6939. cancel_heatup = false;
  6940. bool is_pinda_cooling = false;
  6941. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6942. is_pinda_cooling = true;
  6943. }
  6944. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6945. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6946. {
  6947. SERIAL_PROTOCOLPGM("P:");
  6948. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6949. SERIAL_PROTOCOL('/');
  6950. SERIAL_PROTOCOLLN(set_target_pinda);
  6951. codenum = _millis();
  6952. }
  6953. manage_heater();
  6954. manage_inactivity();
  6955. lcd_update(0);
  6956. }
  6957. LCD_MESSAGERPGM(MSG_OK);
  6958. break;
  6959. }
  6960. /*!
  6961. ### 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>
  6962. Set compensation ustep value `S` for compensation table index `I`.
  6963. #### Usage
  6964. M861 [ ? | ! | Z | S | I ]
  6965. #### Parameters
  6966. - `?` - Print current EEPROM offset values
  6967. - `!` - Set factory default values
  6968. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6969. - `S` - Microsteps
  6970. - `I` - Table index
  6971. */
  6972. case 861: {
  6973. const char * const _header = PSTR("index, temp, ustep, um");
  6974. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6975. int16_t usteps = 0;
  6976. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6977. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6978. SERIAL_PROTOCOLLNRPGM(_header);
  6979. for (uint8_t i = 0; i < 6; i++)
  6980. {
  6981. if(i > 0) {
  6982. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6983. }
  6984. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6985. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6986. SERIAL_PROTOCOLPGM(", ");
  6987. SERIAL_PROTOCOL(35 + (i * 5));
  6988. SERIAL_PROTOCOLPGM(", ");
  6989. SERIAL_PROTOCOL(usteps);
  6990. SERIAL_PROTOCOLPGM(", ");
  6991. SERIAL_PROTOCOLLN(mm * 1000);
  6992. }
  6993. }
  6994. else if (code_seen('!')) { // ! - Set factory default values
  6995. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6996. int16_t z_shift = 8; //40C - 20um - 8usteps
  6997. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6998. z_shift = 24; //45C - 60um - 24usteps
  6999. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  7000. z_shift = 48; //50C - 120um - 48usteps
  7001. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  7002. z_shift = 80; //55C - 200um - 80usteps
  7003. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  7004. z_shift = 120; //60C - 300um - 120usteps
  7005. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  7006. SERIAL_PROTOCOLLNPGM("factory restored");
  7007. }
  7008. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  7009. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  7010. int16_t z_shift = 0;
  7011. for (uint8_t i = 0; i < 5; i++) {
  7012. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  7013. }
  7014. SERIAL_PROTOCOLLNPGM("zerorized");
  7015. }
  7016. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  7017. int16_t usteps = code_value_short();
  7018. if (code_seen('I')) {
  7019. uint8_t index = code_value_uint8();
  7020. if (index < 5) {
  7021. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  7022. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7023. SERIAL_PROTOCOLLNRPGM(_header);
  7024. for (uint8_t i = 0; i < 6; i++)
  7025. {
  7026. usteps = 0;
  7027. if (i > 0) {
  7028. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  7029. }
  7030. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7031. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7032. SERIAL_PROTOCOLPGM(", ");
  7033. SERIAL_PROTOCOL(35 + (i * 5));
  7034. SERIAL_PROTOCOLPGM(", ");
  7035. SERIAL_PROTOCOL(usteps);
  7036. SERIAL_PROTOCOLPGM(", ");
  7037. SERIAL_PROTOCOLLN(mm * 1000);
  7038. }
  7039. }
  7040. }
  7041. }
  7042. else {
  7043. SERIAL_PROTOCOLLNPGM("no valid command");
  7044. }
  7045. } break;
  7046. #endif //PINDA_THERMISTOR
  7047. /*!
  7048. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  7049. Checks the parameters of the printer and gcode and performs compatibility check
  7050. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  7051. - M862.2 { P<model_code> | Q }
  7052. - M862.3 { P"<model_name>" | Q }
  7053. - M862.4 { P<fw_version> | Q }
  7054. - M862.5 { P<gcode_level> | Q }
  7055. When run with P<> argument, the check is performed against the input value.
  7056. When run with Q argument, the current value is shown.
  7057. M862.3 accepts text identifiers of printer types too.
  7058. The syntax of M862.3 is (note the quotes around the type):
  7059. M862.3 P "MK3S"
  7060. Accepted printer type identifiers and their numeric counterparts:
  7061. - MK1 (100)
  7062. - MK2 (200)
  7063. - MK2MM (201)
  7064. - MK2S (202)
  7065. - MK2SMM (203)
  7066. - MK2.5 (250)
  7067. - MK2.5MMU2 (20250)
  7068. - MK2.5S (252)
  7069. - MK2.5SMMU2S (20252)
  7070. - MK3 (300)
  7071. - MK3MMU2 (20300)
  7072. - MK3S (302)
  7073. - MK3SMMU2S (20302)
  7074. */
  7075. case 862: // M862: print checking
  7076. float nDummy;
  7077. uint8_t nCommand;
  7078. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7079. switch((ClPrintChecking)nCommand)
  7080. {
  7081. case ClPrintChecking::_Nozzle: // ~ .1
  7082. uint16_t nDiameter;
  7083. if(code_seen('P'))
  7084. {
  7085. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7086. nozzle_diameter_check(nDiameter);
  7087. }
  7088. else if(code_seen('Q'))
  7089. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7090. break;
  7091. case ClPrintChecking::_Model: // ~ .2
  7092. if(code_seen('P'))
  7093. {
  7094. uint16_t nPrinterModel;
  7095. nPrinterModel=(uint16_t)code_value_long();
  7096. // based on current state of MMU (active/stopped/connecting) perform a runtime update of the printer type
  7097. fSetMmuMode(MMU2::mmu2.Enabled());
  7098. printer_model_check(nPrinterModel);
  7099. }
  7100. else if(code_seen('Q'))
  7101. SERIAL_PROTOCOLLN(nPrinterType);
  7102. break;
  7103. case ClPrintChecking::_Smodel: // ~ .3
  7104. if(code_seen('P'))
  7105. {
  7106. fSetMmuMode(MMU2::mmu2.Enabled());
  7107. printer_smodel_check(strchr_pointer);
  7108. }
  7109. else if(code_seen('Q'))
  7110. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7111. break;
  7112. case ClPrintChecking::_Version: // ~ .4
  7113. if(code_seen('P'))
  7114. fw_version_check(++strchr_pointer);
  7115. else if(code_seen('Q'))
  7116. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7117. break;
  7118. case ClPrintChecking::_Gcode: // ~ .5
  7119. if(code_seen('P'))
  7120. {
  7121. uint16_t nGcodeLevel;
  7122. nGcodeLevel=(uint16_t)code_value_long();
  7123. gcode_level_check(nGcodeLevel);
  7124. }
  7125. else if(code_seen('Q'))
  7126. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7127. break;
  7128. }
  7129. break;
  7130. #ifdef LIN_ADVANCE
  7131. /*!
  7132. ### 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>
  7133. 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.
  7134. #### Usage
  7135. M900 [ K | R | W | H | D]
  7136. #### Parameters
  7137. - `K` - Advance K factor
  7138. - `R` - Set ratio directly (overrides WH/D)
  7139. - `W` - Width
  7140. - `H` - Height
  7141. - `D` - Diameter Set ratio from WH/D
  7142. */
  7143. case 900:
  7144. gcode_M900();
  7145. break;
  7146. #endif
  7147. /*!
  7148. ### 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>
  7149. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7150. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7151. #### Usage
  7152. M907 [ X | Y | Z | E | B | S ]
  7153. #### Parameters
  7154. - `X` - X motor driver
  7155. - `Y` - Y motor driver
  7156. - `Z` - Z motor driver
  7157. - `E` - Extruder motor driver
  7158. - `B` - Second Extruder motor driver
  7159. - `S` - All motors
  7160. */
  7161. case 907:
  7162. {
  7163. #ifdef TMC2130
  7164. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7165. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7166. if(code_seen(axis_codes[i])){
  7167. if( i == E_AXIS && FarmOrUserECool() ){
  7168. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7169. SERIAL_ECHOLNPGM(", M907 E ignored");
  7170. continue;
  7171. }
  7172. long cur_mA = code_value_long();
  7173. uint8_t val = tmc2130_cur2val(cur_mA);
  7174. tmc2130_set_current_h(i, val);
  7175. tmc2130_set_current_r(i, val);
  7176. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7177. }
  7178. }
  7179. #else //TMC2130
  7180. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7181. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7182. if(code_seen('B')) st_current_set(4,code_value());
  7183. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7184. #endif
  7185. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7186. if(code_seen('X')) st_current_set(0, code_value());
  7187. #endif
  7188. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7189. if(code_seen('Z')) st_current_set(1, code_value());
  7190. #endif
  7191. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7192. if(code_seen('E')) st_current_set(2, code_value());
  7193. #endif
  7194. #endif //TMC2130
  7195. }
  7196. break;
  7197. /*!
  7198. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7199. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7200. #### Usage
  7201. M908 [ P | S ]
  7202. #### Parameters
  7203. - `P` - channel
  7204. - `S` - current
  7205. */
  7206. case 908:
  7207. {
  7208. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7209. uint8_t channel,current;
  7210. if(code_seen('P')) channel=code_value();
  7211. if(code_seen('S')) current=code_value();
  7212. digitalPotWrite(channel, current);
  7213. #endif
  7214. }
  7215. break;
  7216. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7217. /*!
  7218. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7219. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7220. */
  7221. case 910:
  7222. {
  7223. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7224. }
  7225. break;
  7226. /*!
  7227. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7228. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7229. #### Usage
  7230. M911 [ X | Y | Z | E ]
  7231. #### Parameters
  7232. - `X` - X stepper driver holding current value
  7233. - `Y` - Y stepper driver holding current value
  7234. - `Z` - Z stepper driver holding current value
  7235. - `E` - Extruder stepper driver holding current value
  7236. */
  7237. case 911:
  7238. {
  7239. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7240. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7241. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7242. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7243. }
  7244. break;
  7245. /*!
  7246. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7247. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7248. #### Usage
  7249. M912 [ X | Y | Z | E ]
  7250. #### Parameters
  7251. - `X` - X stepper driver running current value
  7252. - `Y` - Y stepper driver running current value
  7253. - `Z` - Z stepper driver running current value
  7254. - `E` - Extruder stepper driver running current value
  7255. */
  7256. case 912:
  7257. {
  7258. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7259. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7260. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7261. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7262. }
  7263. break;
  7264. /*!
  7265. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7266. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7267. Shows TMC2130 currents.
  7268. */
  7269. case 913:
  7270. {
  7271. tmc2130_print_currents();
  7272. }
  7273. break;
  7274. /*!
  7275. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7276. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7277. */
  7278. case 914:
  7279. {
  7280. tmc2130_mode = TMC2130_MODE_NORMAL;
  7281. update_mode_profile();
  7282. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7283. }
  7284. break;
  7285. /*!
  7286. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7287. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7288. */
  7289. case 915:
  7290. {
  7291. tmc2130_mode = TMC2130_MODE_SILENT;
  7292. update_mode_profile();
  7293. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7294. }
  7295. break;
  7296. /*!
  7297. ### 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>
  7298. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7299. #### Usage
  7300. M916 [ X | Y | Z | E ]
  7301. #### Parameters
  7302. - `X` - X stepper driver stallguard sensitivity threshold value
  7303. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7304. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7305. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7306. */
  7307. case 916:
  7308. {
  7309. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7310. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7311. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7312. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7313. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7314. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7315. }
  7316. break;
  7317. /*!
  7318. ### 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>
  7319. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7320. #### Usage
  7321. M917 [ X | Y | Z | E ]
  7322. #### Parameters
  7323. - `X` - X stepper driver PWM amplitude offset value
  7324. - `Y` - Y stepper driver PWM amplitude offset value
  7325. - `Z` - Z stepper driver PWM amplitude offset value
  7326. - `E` - Extruder stepper driver PWM amplitude offset value
  7327. */
  7328. case 917:
  7329. {
  7330. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7331. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7332. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7333. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7334. }
  7335. break;
  7336. /*!
  7337. ### 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>
  7338. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7339. #### Usage
  7340. M918 [ X | Y | Z | E ]
  7341. #### Parameters
  7342. - `X` - X stepper driver PWM amplitude gradient value
  7343. - `Y` - Y stepper driver PWM amplitude gradient value
  7344. - `Z` - Z stepper driver PWM amplitude gradient value
  7345. - `E` - Extruder stepper driver PWM amplitude gradient value
  7346. */
  7347. case 918:
  7348. {
  7349. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7350. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7351. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7352. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7353. }
  7354. break;
  7355. #endif //TMC2130_SERVICE_CODES_M910_M918
  7356. /*!
  7357. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7358. 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!
  7359. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7360. #### Usage
  7361. M350 [ X | Y | Z | E | B | S ]
  7362. #### Parameters
  7363. - `X` - X new resolution
  7364. - `Y` - Y new resolution
  7365. - `Z` - Z new resolution
  7366. - `E` - E new resolution
  7367. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7368. - `B` - Second extruder new resolution
  7369. - `S` - All axes new resolution
  7370. */
  7371. case 350:
  7372. {
  7373. #ifdef TMC2130
  7374. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7375. {
  7376. if(code_seen(axis_codes[i]))
  7377. {
  7378. uint16_t res_new = code_value();
  7379. #ifdef ALLOW_ALL_MRES
  7380. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7381. #else
  7382. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7383. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7384. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7385. #endif
  7386. if (res_valid)
  7387. {
  7388. st_synchronize();
  7389. uint16_t res = tmc2130_get_res(i);
  7390. tmc2130_set_res(i, res_new);
  7391. cs.axis_ustep_resolution[i] = res_new;
  7392. if (res_new > res)
  7393. {
  7394. uint16_t fac = (res_new / res);
  7395. cs.axis_steps_per_unit[i] *= fac;
  7396. position[i] *= fac;
  7397. }
  7398. else
  7399. {
  7400. uint16_t fac = (res / res_new);
  7401. cs.axis_steps_per_unit[i] /= fac;
  7402. position[i] /= fac;
  7403. }
  7404. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7405. if (i == E_AXIS)
  7406. fsensor.init();
  7407. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7408. }
  7409. }
  7410. }
  7411. reset_acceleration_rates();
  7412. #else //TMC2130
  7413. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7414. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7415. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7416. if(code_seen('B')) microstep_mode(4,code_value());
  7417. microstep_readings();
  7418. #endif
  7419. #endif //TMC2130
  7420. }
  7421. break;
  7422. /*!
  7423. ### 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>
  7424. Toggle MS1 MS2 pins directly.
  7425. #### Usage
  7426. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7427. #### Parameters
  7428. - `X` - Update X axis
  7429. - `Y` - Update Y axis
  7430. - `Z` - Update Z axis
  7431. - `E` - Update E axis
  7432. - `S` - which MSx pin to toggle
  7433. - `B` - new pin value
  7434. */
  7435. case 351:
  7436. {
  7437. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7438. if(code_seen('S')) switch((int)code_value())
  7439. {
  7440. case 1:
  7441. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7442. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7443. break;
  7444. case 2:
  7445. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7446. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7447. break;
  7448. }
  7449. microstep_readings();
  7450. #endif
  7451. }
  7452. break;
  7453. /*!
  7454. ### M701 - Load filament to extruder <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7455. Load filament into the active extruder.
  7456. #### Usage
  7457. M701 [ P | T | L | Z ]
  7458. #### Parameters
  7459. - `P` - n index of MMU slot (zero based, so 0-4 like T0 and T4)
  7460. - `T` - Alias of `P`. Used for compatibility with Marlin
  7461. - `L` - Extrude distance for insertion (positive value)(manual reload)
  7462. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_LOAD
  7463. */
  7464. case 701:
  7465. {
  7466. uint8_t mmuSlotIndex = 0xffU;
  7467. float fastLoadLength = FILAMENTCHANGE_FIRSTFEED; // Only used without MMU
  7468. float z_target = MIN_Z_FOR_LOAD;
  7469. if( MMU2::mmu2.Enabled() )
  7470. {
  7471. if( code_seen('P') || code_seen('T') ) {
  7472. mmuSlotIndex = code_value_uint8();
  7473. }
  7474. }
  7475. if (code_seen('L')) fastLoadLength = code_value();
  7476. // Z lift. For safety only allow positive values
  7477. if (code_seen('Z')) z_target = fabs(code_value());
  7478. // Raise the Z axis
  7479. float delta = raise_z(z_target);
  7480. // Load filament
  7481. gcode_M701(fastLoadLength, mmuSlotIndex);
  7482. // Restore Z axis
  7483. raise_z(-delta);
  7484. }
  7485. break;
  7486. /*!
  7487. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7488. #### Usage
  7489. M702 [ U | Z ]
  7490. #### Parameters
  7491. - `U` - Retract distance for removal (manual reload). Default value is 0.
  7492. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_UNLOAD.
  7493. */
  7494. case 702:
  7495. {
  7496. float z_target = MIN_Z_FOR_UNLOAD;
  7497. float unloadLength = FILAMENTCHANGE_FINALRETRACT;
  7498. if (code_seen('U')) unloadLength = code_value();
  7499. // For safety only allow positive values
  7500. if (code_seen('Z')) z_target = fabs(code_value());
  7501. // Raise the Z axis
  7502. float delta = raise_z(z_target);
  7503. // Unload filament
  7504. if (MMU2::mmu2.Enabled()) MMU2::mmu2.unload();
  7505. else unload_filament(unloadLength);
  7506. // Restore Z axis
  7507. raise_z(-delta);
  7508. }
  7509. break;
  7510. /*!
  7511. ### M704 - Load to MMU
  7512. #### Usage
  7513. M704 [ P ]
  7514. #### Parameters
  7515. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7516. */
  7517. case 704:
  7518. {
  7519. gcodes_M704_M705_M706(704);
  7520. }
  7521. break;
  7522. /*!
  7523. ### M705 - Eject filament
  7524. #### Usage
  7525. M705 [ P ]
  7526. #### Parameters
  7527. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7528. */
  7529. case 705:
  7530. {
  7531. gcodes_M704_M705_M706(705);
  7532. }
  7533. break;
  7534. /*!
  7535. ### M706 - Cut filament
  7536. #### Usage
  7537. M706 [ P ]
  7538. #### Parameters
  7539. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7540. */
  7541. case 706:
  7542. {
  7543. gcodes_M704_M705_M706(706);
  7544. }
  7545. break;
  7546. /*!
  7547. ### M707 - Read from MMU register
  7548. #### Usage
  7549. M707 [ A | C ]
  7550. M707 A0x14 C2 - Read two bytes from register 0x14
  7551. #### Parameters
  7552. - `A` - Address of register in hexidecimal. Default value is 0.
  7553. - `C` - Number of bytes to read. Default value is 0.
  7554. */
  7555. case 707:
  7556. {
  7557. uint8_t addr = 0;
  7558. uint8_t nrbytes = 0;
  7559. if ( MMU2::mmu2.Enabled() )
  7560. {
  7561. if( code_seen('A') ) {
  7562. addr = uint8_t(strtol(strchr_pointer+1, NULL, 0));
  7563. }
  7564. if( code_seen('C') ) {
  7565. nrbytes = code_value_uint8();
  7566. }
  7567. MMU2::mmu2.ReadRegister(addr, nrbytes);
  7568. }
  7569. }
  7570. break;
  7571. /*!
  7572. ### M708 - Write to MMU register
  7573. #### Usage
  7574. M708 [ A | X | C ]
  7575. M708 A0x14 X30 C1 - Write to register 0x14 the value 30 which is 1 byte.
  7576. #### Parameters
  7577. - `A` - Address of register in hexidecimal. Default value is 0.
  7578. - `X` - Data to write. Default value is 0.
  7579. - `C` - Number of bytes to write. Default value is 0.
  7580. */
  7581. case 708:
  7582. {
  7583. uint8_t addr = 0;
  7584. uint8_t data = 0;
  7585. uint8_t nrbytes = 0;
  7586. if ( MMU2::mmu2.Enabled() )
  7587. {
  7588. if( code_seen('A') ) {
  7589. addr = uint8_t(strtol(strchr_pointer+1, NULL, 0));
  7590. }
  7591. if( code_seen('X') ) {
  7592. data = code_value_uint8();
  7593. }
  7594. if( code_seen('C') ) {
  7595. nrbytes = code_value_uint8();
  7596. }
  7597. MMU2::mmu2.WriteRegister(addr, data, nrbytes);
  7598. }
  7599. }
  7600. break;
  7601. /*!
  7602. ### M709 - MMU turn on/off/reset
  7603. The MK3S cannot not power off the MMU, for that reason the functionality is not supported.
  7604. #### Usage
  7605. M709 [ X ]
  7606. M709 X0 - issue an X0 command via communication into the MMU (soft reset)
  7607. M709 X1 - toggle the MMU's reset pin (hardware reset)
  7608. #### Parameters
  7609. - `X` - Reset MMU
  7610. */
  7611. case 709:
  7612. {
  7613. if (MMU2::mmu2.Enabled() && code_seen('X'))
  7614. {
  7615. switch (code_value_uint8())
  7616. {
  7617. case 0:
  7618. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  7619. break;
  7620. case 1:
  7621. MMU2::mmu2.Reset(MMU2::MMU2::ResetPin);
  7622. break;
  7623. default:
  7624. break;
  7625. }
  7626. }
  7627. }
  7628. break;
  7629. /*!
  7630. ### M999 - Restart after being stopped <a href="https://reprap.org/wiki/G-code#M999:_Restart_after_being_stopped_by_error">M999: Restart after being stopped by error</a>
  7631. @todo Usually doesn't work. Should be fixed or removed. Most of the time, if `Stopped` it set, the print fails and is unrecoverable.
  7632. */
  7633. case 999:
  7634. Stopped = false;
  7635. lcd_reset_alert_level();
  7636. gcode_LastN = Stopped_gcode_LastN;
  7637. FlushSerialRequestResend();
  7638. break;
  7639. /*!
  7640. #### End of M-Commands
  7641. */
  7642. default:
  7643. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7644. }
  7645. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7646. mcode_in_progress = 0;
  7647. }
  7648. }
  7649. // end if(code_seen('M')) (end of M codes)
  7650. /*!
  7651. -----------------------------------------------------------------------------------------
  7652. # T Codes
  7653. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7654. #### For MMU_V2:
  7655. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7656. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7657. @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.
  7658. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7659. */
  7660. else if(code_seen('T')){
  7661. TCodes(strchr_pointer, code_value());
  7662. } // end if(code_seen('T')) (end of T codes)
  7663. /*!
  7664. #### End of T-Codes
  7665. */
  7666. /**
  7667. *---------------------------------------------------------------------------------
  7668. *# D codes
  7669. */
  7670. else if (code_seen('D')) // D codes (debug)
  7671. {
  7672. switch(code_value_short())
  7673. {
  7674. /*!
  7675. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7676. */
  7677. case -1:
  7678. dcode__1(); break;
  7679. #ifdef DEBUG_DCODES
  7680. /*!
  7681. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7682. #### Usage
  7683. D0 [ B ]
  7684. #### Parameters
  7685. - `B` - Bootloader
  7686. */
  7687. case 0:
  7688. dcode_0(); break;
  7689. /*!
  7690. *
  7691. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7692. D1
  7693. *
  7694. */
  7695. case 1:
  7696. dcode_1(); break;
  7697. #endif
  7698. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7699. /*!
  7700. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7701. This command can be used without any additional parameters. It will read the entire RAM.
  7702. #### Usage
  7703. D2 [ A | C | X ]
  7704. #### Parameters
  7705. - `A` - Address (x0000-x1fff)
  7706. - `C` - Count (1-8192)
  7707. - `X` - Data
  7708. #### Notes
  7709. - The hex address needs to be lowercase without the 0 before the x
  7710. - Count is decimal
  7711. - The hex data needs to be lowercase
  7712. */
  7713. case 2:
  7714. dcode_2(); break;
  7715. #endif //DEBUG_DCODES
  7716. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7717. /*!
  7718. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7719. This command can be used without any additional parameters. It will read the entire eeprom.
  7720. #### Usage
  7721. D3 [ A | C | X ]
  7722. #### Parameters
  7723. - `A` - Address (x0000-x0fff)
  7724. - `C` - Count (1-4096)
  7725. - `X` - Data (hex)
  7726. #### Notes
  7727. - The hex address needs to be lowercase without the 0 before the x
  7728. - Count is decimal
  7729. - The hex data needs to be lowercase
  7730. */
  7731. case 3:
  7732. dcode_3(); break;
  7733. #endif //DEBUG_DCODE3
  7734. #ifdef DEBUG_DCODES
  7735. /*!
  7736. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7737. To read the digital value of a pin you need only to define the pin number.
  7738. #### Usage
  7739. D4 [ P | F | V ]
  7740. #### Parameters
  7741. - `P` - Pin (0-255)
  7742. - `F` - Function in/out (0/1)
  7743. - `V` - Value (0/1)
  7744. */
  7745. case 4:
  7746. dcode_4(); break;
  7747. #endif //DEBUG_DCODES
  7748. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7749. /*!
  7750. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7751. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7752. #### Usage
  7753. D5 [ A | C | X | E ]
  7754. #### Parameters
  7755. - `A` - Address (x00000-x3ffff)
  7756. - `C` - Count (1-8192)
  7757. - `X` - Data (hex)
  7758. - `E` - Erase
  7759. #### Notes
  7760. - The hex address needs to be lowercase without the 0 before the x
  7761. - Count is decimal
  7762. - The hex data needs to be lowercase
  7763. */
  7764. case 5:
  7765. dcode_5(); break;
  7766. #endif //DEBUG_DCODE5
  7767. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7768. /*!
  7769. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7770. Reserved
  7771. */
  7772. case 6:
  7773. dcode_6(); break;
  7774. #endif
  7775. #ifdef DEBUG_DCODES
  7776. /*!
  7777. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7778. Reserved
  7779. */
  7780. case 7:
  7781. dcode_7(); break;
  7782. /*!
  7783. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7784. #### Usage
  7785. D8 [ ? | ! | P | Z ]
  7786. #### Parameters
  7787. - `?` - Read PINDA temperature shift values
  7788. - `!` - Reset PINDA temperature shift values to default
  7789. - `P` - Pinda temperature [C]
  7790. - `Z` - Z Offset [mm]
  7791. */
  7792. case 8:
  7793. dcode_8(); break;
  7794. /*!
  7795. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7796. #### Usage
  7797. D9 [ I | V ]
  7798. #### Parameters
  7799. - `I` - ADC channel index
  7800. - `0` - Heater 0 temperature
  7801. - `1` - Heater 1 temperature
  7802. - `2` - Bed temperature
  7803. - `3` - PINDA temperature
  7804. - `4` - PWR voltage
  7805. - `5` - Ambient temperature
  7806. - `6` - BED voltage
  7807. - `V` Value to be written as simulated
  7808. */
  7809. case 9:
  7810. dcode_9(); break;
  7811. /*!
  7812. ### 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>
  7813. */
  7814. case 10:
  7815. dcode_10(); break;
  7816. /*!
  7817. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7818. Writes the current time in the log file.
  7819. */
  7820. #endif //DEBUG_DCODES
  7821. #ifdef XFLASH_DUMP
  7822. /*!
  7823. ### 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>
  7824. Generate a crash dump for later retrival.
  7825. #### Usage
  7826. D20 [E]
  7827. ### Parameters
  7828. - `E` - Perform an emergency crash dump (resets the printer).
  7829. ### Notes
  7830. - A crash dump can be later recovered with D21, or cleared with D22.
  7831. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7832. is completed.
  7833. */
  7834. case 20: {
  7835. dcode_20();
  7836. break;
  7837. };
  7838. /*!
  7839. ### 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>
  7840. Output the complete crash dump (if present) to the serial.
  7841. #### Usage
  7842. D21
  7843. ### Notes
  7844. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7845. */
  7846. case 21: {
  7847. dcode_21();
  7848. break;
  7849. };
  7850. /*!
  7851. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7852. Clear an existing internal crash dump.
  7853. #### Usage
  7854. D22
  7855. */
  7856. case 22: {
  7857. dcode_22();
  7858. break;
  7859. };
  7860. #endif //XFLASH_DUMP
  7861. #ifdef EMERGENCY_SERIAL_DUMP
  7862. /*!
  7863. ### 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>
  7864. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7865. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7866. #### Usage
  7867. D23 [E] [R]
  7868. #### Parameters
  7869. - `E` - Perform an emergency crash dump (resets the printer).
  7870. - `R` - Disable online dumps.
  7871. */
  7872. case 23: {
  7873. dcode_23();
  7874. break;
  7875. };
  7876. #endif
  7877. #ifdef TEMP_MODEL_DEBUG
  7878. /*!
  7879. ## D70 - Enable low-level temperature model logging for offline simulation
  7880. #### Usage
  7881. D70 [ S ]
  7882. #### Parameters
  7883. - `S` - Enable 0-1 (default 0)
  7884. */
  7885. case 70: {
  7886. if(code_seen('S'))
  7887. temp_model_log_enable(code_value_short());
  7888. break;
  7889. }
  7890. #endif
  7891. #ifdef HEATBED_ANALYSIS
  7892. /*!
  7893. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7894. This command will log data to SD card file "mesh.txt".
  7895. #### Usage
  7896. D80 [ E | F | G | H | I | J ]
  7897. #### Parameters
  7898. - `E` - Dimension X (default 40)
  7899. - `F` - Dimention Y (default 40)
  7900. - `G` - Points X (default 40)
  7901. - `H` - Points Y (default 40)
  7902. - `I` - Offset X (default 74)
  7903. - `J` - Offset Y (default 34)
  7904. */
  7905. case 80:
  7906. dcode_80(); break;
  7907. /*!
  7908. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7909. This command will log data to SD card file "wldsd.txt".
  7910. #### Usage
  7911. D81 [ E | F | G | H | I | J ]
  7912. #### Parameters
  7913. - `E` - Dimension X (default 40)
  7914. - `F` - Dimention Y (default 40)
  7915. - `G` - Points X (default 40)
  7916. - `H` - Points Y (default 40)
  7917. - `I` - Offset X (default 74)
  7918. - `J` - Offset Y (default 34)
  7919. */
  7920. case 81:
  7921. dcode_81(); break;
  7922. #endif //HEATBED_ANALYSIS
  7923. #ifdef DEBUG_DCODES
  7924. /*!
  7925. ### 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>
  7926. */
  7927. case 106:
  7928. dcode_106(); break;
  7929. #ifdef TMC2130
  7930. /*!
  7931. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7932. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7933. #### Usage
  7934. D2130 [ Axis | Command | Subcommand | Value ]
  7935. #### Parameters
  7936. - Axis
  7937. - `X` - X stepper driver
  7938. - `Y` - Y stepper driver
  7939. - `Z` - Z stepper driver
  7940. - `E` - Extruder stepper driver
  7941. - Commands
  7942. - `0` - Current off
  7943. - `1` - Current on
  7944. - `+` - Single step
  7945. - `-` - Single step oposite direction
  7946. - `NNN` - Value sereval steps
  7947. - `?` - Read register
  7948. - Subcommands for read register
  7949. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7950. - `step` - Step
  7951. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7952. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7953. - `wave` - Microstep linearity compensation curve
  7954. - `!` - Set register
  7955. - Subcommands for set register
  7956. - `mres` - Micro step resolution
  7957. - `step` - Step
  7958. - `wave` - Microstep linearity compensation curve
  7959. - Values for set register
  7960. - `0, 180 --> 250` - Off
  7961. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7962. - `@` - Home calibrate axis
  7963. Examples:
  7964. D2130E?wave
  7965. Print extruder microstep linearity compensation curve
  7966. D2130E!wave0
  7967. Disable extruder linearity compensation curve, (sine curve is used)
  7968. D2130E!wave220
  7969. (sin(x))^1.1 extruder microstep compensation curve used
  7970. Notes:
  7971. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7972. *
  7973. */
  7974. case 2130:
  7975. dcode_2130(); break;
  7976. #endif //TMC2130
  7977. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7978. /*!
  7979. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7980. #### Usage
  7981. D9125 [ ? | ! | R | X | Y | L ]
  7982. #### Parameters
  7983. - `?` - Print values
  7984. - `!` - Print values
  7985. - `R` - Resolution. Not active in code
  7986. - `X` - X values
  7987. - `Y` - Y values
  7988. - `L` - Activate filament sensor log
  7989. */
  7990. case 9125:
  7991. dcode_9125(); break;
  7992. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7993. #endif //DEBUG_DCODES
  7994. default:
  7995. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7996. }
  7997. }
  7998. else
  7999. {
  8000. SERIAL_ECHO_START;
  8001. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  8002. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  8003. SERIAL_ECHOLNPGM("\"(2)");
  8004. }
  8005. KEEPALIVE_STATE(NOT_BUSY);
  8006. ClearToSend();
  8007. }
  8008. /*!
  8009. #### End of D-Codes
  8010. */
  8011. /** @defgroup GCodes G-Code List
  8012. */
  8013. // ---------------------------------------------------
  8014. void FlushSerialRequestResend()
  8015. {
  8016. //char cmdbuffer[bufindr][100]="Resend:";
  8017. MYSERIAL.flush();
  8018. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  8019. }
  8020. // Confirm the execution of a command, if sent from a serial line.
  8021. // Execution of a command from a SD card will not be confirmed.
  8022. void ClearToSend()
  8023. {
  8024. previous_millis_cmd.start();
  8025. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  8026. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  8027. }
  8028. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8029. void update_currents() {
  8030. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  8031. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  8032. float tmp_motor[3];
  8033. //SERIAL_ECHOLNPGM("Currents updated: ");
  8034. if (destination[Z_AXIS] < Z_SILENT) {
  8035. //SERIAL_ECHOLNPGM("LOW");
  8036. for (uint8_t i = 0; i < 3; i++) {
  8037. st_current_set(i, current_low[i]);
  8038. /*MYSERIAL.print(int(i));
  8039. SERIAL_ECHOPGM(": ");
  8040. MYSERIAL.println(current_low[i]);*/
  8041. }
  8042. }
  8043. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  8044. //SERIAL_ECHOLNPGM("HIGH");
  8045. for (uint8_t i = 0; i < 3; i++) {
  8046. st_current_set(i, current_high[i]);
  8047. /*MYSERIAL.print(int(i));
  8048. SERIAL_ECHOPGM(": ");
  8049. MYSERIAL.println(current_high[i]);*/
  8050. }
  8051. }
  8052. else {
  8053. for (uint8_t i = 0; i < 3; i++) {
  8054. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  8055. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  8056. st_current_set(i, tmp_motor[i]);
  8057. /*MYSERIAL.print(int(i));
  8058. SERIAL_ECHOPGM(": ");
  8059. MYSERIAL.println(tmp_motor[i]);*/
  8060. }
  8061. }
  8062. }
  8063. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8064. void get_coordinates() {
  8065. bool seen[4]={false,false,false,false};
  8066. for(int8_t i=0; i < NUM_AXIS; i++) {
  8067. if(code_seen(axis_codes[i]))
  8068. {
  8069. bool relative = axis_relative_modes & (1 << i);
  8070. destination[i] = code_value();
  8071. if (i == E_AXIS) {
  8072. float emult = extruder_multiplier[active_extruder];
  8073. if (emult != 1.) {
  8074. if (! relative) {
  8075. destination[i] -= current_position[i];
  8076. relative = true;
  8077. }
  8078. destination[i] *= emult;
  8079. }
  8080. }
  8081. if (relative)
  8082. destination[i] += current_position[i];
  8083. seen[i]=true;
  8084. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8085. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  8086. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8087. }
  8088. else destination[i] = current_position[i]; //Are these else lines really needed?
  8089. }
  8090. if(code_seen('F')) {
  8091. next_feedrate = code_value();
  8092. if(next_feedrate > 0.0) feedrate = next_feedrate;
  8093. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  8094. {
  8095. // float e_max_speed =
  8096. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  8097. }
  8098. }
  8099. }
  8100. void clamp_to_software_endstops(float target[3])
  8101. {
  8102. #ifdef DEBUG_DISABLE_SWLIMITS
  8103. return;
  8104. #endif //DEBUG_DISABLE_SWLIMITS
  8105. world2machine_clamp(target[0], target[1]);
  8106. // Clamp the Z coordinate.
  8107. if (min_software_endstops) {
  8108. float negative_z_offset = 0;
  8109. #ifdef ENABLE_AUTO_BED_LEVELING
  8110. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8111. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8112. #endif
  8113. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8114. }
  8115. if (max_software_endstops) {
  8116. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8117. }
  8118. }
  8119. uint16_t restore_interrupted_gcode() {
  8120. // When recovering from a previous print move, restore the originally
  8121. // calculated start position on the first USB/SD command. This accounts
  8122. // properly for relative moves
  8123. if (
  8124. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  8125. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  8126. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  8127. )
  8128. ) {
  8129. memcpy(current_position, saved_start_position, sizeof(current_position));
  8130. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  8131. return saved_segment_idx;
  8132. }
  8133. else
  8134. return 1; //begin with the first segment
  8135. }
  8136. #ifdef MESH_BED_LEVELING
  8137. 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) {
  8138. float dx = x - current_position[X_AXIS];
  8139. float dy = y - current_position[Y_AXIS];
  8140. uint16_t n_segments = 0;
  8141. if (mbl.active) {
  8142. float len = fabs(dx) + fabs(dy);
  8143. if (len > 0)
  8144. // Split to 3cm segments or shorter.
  8145. n_segments = uint16_t(ceil(len / 30.f));
  8146. }
  8147. if (n_segments > 1 && start_segment_idx) {
  8148. float dz = z - current_position[Z_AXIS];
  8149. float de = e - current_position[E_AXIS];
  8150. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  8151. float t = float(i) / float(n_segments);
  8152. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8153. current_position[Y_AXIS] + t * dy,
  8154. current_position[Z_AXIS] + t * dz,
  8155. current_position[E_AXIS] + t * de,
  8156. feed_rate, extruder, current_position, i);
  8157. if (planner_aborted)
  8158. return;
  8159. }
  8160. }
  8161. // The rest of the path.
  8162. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  8163. }
  8164. #endif // MESH_BED_LEVELING
  8165. void prepare_move(uint16_t start_segment_idx)
  8166. {
  8167. clamp_to_software_endstops(destination);
  8168. previous_millis_cmd.start();
  8169. // Do not use feedmultiply for E or Z only moves
  8170. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8171. plan_buffer_line_destinationXYZE(feedrate/60);
  8172. }
  8173. else {
  8174. #ifdef MESH_BED_LEVELING
  8175. 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);
  8176. #else
  8177. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8178. #endif
  8179. }
  8180. set_current_to_destination();
  8181. }
  8182. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8183. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8184. // Trace the arc
  8185. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8186. // As far as the parser is concerned, the position is now == target. In reality the
  8187. // motion control system might still be processing the action and the real tool position
  8188. // in any intermediate location.
  8189. set_current_to_destination();
  8190. previous_millis_cmd.start();
  8191. }
  8192. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8193. #if defined(FAN_PIN)
  8194. #if CONTROLLERFAN_PIN == FAN_PIN
  8195. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8196. #endif
  8197. #endif
  8198. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8199. unsigned long lastMotorCheck = 0;
  8200. void controllerFan()
  8201. {
  8202. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8203. {
  8204. lastMotorCheck = _millis();
  8205. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8206. #if EXTRUDERS > 2
  8207. || !READ(E2_ENABLE_PIN)
  8208. #endif
  8209. #if EXTRUDER > 1
  8210. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8211. || !READ(X2_ENABLE_PIN)
  8212. #endif
  8213. || !READ(E1_ENABLE_PIN)
  8214. #endif
  8215. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8216. {
  8217. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8218. }
  8219. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8220. {
  8221. digitalWrite(CONTROLLERFAN_PIN, 0);
  8222. analogWrite(CONTROLLERFAN_PIN, 0);
  8223. }
  8224. else
  8225. {
  8226. // allows digital or PWM fan output to be used (see M42 handling)
  8227. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8228. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8229. }
  8230. }
  8231. }
  8232. #endif
  8233. #ifdef SAFETYTIMER
  8234. /**
  8235. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8236. *
  8237. * Full screen blocking notification message is shown after heater turning off.
  8238. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8239. * damage print.
  8240. *
  8241. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8242. */
  8243. static void handleSafetyTimer()
  8244. {
  8245. #if (EXTRUDERS > 1)
  8246. #error Implemented only for one extruder.
  8247. #endif //(EXTRUDERS > 1)
  8248. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8249. {
  8250. safetyTimer.stop();
  8251. }
  8252. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8253. {
  8254. safetyTimer.start();
  8255. }
  8256. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8257. {
  8258. setTargetBed(0);
  8259. setAllTargetHotends(0);
  8260. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8261. }
  8262. }
  8263. #endif //SAFETYTIMER
  8264. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8265. {
  8266. #ifdef FILAMENT_SENSOR
  8267. if (fsensor.update()) {
  8268. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8269. }
  8270. #endif
  8271. #ifdef SAFETYTIMER
  8272. handleSafetyTimer();
  8273. #endif //SAFETYTIMER
  8274. #if defined(KILL_PIN) && KILL_PIN > -1
  8275. static int killCount = 0; // make the inactivity button a bit less responsive
  8276. const int KILL_DELAY = 10000;
  8277. #endif
  8278. if(buflen < (BUFSIZE-1)){
  8279. get_command();
  8280. }
  8281. if(previous_millis_cmd.expired(max_inactive_time))
  8282. if(max_inactive_time)
  8283. kill(_n("Inactivity Shutdown"), 4);
  8284. if(stepper_inactive_time) {
  8285. if(previous_millis_cmd.expired(stepper_inactive_time))
  8286. {
  8287. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8288. disable_x();
  8289. disable_y();
  8290. disable_z();
  8291. disable_e0();
  8292. disable_e1();
  8293. disable_e2();
  8294. }
  8295. }
  8296. }
  8297. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8298. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8299. {
  8300. chdkActive = false;
  8301. WRITE(CHDK, LOW);
  8302. }
  8303. #endif
  8304. #if defined(KILL_PIN) && KILL_PIN > -1
  8305. // Check if the kill button was pressed and wait just in case it was an accidental
  8306. // key kill key press
  8307. // -------------------------------------------------------------------------------
  8308. if( 0 == READ(KILL_PIN) )
  8309. {
  8310. killCount++;
  8311. }
  8312. else if (killCount > 0)
  8313. {
  8314. killCount--;
  8315. }
  8316. // Exceeded threshold and we can confirm that it was not accidental
  8317. // KILL the machine
  8318. // ----------------------------------------------------------------
  8319. if ( killCount >= KILL_DELAY)
  8320. {
  8321. kill(NULL, 5);
  8322. }
  8323. #endif
  8324. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8325. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8326. #endif
  8327. #ifdef EXTRUDER_RUNOUT_PREVENT
  8328. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8329. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8330. {
  8331. bool oldstatus=READ(E0_ENABLE_PIN);
  8332. enable_e0();
  8333. float oldepos=current_position[E_AXIS];
  8334. float oldedes=destination[E_AXIS];
  8335. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8336. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8337. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8338. current_position[E_AXIS]=oldepos;
  8339. destination[E_AXIS]=oldedes;
  8340. plan_set_e_position(oldepos);
  8341. previous_millis_cmd.start();
  8342. st_synchronize();
  8343. WRITE(E0_ENABLE_PIN,oldstatus);
  8344. }
  8345. #endif
  8346. check_axes_activity();
  8347. MMU2::mmu2.mmu_loop();
  8348. // handle longpress
  8349. if(lcd_longpress_trigger)
  8350. {
  8351. // long press is not possible in modal mode, wait until ready
  8352. if (lcd_longpress_func && lcd_update_enabled)
  8353. {
  8354. lcd_longpress_func();
  8355. lcd_longpress_trigger = 0;
  8356. }
  8357. }
  8358. #if defined(AUTO_REPORT)
  8359. host_autoreport();
  8360. #endif //AUTO_REPORT
  8361. host_keepalive();
  8362. }
  8363. void kill(const char *full_screen_message, unsigned char id)
  8364. {
  8365. printf_P(_N("KILL: %d\n"), id);
  8366. //return;
  8367. cli(); // Stop interrupts
  8368. disable_heater();
  8369. disable_x();
  8370. // SERIAL_ECHOLNPGM("kill - disable Y");
  8371. disable_y();
  8372. poweroff_z();
  8373. disable_e0();
  8374. disable_e1();
  8375. disable_e2();
  8376. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8377. pinMode(PS_ON_PIN,INPUT);
  8378. #endif
  8379. SERIAL_ERROR_START;
  8380. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8381. if (full_screen_message != NULL) {
  8382. SERIAL_ERRORLNRPGM(full_screen_message);
  8383. lcd_display_message_fullscreen_P(full_screen_message);
  8384. } else {
  8385. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8386. }
  8387. // FMC small patch to update the LCD before ending
  8388. sei(); // enable interrupts
  8389. for ( int i=5; i--; lcd_update(0))
  8390. {
  8391. _delay(200);
  8392. }
  8393. cli(); // disable interrupts
  8394. suicide();
  8395. while(1)
  8396. {
  8397. #ifdef WATCHDOG
  8398. wdt_reset();
  8399. #endif //WATCHDOG
  8400. /* Intentionally left empty */
  8401. } // Wait for reset
  8402. }
  8403. void UnconditionalStop()
  8404. {
  8405. CRITICAL_SECTION_START;
  8406. // Disable all heaters and unroll the temperature wait loop stack
  8407. disable_heater();
  8408. cancel_heatup = true;
  8409. heating_status = HeatingStatus::NO_HEATING;
  8410. // Clear any saved printing state
  8411. cancel_saved_printing();
  8412. // Abort the planner
  8413. planner_abort_hard();
  8414. // Reset the queue
  8415. cmdqueue_reset();
  8416. cmdqueue_serial_disabled = false;
  8417. // Reset the sd status
  8418. card.sdprinting = false;
  8419. card.closefile();
  8420. st_reset_timer();
  8421. CRITICAL_SECTION_END;
  8422. }
  8423. // Emergency stop used by overtemp functions which allows recovery
  8424. // WARNING: This function is called *continuously* during a thermal failure.
  8425. //
  8426. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8427. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8428. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8429. // kept in busy state and *must* be recovered from the LCD.
  8430. void ThermalStop(bool allow_pause)
  8431. {
  8432. if(Stopped == false) {
  8433. Stopped = true;
  8434. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8435. if (!isPrintPaused) {
  8436. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8437. // we cannot make a distinction for the host here, the pause must be instantaneous
  8438. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8439. // disable heaters and save the original temperatures to saved_*, which will get
  8440. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8441. // original values after the pause handler is called.
  8442. float bed_temp = saved_bed_temperature;
  8443. float ext_temp = saved_extruder_temperature;
  8444. int fan_speed = saved_fan_speed;
  8445. lcd_pause_print();
  8446. saved_bed_temperature = bed_temp;
  8447. saved_extruder_temperature = ext_temp;
  8448. saved_fan_speed = fan_speed;
  8449. }
  8450. } else {
  8451. // We got a hard thermal error and/or there is no print going on. Just stop.
  8452. lcd_print_stop();
  8453. // Also prevent further menu entry
  8454. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8455. }
  8456. // Report the status on the serial, switch to a busy state
  8457. SERIAL_ERROR_START;
  8458. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8459. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8460. // higher-priority alert status message)
  8461. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8462. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8463. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8464. WRITE(BEEPER, HIGH);
  8465. }
  8466. // Return to the status screen to stop any pending menu action which could have been
  8467. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8468. // error is immediately shown.
  8469. if (menu_menu != lcd_status_screen)
  8470. lcd_return_to_status();
  8471. }
  8472. bool IsStopped() { return Stopped; };
  8473. void finishAndDisableSteppers()
  8474. {
  8475. st_synchronize();
  8476. disable_x();
  8477. disable_y();
  8478. disable_z();
  8479. disable_e0();
  8480. disable_e1();
  8481. disable_e2();
  8482. #ifndef LA_NOCOMPAT
  8483. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8484. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8485. // state for the next print.
  8486. la10c_reset();
  8487. #endif
  8488. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8489. print_time_remaining_init();
  8490. }
  8491. #ifdef FAST_PWM_FAN
  8492. void setPwmFrequency(uint8_t pin, int val)
  8493. {
  8494. val &= 0x07;
  8495. switch(digitalPinToTimer(pin))
  8496. {
  8497. #if defined(TCCR0A)
  8498. case TIMER0A:
  8499. case TIMER0B:
  8500. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8501. // TCCR0B |= val;
  8502. break;
  8503. #endif
  8504. #if defined(TCCR1A)
  8505. case TIMER1A:
  8506. case TIMER1B:
  8507. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8508. // TCCR1B |= val;
  8509. break;
  8510. #endif
  8511. #if defined(TCCR2)
  8512. case TIMER2:
  8513. case TIMER2:
  8514. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8515. TCCR2 |= val;
  8516. break;
  8517. #endif
  8518. #if defined(TCCR2A)
  8519. case TIMER2A:
  8520. case TIMER2B:
  8521. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8522. TCCR2B |= val;
  8523. break;
  8524. #endif
  8525. #if defined(TCCR3A)
  8526. case TIMER3A:
  8527. case TIMER3B:
  8528. case TIMER3C:
  8529. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8530. TCCR3B |= val;
  8531. break;
  8532. #endif
  8533. #if defined(TCCR4A)
  8534. case TIMER4A:
  8535. case TIMER4B:
  8536. case TIMER4C:
  8537. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8538. TCCR4B |= val;
  8539. break;
  8540. #endif
  8541. #if defined(TCCR5A)
  8542. case TIMER5A:
  8543. case TIMER5B:
  8544. case TIMER5C:
  8545. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8546. TCCR5B |= val;
  8547. break;
  8548. #endif
  8549. }
  8550. }
  8551. #endif //FAST_PWM_FAN
  8552. //! @brief Get and validate extruder number
  8553. //!
  8554. //! If it is not specified, active_extruder is returned in parameter extruder.
  8555. //! @param [in] code M code number
  8556. //! @param [out] extruder
  8557. //! @return error
  8558. //! @retval true Invalid extruder specified in T code
  8559. //! @retval false Valid extruder specified in T code, or not specifiead
  8560. bool setTargetedHotend(int code, uint8_t &extruder)
  8561. {
  8562. extruder = active_extruder;
  8563. if(code_seen('T')) {
  8564. extruder = code_value_uint8();
  8565. if(extruder >= EXTRUDERS) {
  8566. SERIAL_ECHO_START;
  8567. switch(code){
  8568. case 104:
  8569. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8570. break;
  8571. case 105:
  8572. SERIAL_ECHORPGM(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8573. break;
  8574. case 109:
  8575. SERIAL_ECHORPGM(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8576. break;
  8577. case 218:
  8578. SERIAL_ECHORPGM(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8579. break;
  8580. case 221:
  8581. SERIAL_ECHORPGM(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8582. break;
  8583. }
  8584. SERIAL_PROTOCOLLN((int)extruder);
  8585. return true;
  8586. }
  8587. }
  8588. return false;
  8589. }
  8590. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8591. {
  8592. 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)
  8593. {
  8594. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8595. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8596. }
  8597. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8598. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8599. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8600. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8601. total_filament_used = 0;
  8602. }
  8603. float calculate_extruder_multiplier(float diameter) {
  8604. float out = 1.f;
  8605. if (cs.volumetric_enabled && diameter > 0.f) {
  8606. float area = M_PI * diameter * diameter * 0.25;
  8607. out = 1.f / area;
  8608. }
  8609. if (extrudemultiply != 100)
  8610. out *= float(extrudemultiply) * 0.01f;
  8611. return out;
  8612. }
  8613. void calculate_extruder_multipliers() {
  8614. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8615. #if EXTRUDERS > 1
  8616. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8617. #if EXTRUDERS > 2
  8618. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8619. #endif
  8620. #endif
  8621. }
  8622. void delay_keep_alive(unsigned int ms)
  8623. {
  8624. for (;;) {
  8625. manage_heater();
  8626. // Manage inactivity, but don't disable steppers on timeout.
  8627. manage_inactivity(true);
  8628. lcd_update(0);
  8629. if (ms == 0)
  8630. break;
  8631. else if (ms >= 50) {
  8632. _delay(50);
  8633. ms -= 50;
  8634. } else {
  8635. _delay(ms);
  8636. ms = 0;
  8637. }
  8638. }
  8639. }
  8640. static void wait_for_heater(long codenum, uint8_t extruder) {
  8641. if (!degTargetHotend(extruder))
  8642. return;
  8643. #ifdef TEMP_RESIDENCY_TIME
  8644. long residencyStart;
  8645. residencyStart = -1;
  8646. /* continue to loop until we have reached the target temp
  8647. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8648. cancel_heatup = false;
  8649. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8650. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8651. #else
  8652. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8653. #endif //TEMP_RESIDENCY_TIME
  8654. if ((_millis() - codenum) > 1000UL)
  8655. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8656. if (!farm_mode) {
  8657. SERIAL_PROTOCOLPGM("T:");
  8658. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8659. SERIAL_PROTOCOLPGM(" E:");
  8660. SERIAL_PROTOCOL((int)extruder);
  8661. #ifdef TEMP_RESIDENCY_TIME
  8662. SERIAL_PROTOCOLPGM(" W:");
  8663. if (residencyStart > -1)
  8664. {
  8665. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8666. SERIAL_PROTOCOLLN(codenum);
  8667. }
  8668. else
  8669. {
  8670. SERIAL_PROTOCOLLN('?');
  8671. }
  8672. }
  8673. #else
  8674. SERIAL_PROTOCOLLN();
  8675. #endif
  8676. codenum = _millis();
  8677. }
  8678. manage_heater();
  8679. manage_inactivity(true); //do not disable steppers
  8680. lcd_update(0);
  8681. #ifdef TEMP_RESIDENCY_TIME
  8682. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8683. or when current temp falls outside the hysteresis after target temp was reached */
  8684. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8685. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8686. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8687. {
  8688. residencyStart = _millis();
  8689. }
  8690. #endif //TEMP_RESIDENCY_TIME
  8691. }
  8692. }
  8693. void check_babystep()
  8694. {
  8695. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8696. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8697. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8698. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8699. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8700. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8701. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8702. babystep_z);
  8703. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8704. lcd_update_enable(true);
  8705. }
  8706. }
  8707. #ifdef HEATBED_ANALYSIS
  8708. void d_setup()
  8709. {
  8710. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8711. pinMode(D_DATA, INPUT_PULLUP);
  8712. pinMode(D_REQUIRE, OUTPUT);
  8713. digitalWrite(D_REQUIRE, HIGH);
  8714. }
  8715. float d_ReadData()
  8716. {
  8717. int digit[13];
  8718. String mergeOutput;
  8719. float output;
  8720. digitalWrite(D_REQUIRE, HIGH);
  8721. for (int i = 0; i<13; i++)
  8722. {
  8723. for (int j = 0; j < 4; j++)
  8724. {
  8725. while (digitalRead(D_DATACLOCK) == LOW) {}
  8726. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8727. bitWrite(digit[i], j, digitalRead(D_DATA));
  8728. }
  8729. }
  8730. digitalWrite(D_REQUIRE, LOW);
  8731. mergeOutput = "";
  8732. output = 0;
  8733. for (int r = 5; r <= 10; r++) //Merge digits
  8734. {
  8735. mergeOutput += digit[r];
  8736. }
  8737. output = mergeOutput.toFloat();
  8738. if (digit[4] == 8) //Handle sign
  8739. {
  8740. output *= -1;
  8741. }
  8742. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8743. {
  8744. output /= 10;
  8745. }
  8746. return output;
  8747. }
  8748. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8749. int t1 = 0;
  8750. int t_delay = 0;
  8751. int digit[13];
  8752. int m;
  8753. char str[3];
  8754. //String mergeOutput;
  8755. char mergeOutput[15];
  8756. float output;
  8757. int mesh_point = 0; //index number of calibration point
  8758. 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
  8759. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8760. float mesh_home_z_search = 4;
  8761. float measure_z_height = 0.2f;
  8762. float row[x_points_num];
  8763. int ix = 0;
  8764. int iy = 0;
  8765. const char* filename_wldsd = "mesh.txt";
  8766. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8767. char numb_wldsd[8]; // (" -A.BCD" + null)
  8768. #ifdef MICROMETER_LOGGING
  8769. d_setup();
  8770. #endif //MICROMETER_LOGGING
  8771. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8772. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8773. unsigned int custom_message_type_old = custom_message_type;
  8774. unsigned int custom_message_state_old = custom_message_state;
  8775. custom_message_type = CustomMsg::MeshBedLeveling;
  8776. custom_message_state = (x_points_num * y_points_num) + 10;
  8777. lcd_update(1);
  8778. //mbl.reset();
  8779. babystep_undo();
  8780. card.openFile(filename_wldsd, false);
  8781. /*destination[Z_AXIS] = mesh_home_z_search;
  8782. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8783. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8784. for(int8_t i=0; i < NUM_AXIS; i++) {
  8785. current_position[i] = destination[i];
  8786. }
  8787. st_synchronize();
  8788. */
  8789. destination[Z_AXIS] = measure_z_height;
  8790. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8791. for(int8_t i=0; i < NUM_AXIS; i++) {
  8792. current_position[i] = destination[i];
  8793. }
  8794. st_synchronize();
  8795. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8796. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8797. SERIAL_PROTOCOL(x_points_num);
  8798. SERIAL_PROTOCOLPGM(",");
  8799. SERIAL_PROTOCOL(y_points_num);
  8800. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8801. SERIAL_PROTOCOL(mesh_home_z_search);
  8802. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8803. SERIAL_PROTOCOL(x_dimension);
  8804. SERIAL_PROTOCOLPGM(",");
  8805. SERIAL_PROTOCOL(y_dimension);
  8806. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8807. while (mesh_point != x_points_num * y_points_num) {
  8808. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8809. iy = mesh_point / x_points_num;
  8810. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8811. float z0 = 0.f;
  8812. /*destination[Z_AXIS] = mesh_home_z_search;
  8813. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8814. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8815. for(int8_t i=0; i < NUM_AXIS; i++) {
  8816. current_position[i] = destination[i];
  8817. }
  8818. st_synchronize();*/
  8819. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8820. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8821. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8822. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8823. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8824. set_current_to_destination();
  8825. st_synchronize();
  8826. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8827. delay_keep_alive(1000);
  8828. #ifdef MICROMETER_LOGGING
  8829. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8830. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8831. //strcat(data_wldsd, numb_wldsd);
  8832. //MYSERIAL.println(data_wldsd);
  8833. //delay(1000);
  8834. //delay(3000);
  8835. //t1 = millis();
  8836. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8837. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8838. memset(digit, 0, sizeof(digit));
  8839. //cli();
  8840. digitalWrite(D_REQUIRE, LOW);
  8841. for (int i = 0; i<13; i++)
  8842. {
  8843. //t1 = millis();
  8844. for (int j = 0; j < 4; j++)
  8845. {
  8846. while (digitalRead(D_DATACLOCK) == LOW) {}
  8847. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8848. //printf_P(PSTR("Done %d\n"), j);
  8849. bitWrite(digit[i], j, digitalRead(D_DATA));
  8850. }
  8851. //t_delay = (millis() - t1);
  8852. //SERIAL_PROTOCOLPGM(" ");
  8853. //SERIAL_PROTOCOL_F(t_delay, 5);
  8854. //SERIAL_PROTOCOLPGM(" ");
  8855. }
  8856. //sei();
  8857. digitalWrite(D_REQUIRE, HIGH);
  8858. mergeOutput[0] = '\0';
  8859. output = 0;
  8860. for (int r = 5; r <= 10; r++) //Merge digits
  8861. {
  8862. sprintf(str, "%d", digit[r]);
  8863. strcat(mergeOutput, str);
  8864. }
  8865. output = atof(mergeOutput);
  8866. if (digit[4] == 8) //Handle sign
  8867. {
  8868. output *= -1;
  8869. }
  8870. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8871. {
  8872. output *= 0.1;
  8873. }
  8874. //output = d_ReadData();
  8875. //row[ix] = current_position[Z_AXIS];
  8876. //row[ix] = d_ReadData();
  8877. row[ix] = output;
  8878. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8879. memset(data_wldsd, 0, sizeof(data_wldsd));
  8880. for (int i = 0; i < x_points_num; i++) {
  8881. SERIAL_PROTOCOLPGM(" ");
  8882. SERIAL_PROTOCOL_F(row[i], 5);
  8883. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8884. dtostrf(row[i], 7, 3, numb_wldsd);
  8885. strcat(data_wldsd, numb_wldsd);
  8886. }
  8887. card.write_command(data_wldsd);
  8888. SERIAL_PROTOCOLPGM("\n");
  8889. }
  8890. custom_message_state--;
  8891. mesh_point++;
  8892. lcd_update(1);
  8893. }
  8894. #endif //MICROMETER_LOGGING
  8895. card.closefile();
  8896. //clean_up_after_endstop_move(l_feedmultiply);
  8897. }
  8898. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8899. int t1 = 0;
  8900. int t_delay = 0;
  8901. int digit[13];
  8902. int m;
  8903. char str[3];
  8904. //String mergeOutput;
  8905. char mergeOutput[15];
  8906. float output;
  8907. int mesh_point = 0; //index number of calibration point
  8908. 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
  8909. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8910. float mesh_home_z_search = 4;
  8911. float row[x_points_num];
  8912. int ix = 0;
  8913. int iy = 0;
  8914. const char* filename_wldsd = "wldsd.txt";
  8915. char data_wldsd[70];
  8916. char numb_wldsd[10];
  8917. d_setup();
  8918. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8919. // We don't know where we are! HOME!
  8920. // Push the commands to the front of the message queue in the reverse order!
  8921. // There shall be always enough space reserved for these commands.
  8922. repeatcommand_front(); // repeat G80 with all its parameters
  8923. enquecommand_front_P(G28W0);
  8924. enquecommand_front_P((PSTR("G1 Z5")));
  8925. return;
  8926. }
  8927. unsigned int custom_message_type_old = custom_message_type;
  8928. unsigned int custom_message_state_old = custom_message_state;
  8929. custom_message_type = CustomMsg::MeshBedLeveling;
  8930. custom_message_state = (x_points_num * y_points_num) + 10;
  8931. lcd_update(1);
  8932. mbl.reset();
  8933. babystep_undo();
  8934. card.openFile(filename_wldsd, false);
  8935. current_position[Z_AXIS] = mesh_home_z_search;
  8936. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8937. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8938. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8939. int l_feedmultiply = setup_for_endstop_move(false);
  8940. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8941. SERIAL_PROTOCOL(x_points_num);
  8942. SERIAL_PROTOCOLPGM(",");
  8943. SERIAL_PROTOCOL(y_points_num);
  8944. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8945. SERIAL_PROTOCOL(mesh_home_z_search);
  8946. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8947. SERIAL_PROTOCOL(x_dimension);
  8948. SERIAL_PROTOCOLPGM(",");
  8949. SERIAL_PROTOCOL(y_dimension);
  8950. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8951. while (mesh_point != x_points_num * y_points_num) {
  8952. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8953. iy = mesh_point / x_points_num;
  8954. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8955. float z0 = 0.f;
  8956. current_position[Z_AXIS] = mesh_home_z_search;
  8957. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8958. st_synchronize();
  8959. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8960. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8961. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8962. st_synchronize();
  8963. 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
  8964. break;
  8965. card.closefile();
  8966. }
  8967. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8968. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8969. //strcat(data_wldsd, numb_wldsd);
  8970. //MYSERIAL.println(data_wldsd);
  8971. //_delay(1000);
  8972. //_delay(3000);
  8973. //t1 = _millis();
  8974. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8975. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8976. memset(digit, 0, sizeof(digit));
  8977. //cli();
  8978. digitalWrite(D_REQUIRE, LOW);
  8979. for (int i = 0; i<13; i++)
  8980. {
  8981. //t1 = _millis();
  8982. for (int j = 0; j < 4; j++)
  8983. {
  8984. while (digitalRead(D_DATACLOCK) == LOW) {}
  8985. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8986. bitWrite(digit[i], j, digitalRead(D_DATA));
  8987. }
  8988. //t_delay = (_millis() - t1);
  8989. //SERIAL_PROTOCOLPGM(" ");
  8990. //SERIAL_PROTOCOL_F(t_delay, 5);
  8991. //SERIAL_PROTOCOLPGM(" ");
  8992. }
  8993. //sei();
  8994. digitalWrite(D_REQUIRE, HIGH);
  8995. mergeOutput[0] = '\0';
  8996. output = 0;
  8997. for (int r = 5; r <= 10; r++) //Merge digits
  8998. {
  8999. sprintf(str, "%d", digit[r]);
  9000. strcat(mergeOutput, str);
  9001. }
  9002. output = atof(mergeOutput);
  9003. if (digit[4] == 8) //Handle sign
  9004. {
  9005. output *= -1;
  9006. }
  9007. for (int i = digit[11]; i > 0; i--) //Handle floating point
  9008. {
  9009. output *= 0.1;
  9010. }
  9011. //output = d_ReadData();
  9012. //row[ix] = current_position[Z_AXIS];
  9013. memset(data_wldsd, 0, sizeof(data_wldsd));
  9014. for (int i = 0; i <3; i++) {
  9015. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9016. dtostrf(current_position[i], 8, 5, numb_wldsd);
  9017. strcat(data_wldsd, numb_wldsd);
  9018. strcat(data_wldsd, ";");
  9019. }
  9020. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9021. dtostrf(output, 8, 5, numb_wldsd);
  9022. strcat(data_wldsd, numb_wldsd);
  9023. //strcat(data_wldsd, ";");
  9024. card.write_command(data_wldsd);
  9025. //row[ix] = d_ReadData();
  9026. row[ix] = output; // current_position[Z_AXIS];
  9027. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  9028. for (int i = 0; i < x_points_num; i++) {
  9029. SERIAL_PROTOCOLPGM(" ");
  9030. SERIAL_PROTOCOL_F(row[i], 5);
  9031. }
  9032. SERIAL_PROTOCOLPGM("\n");
  9033. }
  9034. custom_message_state--;
  9035. mesh_point++;
  9036. lcd_update(1);
  9037. }
  9038. card.closefile();
  9039. clean_up_after_endstop_move(l_feedmultiply);
  9040. }
  9041. #endif //HEATBED_ANALYSIS
  9042. #ifndef PINDA_THERMISTOR
  9043. static void temp_compensation_start() {
  9044. custom_message_type = CustomMsg::TempCompPreheat;
  9045. custom_message_state = PINDA_HEAT_T + 1;
  9046. lcd_update(2);
  9047. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  9048. current_position[E_AXIS] -= default_retraction;
  9049. }
  9050. plan_buffer_line_curposXYZE(400, active_extruder);
  9051. current_position[X_AXIS] = PINDA_PREHEAT_X;
  9052. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  9053. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  9054. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  9055. st_synchronize();
  9056. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  9057. for (int i = 0; i < PINDA_HEAT_T; i++) {
  9058. delay_keep_alive(1000);
  9059. custom_message_state = PINDA_HEAT_T - i;
  9060. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  9061. else lcd_update(1);
  9062. }
  9063. custom_message_type = CustomMsg::Status;
  9064. custom_message_state = 0;
  9065. }
  9066. static void temp_compensation_apply() {
  9067. int i_add;
  9068. int z_shift = 0;
  9069. float z_shift_mm;
  9070. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  9071. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  9072. i_add = (target_temperature_bed - 60) / 10;
  9073. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  9074. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  9075. }else {
  9076. //interpolation
  9077. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  9078. }
  9079. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  9080. 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);
  9081. st_synchronize();
  9082. plan_set_z_position(current_position[Z_AXIS]);
  9083. }
  9084. else {
  9085. //we have no temp compensation data
  9086. }
  9087. }
  9088. #endif //ndef PINDA_THERMISTOR
  9089. float temp_comp_interpolation(float inp_temperature) {
  9090. //cubic spline interpolation
  9091. int n, i, j;
  9092. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  9093. int shift[10];
  9094. int temp_C[10];
  9095. n = 6; //number of measured points
  9096. shift[0] = 0;
  9097. for (i = 0; i < n; i++) {
  9098. if (i > 0) {
  9099. //read shift in steps from EEPROM
  9100. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  9101. }
  9102. temp_C[i] = 50 + i * 10; //temperature in C
  9103. #ifdef PINDA_THERMISTOR
  9104. constexpr int start_compensating_temp = 35;
  9105. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  9106. #ifdef SUPERPINDA_SUPPORT
  9107. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  9108. #endif //SUPERPINDA_SUPPORT
  9109. #else
  9110. temp_C[i] = 50 + i * 10; //temperature in C
  9111. #endif
  9112. x[i] = (float)temp_C[i];
  9113. f[i] = (float)shift[i];
  9114. }
  9115. if (inp_temperature < x[0]) return 0;
  9116. for (i = n - 1; i>0; i--) {
  9117. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9118. h[i - 1] = x[i] - x[i - 1];
  9119. }
  9120. //*********** formation of h, s , f matrix **************
  9121. for (i = 1; i<n - 1; i++) {
  9122. m[i][i] = 2 * (h[i - 1] + h[i]);
  9123. if (i != 1) {
  9124. m[i][i - 1] = h[i - 1];
  9125. m[i - 1][i] = h[i - 1];
  9126. }
  9127. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9128. }
  9129. //*********** forward elimination **************
  9130. for (i = 1; i<n - 2; i++) {
  9131. temp = (m[i + 1][i] / m[i][i]);
  9132. for (j = 1; j <= n - 1; j++)
  9133. m[i + 1][j] -= temp*m[i][j];
  9134. }
  9135. //*********** backward substitution *********
  9136. for (i = n - 2; i>0; i--) {
  9137. sum = 0;
  9138. for (j = i; j <= n - 2; j++)
  9139. sum += m[i][j] * s[j];
  9140. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9141. }
  9142. for (i = 0; i<n - 1; i++)
  9143. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9144. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9145. b = s[i] / 2;
  9146. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9147. d = f[i];
  9148. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9149. }
  9150. return sum;
  9151. }
  9152. #ifdef PINDA_THERMISTOR
  9153. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9154. {
  9155. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9156. if (!calibration_status_pinda()) return 0;
  9157. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9158. }
  9159. #endif //PINDA_THERMISTOR
  9160. void long_pause() //long pause print
  9161. {
  9162. st_synchronize();
  9163. start_pause_print = _millis();
  9164. // Stop heaters
  9165. heating_status = HeatingStatus::NO_HEATING;
  9166. setAllTargetHotends(0);
  9167. // Lift z
  9168. raise_z_above(current_position[Z_AXIS] + Z_PAUSE_LIFT, true);
  9169. // Move XY to side
  9170. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9171. current_position[X_AXIS] = X_PAUSE_POS;
  9172. current_position[Y_AXIS] = Y_PAUSE_POS;
  9173. plan_buffer_line_curposXYZE(50);
  9174. }
  9175. // did we come here from a thermal error?
  9176. if(get_temp_error()) {
  9177. // time to stop the error beep
  9178. WRITE(BEEPER, LOW);
  9179. } else {
  9180. // Turn off the print fan
  9181. fanSpeed = 0;
  9182. }
  9183. }
  9184. void serialecho_temperatures() {
  9185. float tt = degHotend(active_extruder);
  9186. SERIAL_PROTOCOLPGM("T:");
  9187. SERIAL_PROTOCOL(tt);
  9188. SERIAL_PROTOCOLPGM(" E:");
  9189. SERIAL_PROTOCOL((int)active_extruder);
  9190. SERIAL_PROTOCOLPGM(" B:");
  9191. SERIAL_PROTOCOL_F(degBed(), 1);
  9192. SERIAL_PROTOCOLLN();
  9193. }
  9194. #ifdef UVLO_SUPPORT
  9195. void uvlo_drain_reset()
  9196. {
  9197. // burn all that residual power
  9198. wdt_enable(WDTO_1S);
  9199. WRITE(BEEPER,HIGH);
  9200. lcd_clear();
  9201. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9202. while(1);
  9203. }
  9204. void uvlo_()
  9205. {
  9206. unsigned long time_start = _millis();
  9207. bool sd_print = card.sdprinting;
  9208. // Conserve power as soon as possible.
  9209. #ifdef LCD_BL_PIN
  9210. backlightMode = BACKLIGHT_MODE_DIM;
  9211. backlightLevel_LOW = 0;
  9212. backlight_update();
  9213. #endif //LCD_BL_PIN
  9214. disable_x();
  9215. disable_y();
  9216. #ifdef TMC2130
  9217. tmc2130_set_current_h(Z_AXIS, 20);
  9218. tmc2130_set_current_r(Z_AXIS, 20);
  9219. tmc2130_set_current_h(E_AXIS, 20);
  9220. tmc2130_set_current_r(E_AXIS, 20);
  9221. #endif //TMC2130
  9222. // Stop all heaters
  9223. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9224. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9225. setAllTargetHotends(0);
  9226. setTargetBed(0);
  9227. // Calculate the file position, from which to resume this print.
  9228. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9229. {
  9230. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9231. sd_position -= sdlen_planner;
  9232. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9233. sd_position -= sdlen_cmdqueue;
  9234. if (sd_position < 0) sd_position = 0;
  9235. }
  9236. // save the global state at planning time
  9237. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9238. uint16_t feedrate_bckp;
  9239. if (current_block && !pos_invalid)
  9240. {
  9241. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9242. feedrate_bckp = current_block->gcode_feedrate;
  9243. saved_segment_idx = current_block->segment_idx;
  9244. }
  9245. else
  9246. {
  9247. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9248. feedrate_bckp = feedrate;
  9249. saved_segment_idx = 0;
  9250. }
  9251. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9252. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9253. // get the physical Z for further manipulation.
  9254. bool mbl_was_active = mbl.active;
  9255. mbl.active = false;
  9256. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9257. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9258. // are in action.
  9259. planner_abort_hard();
  9260. // Store the print logical Z position, which we need to recover (a slight error here would be
  9261. // recovered on the next Gcode instruction, while a physical location error would not)
  9262. float logical_z = current_position[Z_AXIS];
  9263. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9264. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9265. // Store the print E position before we lose track
  9266. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9267. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9268. // Clean the input command queue, inhibit serial processing using saved_printing
  9269. cmdqueue_reset();
  9270. card.sdprinting = false;
  9271. saved_printing = true;
  9272. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9273. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9274. planner_aborted = false;
  9275. sei();
  9276. // Retract
  9277. current_position[E_AXIS] -= default_retraction;
  9278. plan_buffer_line_curposXYZE(95);
  9279. st_synchronize();
  9280. disable_e0();
  9281. // Read out the current Z motor microstep counter to move the axis up towards
  9282. // a full step before powering off. NOTE: we need to ensure to schedule more
  9283. // than "dropsegments" steps in order to move (this is always the case here
  9284. // due to UVLO_Z_AXIS_SHIFT being used)
  9285. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9286. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9287. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9288. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9289. + UVLO_Z_AXIS_SHIFT;
  9290. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9291. st_synchronize();
  9292. poweroff_z();
  9293. // Write the file position.
  9294. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9295. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9296. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9297. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9298. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9299. // Scale the z value to 1u resolution.
  9300. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9301. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9302. }
  9303. // Write the _final_ Z position and motor microstep counter (unused).
  9304. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9305. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9306. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9307. // Store the current position.
  9308. if (pos_invalid)
  9309. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9310. else
  9311. {
  9312. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9313. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9314. }
  9315. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9316. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9317. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9318. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9319. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9320. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9321. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9322. #if EXTRUDERS > 1
  9323. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9324. #if EXTRUDERS > 2
  9325. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9326. #endif
  9327. #endif
  9328. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9329. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9330. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9331. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9332. // Store the saved target
  9333. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9334. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9335. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9336. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9337. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9338. #ifdef LIN_ADVANCE
  9339. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9340. #endif
  9341. // Finaly store the "power outage" flag.
  9342. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9343. // Increment power failure counter
  9344. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9345. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9346. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9347. WRITE(BEEPER,HIGH);
  9348. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9349. poweron_z();
  9350. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9351. plan_buffer_line_curposXYZE(500);
  9352. st_synchronize();
  9353. wdt_enable(WDTO_1S);
  9354. while(1);
  9355. }
  9356. void uvlo_tiny()
  9357. {
  9358. unsigned long time_start = _millis();
  9359. // Conserve power as soon as possible.
  9360. disable_x();
  9361. disable_y();
  9362. disable_e0();
  9363. #ifdef TMC2130
  9364. tmc2130_set_current_h(Z_AXIS, 20);
  9365. tmc2130_set_current_r(Z_AXIS, 20);
  9366. #endif //TMC2130
  9367. // Stop all heaters
  9368. setAllTargetHotends(0);
  9369. setTargetBed(0);
  9370. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9371. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9372. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9373. // Disable MBL (if not already) to work with physical coordinates.
  9374. mbl.active = false;
  9375. planner_abort_hard();
  9376. // Allow for small roundoffs to be ignored
  9377. 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])
  9378. {
  9379. // Clean the input command queue, inhibit serial processing using saved_printing
  9380. cmdqueue_reset();
  9381. card.sdprinting = false;
  9382. saved_printing = true;
  9383. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9384. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9385. planner_aborted = false;
  9386. sei();
  9387. // The axis was moved: adjust Z as done on a regular UVLO.
  9388. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9389. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9390. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9391. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9392. + UVLO_TINY_Z_AXIS_SHIFT;
  9393. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9394. st_synchronize();
  9395. poweroff_z();
  9396. // Update Z position
  9397. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9398. // Update the _final_ Z motor microstep counter (unused).
  9399. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9400. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9401. }
  9402. // Update the the "power outage" flag.
  9403. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9404. // Increment power failure counter
  9405. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9406. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9407. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9408. uvlo_drain_reset();
  9409. }
  9410. #endif //UVLO_SUPPORT
  9411. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9412. void setup_fan_interrupt() {
  9413. //INT7
  9414. DDRE &= ~(1 << 7); //input pin
  9415. PORTE &= ~(1 << 7); //no internal pull-up
  9416. //start with sensing rising edge
  9417. EICRB &= ~(1 << 6);
  9418. EICRB |= (1 << 7);
  9419. //enable INT7 interrupt
  9420. EIMSK |= (1 << 7);
  9421. }
  9422. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9423. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9424. ISR(INT7_vect) {
  9425. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9426. #ifdef FAN_SOFT_PWM
  9427. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9428. #else //FAN_SOFT_PWM
  9429. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9430. #endif //FAN_SOFT_PWM
  9431. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9432. t_fan_rising_edge = millis_nc();
  9433. }
  9434. else { //interrupt was triggered by falling edge
  9435. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9436. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9437. }
  9438. }
  9439. EICRB ^= (1 << 6); //change edge
  9440. }
  9441. #endif
  9442. #ifdef UVLO_SUPPORT
  9443. void setup_uvlo_interrupt() {
  9444. DDRE &= ~(1 << 4); //input pin
  9445. PORTE &= ~(1 << 4); //no internal pull-up
  9446. // sensing falling edge
  9447. EICRB |= (1 << 0);
  9448. EICRB &= ~(1 << 1);
  9449. // enable INT4 interrupt
  9450. EIMSK |= (1 << 4);
  9451. // check if power was lost before we armed the interrupt
  9452. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9453. {
  9454. SERIAL_ECHOLNPGM("INT4");
  9455. uvlo_drain_reset();
  9456. }
  9457. }
  9458. ISR(INT4_vect) {
  9459. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9460. SERIAL_ECHOLNPGM("INT4");
  9461. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9462. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9463. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9464. }
  9465. void recover_print(uint8_t automatic) {
  9466. char cmd[30];
  9467. lcd_update_enable(true);
  9468. lcd_update(2);
  9469. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9470. // Recover position, temperatures and extrude_multipliers
  9471. bool mbl_was_active = recover_machine_state_after_power_panic();
  9472. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9473. // and second also so one may remove the excess priming material.
  9474. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9475. {
  9476. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9477. enquecommand(cmd);
  9478. }
  9479. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9480. // transformation status. G28 will not touch Z when MBL is off.
  9481. enquecommand_P(PSTR("G28 X Y"));
  9482. // Set the target bed and nozzle temperatures and wait.
  9483. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9484. enquecommand(cmd);
  9485. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9486. enquecommand(cmd);
  9487. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9488. enquecommand(cmd);
  9489. enquecommand_P(PSTR("M83")); //E axis relative mode
  9490. // If not automatically recoreverd (long power loss)
  9491. if(automatic == 0){
  9492. //Extrude some filament to stabilize the pressure
  9493. enquecommand_P(PSTR("G1 E5 F120"));
  9494. // Retract to be consistent with a short pause
  9495. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9496. enquecommand(cmd);
  9497. }
  9498. 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]);
  9499. // Restart the print.
  9500. restore_print_from_eeprom(mbl_was_active);
  9501. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9502. }
  9503. bool recover_machine_state_after_power_panic()
  9504. {
  9505. // 1) Preset some dummy values for the XY axes
  9506. current_position[X_AXIS] = 0;
  9507. current_position[Y_AXIS] = 0;
  9508. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9509. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9510. bool mbl_was_active = false;
  9511. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9512. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9513. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9514. // Scale the z value to 10u resolution.
  9515. int16_t v;
  9516. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9517. if (v != 0)
  9518. mbl_was_active = true;
  9519. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9520. }
  9521. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9522. // The current position after power panic is moved to the next closest 0th full step.
  9523. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9524. // Recover last E axis position
  9525. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9526. // 3) Initialize the logical to physical coordinate system transformation.
  9527. world2machine_initialize();
  9528. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9529. // print_mesh_bed_leveling_table();
  9530. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9531. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9532. babystep_load();
  9533. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9534. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9535. clamp_to_software_endstops(current_position);
  9536. set_destination_to_current();
  9537. plan_set_position_curposXYZE();
  9538. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9539. print_world_coordinates();
  9540. // 6) Power up the Z motors, mark their positions as known.
  9541. axis_known_position[Z_AXIS] = true;
  9542. enable_z();
  9543. // 7) Recover the target temperatures.
  9544. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9545. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9546. // 8) Recover extruder multipilers
  9547. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9548. #if EXTRUDERS > 1
  9549. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9550. #if EXTRUDERS > 2
  9551. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9552. #endif
  9553. #endif
  9554. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9555. // 9) Recover the saved target
  9556. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9557. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9558. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9559. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9560. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9561. #ifdef LIN_ADVANCE
  9562. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9563. #endif
  9564. return mbl_was_active;
  9565. }
  9566. void restore_print_from_eeprom(bool mbl_was_active) {
  9567. int feedrate_rec;
  9568. int feedmultiply_rec;
  9569. uint8_t fan_speed_rec;
  9570. char cmd[48];
  9571. char filename[FILENAME_LENGTH];
  9572. uint8_t depth = 0;
  9573. char dir_name[9];
  9574. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9575. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9576. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9577. SERIAL_ECHOPGM("Feedrate:");
  9578. MYSERIAL.print(feedrate_rec);
  9579. SERIAL_ECHOPGM(", feedmultiply:");
  9580. MYSERIAL.println(feedmultiply_rec);
  9581. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9582. MYSERIAL.println(int(depth));
  9583. for (uint8_t i = 0; i < depth; i++) {
  9584. for (uint8_t j = 0; j < 8; j++) {
  9585. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9586. }
  9587. dir_name[8] = '\0';
  9588. MYSERIAL.println(dir_name);
  9589. // strcpy(card.dir_names[i], dir_name);
  9590. card.chdir(dir_name, false);
  9591. }
  9592. for (uint8_t i = 0; i < 8; i++) {
  9593. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9594. }
  9595. filename[8] = '\0';
  9596. MYSERIAL.print(filename);
  9597. strcat_P(filename, PSTR(".gco"));
  9598. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9599. enquecommand(cmd);
  9600. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9601. SERIAL_ECHOPGM("Position read from eeprom:");
  9602. MYSERIAL.println(position);
  9603. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9604. // without shifting Z along the way. This requires performing the move without mbl.
  9605. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9606. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9607. if (pos_x != X_COORD_INVALID)
  9608. {
  9609. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9610. enquecommand(cmd);
  9611. }
  9612. // Enable MBL and switch to logical positioning
  9613. if (mbl_was_active)
  9614. enquecommand_P(PSTR("PRUSA MBL V1"));
  9615. // Move the Z axis down to the print, in logical coordinates.
  9616. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9617. enquecommand(cmd);
  9618. // Restore acceleration settings
  9619. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9620. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9621. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9622. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9623. enquecommand(cmd);
  9624. // Unretract.
  9625. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9626. enquecommand(cmd);
  9627. // Recover final E axis position and mode
  9628. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9629. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9630. enquecommand(cmd);
  9631. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9632. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9633. // Set the feedrates saved at the power panic.
  9634. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9635. enquecommand(cmd);
  9636. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9637. enquecommand(cmd);
  9638. // Set the fan speed saved at the power panic.
  9639. strcpy_P(cmd, PSTR("M106 S"));
  9640. strcat(cmd, itostr3(int(fan_speed_rec)));
  9641. enquecommand(cmd);
  9642. // Set a position in the file.
  9643. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9644. enquecommand(cmd);
  9645. enquecommand_P(PSTR("G4 S0"));
  9646. enquecommand_P(PSTR("PRUSA uvlo"));
  9647. }
  9648. #endif //UVLO_SUPPORT
  9649. //! @brief Immediately stop print moves
  9650. //!
  9651. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9652. //! If printing from sd card, position in file is saved.
  9653. //! If printing from USB, line number is saved.
  9654. //!
  9655. //! @param z_move
  9656. //! @param e_move
  9657. void stop_and_save_print_to_ram(float z_move, float e_move)
  9658. {
  9659. if (saved_printing) return;
  9660. #if 0
  9661. unsigned char nplanner_blocks;
  9662. #endif
  9663. unsigned char nlines;
  9664. uint16_t sdlen_planner;
  9665. uint16_t sdlen_cmdqueue;
  9666. cli();
  9667. if (card.sdprinting) {
  9668. #if 0
  9669. nplanner_blocks = number_of_blocks();
  9670. #endif
  9671. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9672. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9673. saved_sdpos -= sdlen_planner;
  9674. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9675. saved_sdpos -= sdlen_cmdqueue;
  9676. saved_printing_type = PRINTING_TYPE_SD;
  9677. }
  9678. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9679. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9680. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9681. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9682. saved_sdpos -= nlines;
  9683. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9684. saved_printing_type = PRINTING_TYPE_USB;
  9685. }
  9686. else {
  9687. saved_printing_type = PRINTING_TYPE_NONE;
  9688. //not sd printing nor usb printing
  9689. }
  9690. #if 0
  9691. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9692. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9693. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9694. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9695. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9696. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9697. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9698. {
  9699. card.setIndex(saved_sdpos);
  9700. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9701. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9702. MYSERIAL.print(char(card.get()));
  9703. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9704. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9705. MYSERIAL.print(char(card.get()));
  9706. SERIAL_ECHOLNPGM("End of command buffer");
  9707. }
  9708. {
  9709. // Print the content of the planner buffer, line by line:
  9710. card.setIndex(saved_sdpos);
  9711. int8_t iline = 0;
  9712. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9713. SERIAL_ECHOPGM("Planner line (from file): ");
  9714. MYSERIAL.print(int(iline), DEC);
  9715. SERIAL_ECHOPGM(", length: ");
  9716. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9717. SERIAL_ECHOPGM(", steps: (");
  9718. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9719. SERIAL_ECHOPGM(",");
  9720. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9721. SERIAL_ECHOPGM(",");
  9722. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9723. SERIAL_ECHOPGM(",");
  9724. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9725. SERIAL_ECHOPGM("), events: ");
  9726. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9727. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9728. MYSERIAL.print(char(card.get()));
  9729. }
  9730. }
  9731. {
  9732. // Print the content of the command buffer, line by line:
  9733. int8_t iline = 0;
  9734. union {
  9735. struct {
  9736. char lo;
  9737. char hi;
  9738. } lohi;
  9739. uint16_t value;
  9740. } sdlen_single;
  9741. int _bufindr = bufindr;
  9742. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9743. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9744. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9745. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9746. }
  9747. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9748. MYSERIAL.print(int(iline), DEC);
  9749. SERIAL_ECHOPGM(", type: ");
  9750. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9751. SERIAL_ECHOPGM(", len: ");
  9752. MYSERIAL.println(sdlen_single.value, DEC);
  9753. // Print the content of the buffer line.
  9754. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9755. SERIAL_ECHOPGM("Buffer line (from file): ");
  9756. MYSERIAL.println(int(iline), DEC);
  9757. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9758. MYSERIAL.print(char(card.get()));
  9759. if (-- _buflen == 0)
  9760. break;
  9761. // First skip the current command ID and iterate up to the end of the string.
  9762. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9763. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9764. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9765. // If the end of the buffer was empty,
  9766. if (_bufindr == sizeof(cmdbuffer)) {
  9767. // skip to the start and find the nonzero command.
  9768. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9769. }
  9770. }
  9771. }
  9772. #endif
  9773. // save the global state at planning time
  9774. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9775. if (current_block && !pos_invalid)
  9776. {
  9777. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9778. saved_feedrate2 = current_block->gcode_feedrate;
  9779. saved_segment_idx = current_block->segment_idx;
  9780. // 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);
  9781. }
  9782. else
  9783. {
  9784. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9785. saved_feedrate2 = feedrate;
  9786. saved_segment_idx = 0;
  9787. }
  9788. planner_abort_hard(); //abort printing
  9789. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9790. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9791. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9792. saved_extruder_temperature = degTargetHotend(active_extruder);
  9793. saved_bed_temperature = degTargetBed();
  9794. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9795. saved_fan_speed = fanSpeed;
  9796. cmdqueue_reset(); //empty cmdqueue
  9797. card.sdprinting = false;
  9798. // card.closefile();
  9799. saved_printing = true;
  9800. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9801. st_reset_timer();
  9802. sei();
  9803. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9804. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9805. // the caller can continue processing. This is used during powerpanic to save the state as we
  9806. // move away from the print.
  9807. char buf[48];
  9808. if(e_move)
  9809. {
  9810. // First unretract (relative extrusion)
  9811. if(!saved_extruder_relative_mode){
  9812. enquecommand(PSTR("M83"), true);
  9813. }
  9814. //retract 45mm/s
  9815. // A single sprintf may not be faster, but is definitely 20B shorter
  9816. // than a sequence of commands building the string piece by piece
  9817. // A snprintf would have been a safer call, but since it is not used
  9818. // in the whole program, its implementation would bring more bytes to the total size
  9819. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9820. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9821. enquecommand(buf, false);
  9822. }
  9823. if(z_move)
  9824. {
  9825. // Then lift Z axis
  9826. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9827. enquecommand(buf, false);
  9828. }
  9829. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9830. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9831. repeatcommand_front();
  9832. }
  9833. }
  9834. void restore_extruder_temperature_from_ram() {
  9835. if (degTargetHotend(active_extruder) != saved_extruder_temperature)
  9836. {
  9837. setTargetHotendSafe(saved_extruder_temperature, active_extruder);
  9838. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9839. wait_for_heater(_millis(), active_extruder);
  9840. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9841. }
  9842. }
  9843. //! @brief Restore print from ram
  9844. //!
  9845. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9846. //! print fan speed, waits for extruder temperature restore, then restores
  9847. //! position and continues print moves.
  9848. //!
  9849. //! Internally lcd_update() is called by wait_for_heater().
  9850. //!
  9851. //! @param e_move
  9852. void restore_print_from_ram_and_continue(float e_move)
  9853. {
  9854. if (!saved_printing) return;
  9855. #ifdef FANCHECK
  9856. // Do not allow resume printing if fans are still not ok
  9857. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9858. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9859. #endif
  9860. // restore bed temperature (bed can be disabled during a thermal warning)
  9861. if (degBed() != saved_bed_temperature)
  9862. setTargetBed(saved_bed_temperature);
  9863. fanSpeed = saved_fan_speed;
  9864. restore_extruder_temperature_from_ram();
  9865. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9866. float e = saved_pos[E_AXIS] - e_move;
  9867. plan_set_e_position(e);
  9868. #ifdef FANCHECK
  9869. fans_check_enabled = false;
  9870. #endif
  9871. // do not restore XY for commands that do not require that
  9872. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9873. {
  9874. saved_pos[X_AXIS] = current_position[X_AXIS];
  9875. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9876. }
  9877. //first move print head in XY to the saved position:
  9878. 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);
  9879. //then move Z
  9880. 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);
  9881. //and finaly unretract (35mm/s)
  9882. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9883. st_synchronize();
  9884. #ifdef FANCHECK
  9885. fans_check_enabled = true;
  9886. #endif
  9887. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9888. feedrate = saved_feedrate2;
  9889. feedmultiply = saved_feedmultiply2;
  9890. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9891. set_destination_to_current();
  9892. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9893. card.setIndex(saved_sdpos);
  9894. sdpos_atomic = saved_sdpos;
  9895. card.sdprinting = true;
  9896. }
  9897. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9898. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9899. serial_count = 0;
  9900. FlushSerialRequestResend();
  9901. }
  9902. else {
  9903. //not sd printing nor usb printing
  9904. }
  9905. lcd_setstatuspgm(MSG_WELCOME);
  9906. saved_printing_type = PRINTING_TYPE_NONE;
  9907. saved_printing = false;
  9908. planner_aborted = true; // unroll the stack
  9909. }
  9910. // Cancel the state related to a currently saved print
  9911. void cancel_saved_printing()
  9912. {
  9913. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9914. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9915. saved_printing_type = PRINTING_TYPE_NONE;
  9916. saved_printing = false;
  9917. }
  9918. void print_world_coordinates()
  9919. {
  9920. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9921. }
  9922. void print_physical_coordinates()
  9923. {
  9924. 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));
  9925. }
  9926. void print_mesh_bed_leveling_table()
  9927. {
  9928. SERIAL_ECHOPGM("mesh bed leveling: ");
  9929. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9930. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9931. MYSERIAL.print(mbl.z_values[y][x], 3);
  9932. SERIAL_ECHO(' ');
  9933. }
  9934. SERIAL_ECHOLN();
  9935. }
  9936. uint8_t calc_percent_done()
  9937. {
  9938. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9939. uint8_t percent_done = 0;
  9940. #ifdef TMC2130
  9941. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9942. {
  9943. percent_done = print_percent_done_normal;
  9944. }
  9945. else if (print_percent_done_silent <= 100)
  9946. {
  9947. percent_done = print_percent_done_silent;
  9948. }
  9949. #else
  9950. if (print_percent_done_normal <= 100)
  9951. {
  9952. percent_done = print_percent_done_normal;
  9953. }
  9954. #endif //TMC2130
  9955. else
  9956. {
  9957. percent_done = card.percentDone();
  9958. }
  9959. return percent_done;
  9960. }
  9961. static void print_time_remaining_init()
  9962. {
  9963. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9964. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9965. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9966. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9967. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9968. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9969. }
  9970. void load_filament_final_feed()
  9971. {
  9972. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9973. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9974. }
  9975. //! @brief Wait for user to check the state
  9976. //! @par nozzle_temp nozzle temperature to load filament
  9977. void M600_check_state(float nozzle_temp)
  9978. {
  9979. lcd_change_fil_state = 0;
  9980. while (lcd_change_fil_state != 1)
  9981. {
  9982. lcd_change_fil_state = 0;
  9983. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9984. lcd_alright();
  9985. KEEPALIVE_STATE(IN_HANDLER);
  9986. switch(lcd_change_fil_state)
  9987. {
  9988. // Filament failed to load so load it again
  9989. case 2:
  9990. if (MMU2::mmu2.Enabled()){
  9991. // Unload filament
  9992. mmu_M600_unload_filament();
  9993. // Ask to remove any old filament and load new
  9994. mmu_M600_wait_and_beep();
  9995. // After user clicks knob, MMU will load the filament
  9996. mmu_M600_load_filament(false, nozzle_temp);
  9997. } else {
  9998. M600_load_filament_movements();
  9999. }
  10000. break;
  10001. // Filament loaded properly but color is not clear
  10002. case 3:
  10003. st_synchronize();
  10004. load_filament_final_feed();
  10005. lcd_loading_color();
  10006. st_synchronize();
  10007. break;
  10008. // Everything good
  10009. default:
  10010. lcd_change_success();
  10011. break;
  10012. }
  10013. }
  10014. }
  10015. //! @brief Wait for user action
  10016. //!
  10017. //! Beep, manage nozzle heater and wait for user to start unload filament
  10018. //! If times out, active extruder temperature is set to 0.
  10019. //!
  10020. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  10021. void M600_wait_for_user(float HotendTempBckp) {
  10022. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10023. int counterBeep = 0;
  10024. unsigned long waiting_start_time = _millis();
  10025. uint8_t wait_for_user_state = 0;
  10026. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10027. bool bFirst=true;
  10028. while (!(wait_for_user_state == 0 && lcd_clicked())){
  10029. manage_heater();
  10030. manage_inactivity(true);
  10031. #if BEEPER > 0
  10032. if (counterBeep == 500) {
  10033. counterBeep = 0;
  10034. }
  10035. SET_OUTPUT(BEEPER);
  10036. if (counterBeep == 0) {
  10037. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  10038. {
  10039. bFirst=false;
  10040. WRITE(BEEPER, HIGH);
  10041. }
  10042. }
  10043. if (counterBeep == 20) {
  10044. WRITE(BEEPER, LOW);
  10045. }
  10046. counterBeep++;
  10047. #endif //BEEPER > 0
  10048. switch (wait_for_user_state) {
  10049. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  10050. delay_keep_alive(4);
  10051. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  10052. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  10053. wait_for_user_state = 1;
  10054. setAllTargetHotends(0);
  10055. st_synchronize();
  10056. disable_e0();
  10057. disable_e1();
  10058. disable_e2();
  10059. }
  10060. break;
  10061. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  10062. delay_keep_alive(4);
  10063. if (lcd_clicked()) {
  10064. setTargetHotend(HotendTempBckp, active_extruder);
  10065. lcd_wait_for_heater();
  10066. wait_for_user_state = 2;
  10067. }
  10068. break;
  10069. case 2: //waiting for nozzle to reach target temperature
  10070. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  10071. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10072. waiting_start_time = _millis();
  10073. wait_for_user_state = 0;
  10074. }
  10075. else {
  10076. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  10077. lcd_set_cursor(1, 4);
  10078. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  10079. }
  10080. break;
  10081. }
  10082. }
  10083. WRITE(BEEPER, LOW);
  10084. }
  10085. void M600_load_filament_movements()
  10086. {
  10087. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  10088. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  10089. load_filament_final_feed();
  10090. lcd_loading_filament();
  10091. st_synchronize();
  10092. }
  10093. void M600_load_filament() {
  10094. //load filament for single material and MMU
  10095. lcd_wait_interact();
  10096. //load_filament_time = _millis();
  10097. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10098. while(!lcd_clicked())
  10099. {
  10100. manage_heater();
  10101. manage_inactivity(true);
  10102. #ifdef FILAMENT_SENSOR
  10103. if (fsensor.getFilamentLoadEvent()) {
  10104. Sound_MakeCustom(50,1000,false);
  10105. break;
  10106. }
  10107. #endif //FILAMENT_SENSOR
  10108. }
  10109. KEEPALIVE_STATE(IN_HANDLER);
  10110. M600_load_filament_movements();
  10111. Sound_MakeCustom(50,1000,false);
  10112. lcd_update_enable(false);
  10113. }
  10114. //! @brief Wait for click
  10115. //!
  10116. //! Set
  10117. void marlin_wait_for_click()
  10118. {
  10119. int8_t busy_state_backup = busy_state;
  10120. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10121. lcd_consume_click();
  10122. while(!lcd_clicked())
  10123. {
  10124. manage_heater();
  10125. manage_inactivity(true);
  10126. lcd_update(0);
  10127. }
  10128. KEEPALIVE_STATE(busy_state_backup);
  10129. }
  10130. #define FIL_LOAD_LENGTH 60
  10131. #ifdef PSU_Delta
  10132. bool bEnableForce_z;
  10133. void init_force_z()
  10134. {
  10135. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10136. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10137. disable_force_z();
  10138. }
  10139. void check_force_z()
  10140. {
  10141. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10142. init_force_z(); // causes enforced switching into disable-state
  10143. }
  10144. void disable_force_z()
  10145. {
  10146. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10147. bEnableForce_z=false;
  10148. // switching to silent mode
  10149. #ifdef TMC2130
  10150. tmc2130_mode=TMC2130_MODE_SILENT;
  10151. update_mode_profile();
  10152. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10153. #endif // TMC2130
  10154. }
  10155. void enable_force_z()
  10156. {
  10157. if(bEnableForce_z)
  10158. return; // motor already enabled (may be ;-p )
  10159. bEnableForce_z=true;
  10160. // mode recovering
  10161. #ifdef TMC2130
  10162. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10163. update_mode_profile();
  10164. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10165. #endif // TMC2130
  10166. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10167. }
  10168. #endif // PSU_Delta