Marlin_main.cpp 386 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615
  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 "SpoolJoin.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. unsigned long pause_time = 0;
  153. unsigned long start_pause_print = _millis();
  154. unsigned long t_fan_rising_edge = _millis();
  155. LongTimer safetyTimer;
  156. static LongTimer crashDetTimer;
  157. //unsigned long load_filament_time;
  158. bool mesh_bed_leveling_flag = false;
  159. unsigned long total_filament_used;
  160. HeatingStatus heating_status;
  161. uint8_t heating_status_counter;
  162. bool loading_flag = false;
  163. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  164. bool fan_state[2];
  165. int fan_edge_counter[2];
  166. int fan_speed[2];
  167. float extruder_multiplier[EXTRUDERS] = {1.0
  168. #if EXTRUDERS > 1
  169. , 1.0
  170. #if EXTRUDERS > 2
  171. , 1.0
  172. #endif
  173. #endif
  174. };
  175. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  176. //shortcuts for more readable code
  177. #define _x current_position[X_AXIS]
  178. #define _y current_position[Y_AXIS]
  179. #define _z current_position[Z_AXIS]
  180. #define _e current_position[E_AXIS]
  181. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  182. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  183. bool axis_known_position[3] = {false, false, false};
  184. // Extruder offset
  185. #if EXTRUDERS > 1
  186. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  187. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  188. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  189. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  190. #endif
  191. };
  192. #endif
  193. int fanSpeed=0;
  194. uint8_t newFanSpeed = 0;
  195. #ifdef FWRETRACT
  196. bool retracted[EXTRUDERS]={false
  197. #if EXTRUDERS > 1
  198. , false
  199. #if EXTRUDERS > 2
  200. , false
  201. #endif
  202. #endif
  203. };
  204. bool retracted_swap[EXTRUDERS]={false
  205. #if EXTRUDERS > 1
  206. , false
  207. #if EXTRUDERS > 2
  208. , false
  209. #endif
  210. #endif
  211. };
  212. float retract_length_swap = RETRACT_LENGTH_SWAP;
  213. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  214. #endif
  215. #ifdef PS_DEFAULT_OFF
  216. bool powersupply = false;
  217. #else
  218. bool powersupply = true;
  219. #endif
  220. bool cancel_heatup = false;
  221. int8_t busy_state = NOT_BUSY;
  222. static long prev_busy_signal_ms = -1;
  223. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  224. const char errormagic[] PROGMEM = "Error:";
  225. const char echomagic[] PROGMEM = "echo:";
  226. const char G28W0[] PROGMEM = "G28 W0";
  227. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  228. // that they can be used later for various logical checks
  229. #define X_COORD_INVALID (X_MIN_POS-1)
  230. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  231. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  232. uint16_t saved_segment_idx = 0;
  233. // storing estimated time to end of print counted by slicer
  234. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  235. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  236. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  237. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  238. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  239. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  240. uint32_t IP_address = 0;
  241. //===========================================================================
  242. //=============================Private Variables=============================
  243. //===========================================================================
  244. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  245. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  246. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  247. // For tracing an arc
  248. static float offset[3] = {0.0, 0.0, 0.0};
  249. // Current feedrate
  250. float feedrate = 1500.0;
  251. // Feedrate for the next move
  252. static float next_feedrate;
  253. // Original feedrate saved during homing moves
  254. static float saved_feedrate;
  255. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  256. //static float tt = 0;
  257. //static float bt = 0;
  258. //Inactivity shutdown variables
  259. static LongTimer previous_millis_cmd;
  260. unsigned long max_inactive_time = 0;
  261. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  262. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  263. unsigned long starttime=0;
  264. unsigned long stoptime=0;
  265. ShortTimer usb_timer;
  266. bool Stopped=false;
  267. #if NUM_SERVOS > 0
  268. Servo servos[NUM_SERVOS];
  269. #endif
  270. bool target_direction;
  271. //Insert variables if CHDK is defined
  272. #ifdef CHDK
  273. unsigned long chdkHigh = 0;
  274. bool chdkActive = false;
  275. #endif
  276. //! @name RAM save/restore printing
  277. //! @{
  278. bool saved_printing = false; //!< Print is paused and saved in RAM
  279. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  280. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  281. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  282. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  283. static int saved_feedmultiply2 = 0;
  284. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  285. float saved_bed_temperature = 0.0;
  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. || MMU2::mmu2.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_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_X);
  498. eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT);
  499. }
  500. if (mask & Y_AXIS_MASK)
  501. {
  502. eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_Y);
  503. eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT);
  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. failstats_reset_print();
  575. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  576. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  577. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  578. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  579. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  580. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  581. eeprom_update_dword((uint32_t *)EEPROM_TOTAL_TOOLCHANGE_COUNT, 0);
  582. }
  583. // Factory reset function
  584. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  585. // Level input parameter sets depth of reset
  586. static void factory_reset(char level)
  587. {
  588. lcd_clear();
  589. Sound_MakeCustom(100,0,false);
  590. switch (level) {
  591. case 0: // Level 0: Language reset
  592. lang_reset();
  593. break;
  594. case 1: //Level 1: Reset statistics
  595. factory_reset_stats();
  596. lcd_menu_statistics();
  597. break;
  598. case 2: // Level 2: Prepare for shipping
  599. factory_reset_stats();
  600. // FALLTHRU
  601. case 3: // Level 3: Preparation after being serviced
  602. // Force language selection at the next boot up.
  603. lang_reset();
  604. // Force the "Follow calibration flow" message at the next boot up.
  605. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  606. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  607. farm_disable();
  608. #ifdef FILAMENT_SENSOR
  609. fsensor.setEnabled(true);
  610. fsensor.setAutoLoadEnabled(true, true);
  611. fsensor.setRunoutEnabled(true, true);
  612. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  613. fsensor.setJamDetectionEnabled(true, true);
  614. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  615. #endif //FILAMENT_SENSOR
  616. break;
  617. case 4:
  618. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  619. // Erase EEPROM
  620. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  621. eeprom_update_byte((uint8_t*)i, 0xFF);
  622. menu_progressbar_update(i);
  623. }
  624. menu_progressbar_finish();
  625. softReset();
  626. break;
  627. default:
  628. break;
  629. }
  630. }
  631. extern "C" {
  632. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  633. }
  634. int uart_putchar(char c, FILE *)
  635. {
  636. MYSERIAL.write(c);
  637. return 0;
  638. }
  639. void lcd_splash()
  640. {
  641. lcd_clear(); // clears display and homes screen
  642. lcd_printf_P(PSTR("\n Original Prusa i3\n Prusa Research\n%20.20S"), PSTR(FW_VERSION));
  643. }
  644. void factory_reset()
  645. {
  646. KEEPALIVE_STATE(PAUSED_FOR_USER);
  647. if (!READ(BTN_ENC))
  648. {
  649. _delay_ms(1000);
  650. if (!READ(BTN_ENC))
  651. {
  652. lcd_clear();
  653. lcd_puts_P(PSTR("Factory RESET"));
  654. SET_OUTPUT(BEEPER);
  655. if(eSoundMode!=e_SOUND_MODE_SILENT)
  656. WRITE(BEEPER, HIGH);
  657. while (!READ(BTN_ENC));
  658. WRITE(BEEPER, LOW);
  659. _delay_ms(2000);
  660. char level = reset_menu();
  661. factory_reset(level);
  662. switch (level) {
  663. case 0:
  664. case 1:
  665. case 2:
  666. case 3:
  667. case 4: _delay_ms(0); break;
  668. }
  669. }
  670. }
  671. KEEPALIVE_STATE(IN_HANDLER);
  672. }
  673. #if 0
  674. void show_fw_version_warnings() {
  675. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  676. switch (FW_DEV_VERSION) {
  677. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(MSG_FW_VERSION_BETA); break;
  678. case(FW_VERSION_ALPHA):
  679. case(FW_VERSION_DEVEL):
  680. case(FW_VERSION_DEBUG):
  681. lcd_update_enable(false);
  682. lcd_clear();
  683. #if (FW_DEV_VERSION == FW_VERSION_DEVEL || FW_DEV_VERSION == FW_VERSION_ALPHA)
  684. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  685. #else
  686. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  687. #endif
  688. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  689. lcd_puts_at_P(0, 2, PSTR("FW")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  690. lcd_puts_at_P(0, 3, PSTR("Repo: ")); lcd_puts_P(PSTR(FW_REPOSITORY));
  691. lcd_wait_for_click();
  692. break;
  693. // 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
  694. }
  695. lcd_update_enable(true);
  696. }
  697. #endif
  698. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  699. //! @brief try to check if firmware is on right type of printer
  700. static void check_if_fw_is_on_right_printer() {
  701. if (fsensor.probeOtherType()) {
  702. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  703. }
  704. }
  705. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  706. uint8_t check_printer_version()
  707. {
  708. uint8_t version_changed = 0;
  709. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  710. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  711. if (printer_type != PRINTER_TYPE) {
  712. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  713. else version_changed |= 0b10;
  714. }
  715. if (motherboard != MOTHERBOARD) {
  716. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  717. else version_changed |= 0b01;
  718. }
  719. return version_changed;
  720. }
  721. #ifdef BOOTAPP
  722. #include "bootapp.h" //bootloader support
  723. #endif //BOOTAPP
  724. #if (LANG_MODE != 0) //secondary language support
  725. #ifdef XFLASH
  726. // language update from external flash
  727. #define LANGBOOT_BLOCKSIZE 0x1000u
  728. #define LANGBOOT_RAMBUFFER 0x0800
  729. void update_sec_lang_from_external_flash()
  730. {
  731. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  732. {
  733. uint8_t lang = boot_reserved >> 3;
  734. uint8_t state = boot_reserved & 0x07;
  735. lang_table_header_t header;
  736. uint32_t src_addr;
  737. if (lang_get_header(lang, &header, &src_addr))
  738. {
  739. lcd_puts_at_P(1,3,PSTR("Language update."));
  740. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  741. _delay(100);
  742. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  743. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  744. {
  745. cli();
  746. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  747. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  748. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  749. if (state == 0)
  750. {
  751. //TODO - check header integrity
  752. }
  753. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  754. }
  755. else
  756. {
  757. //TODO - check sec lang data integrity
  758. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  759. }
  760. }
  761. }
  762. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  763. }
  764. #ifdef DEBUG_XFLASH
  765. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  766. {
  767. lang_table_header_t header;
  768. uint8_t count = 0;
  769. uint32_t addr = 0x00000;
  770. while (1)
  771. {
  772. printf_P(_n("LANGTABLE%d:"), count);
  773. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  774. if (header.magic != LANG_MAGIC)
  775. {
  776. puts_P(_n("NG!"));
  777. break;
  778. }
  779. puts_P(_n("OK"));
  780. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  781. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  782. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  783. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  784. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  785. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  786. addr += header.size;
  787. codes[count] = header.code;
  788. count ++;
  789. }
  790. return count;
  791. }
  792. void list_sec_lang_from_external_flash()
  793. {
  794. uint16_t codes[8];
  795. uint8_t count = lang_xflash_enum_codes(codes);
  796. printf_P(_n("XFlash lang count = %hhd\n"), count);
  797. }
  798. #endif //DEBUG_XFLASH
  799. #endif //XFLASH
  800. #endif //(LANG_MODE != 0)
  801. static void fw_crash_init()
  802. {
  803. #ifdef XFLASH_DUMP
  804. dump_crash_reason crash_reason;
  805. if(xfdump_check_state(&crash_reason))
  806. {
  807. // always signal to the host that a dump is available for retrieval
  808. puts_P(_N("// action:dump_available"));
  809. #ifdef EMERGENCY_DUMP
  810. if(crash_reason != dump_crash_reason::manual &&
  811. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  812. {
  813. lcd_show_fullscreen_message_and_wait_P(
  814. _n("FW crash detected! "
  815. "You can continue printing. "
  816. "Debug data available for analysis. "
  817. "Contact support to submit details."));
  818. }
  819. #endif
  820. }
  821. #else //XFLASH_DUMP
  822. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  823. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  824. {
  825. lcd_beeper_quick_feedback();
  826. lcd_clear();
  827. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  828. switch(crash_reason)
  829. {
  830. case dump_crash_reason::stack_error:
  831. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  832. break;
  833. case dump_crash_reason::watchdog:
  834. lcd_puts_P(_n("Watchdog timeout"));
  835. break;
  836. case dump_crash_reason::bad_isr:
  837. lcd_puts_P(_n("Bad interrupt"));
  838. break;
  839. default:
  840. lcd_print((uint8_t)crash_reason);
  841. break;
  842. }
  843. lcd_wait_for_click();
  844. }
  845. #endif //XFLASH_DUMP
  846. // prevent crash prompts to reappear once acknowledged
  847. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  848. }
  849. static void xflash_err_msg()
  850. {
  851. puts_P(_n("XFLASH not responding."));
  852. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  853. }
  854. // "Setup" function is called by the Arduino framework on startup.
  855. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  856. // are initialized by the main() routine provided by the Arduino framework.
  857. void setup()
  858. {
  859. timer2_init(); // enables functional millis
  860. ultralcd_init();
  861. spi_init();
  862. lcd_splash();
  863. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  864. selectedSerialPort = eeprom_init_default_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, 0);
  865. MYSERIAL.begin(BAUDRATE);
  866. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  867. stdout = uartout;
  868. #ifdef XFLASH
  869. bool xflash_success = xflash_init();
  870. uint8_t optiboot_status = 1;
  871. if (xflash_success)
  872. {
  873. optiboot_status = optiboot_xflash_enter();
  874. #if (LANG_MODE != 0) //secondary language support
  875. update_sec_lang_from_external_flash();
  876. #endif //(LANG_MODE != 0)
  877. }
  878. #else
  879. const bool xflash_success = true;
  880. #endif //XFLASH
  881. setup_killpin();
  882. setup_powerhold();
  883. farm_mode_init();
  884. #ifdef TMC2130
  885. if( FarmOrUserECool() ){
  886. //increased extruder current (PFW363)
  887. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  888. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  889. }
  890. #endif //TMC2130
  891. #ifdef PRUSA_SN_SUPPORT
  892. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  893. //SN is valid only if it is NULL terminated and starts with "CZPX".
  894. {
  895. char SN[20];
  896. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  897. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  898. {
  899. if (!get_PRUSA_SN(SN))
  900. {
  901. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  902. puts_P(PSTR("SN updated"));
  903. }
  904. else
  905. puts_P(PSTR("SN update failed"));
  906. }
  907. }
  908. #endif //PRUSA_SN_SUPPORT
  909. #ifndef XFLASH
  910. SERIAL_PROTOCOLLNPGM("start");
  911. #else
  912. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  913. SERIAL_PROTOCOLLNPGM("start");
  914. #endif
  915. SERIAL_ECHO_START;
  916. puts_P(PSTR(" " FW_VERSION_FULL));
  917. if (eeprom_read_byte((uint8_t *)EEPROM_MMU_ENABLED)) {
  918. MMU2::mmu2.Start();
  919. }
  920. SpoolJoin::spooljoin.initSpoolJoinStatus();
  921. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  922. #ifdef DEBUG_SEC_LANG
  923. lang_table_header_t header;
  924. uint32_t src_addr = 0x00000;
  925. if (lang_get_header(1, &header, &src_addr))
  926. {
  927. printf_P(
  928. _n(
  929. " _src_addr = 0x%08lx\n"
  930. " _lt_magic = 0x%08lx %S\n"
  931. " _lt_size = 0x%04x (%d)\n"
  932. " _lt_count = 0x%04x (%d)\n"
  933. " _lt_chsum = 0x%04x\n"
  934. " _lt_code = 0x%04x (%c%c)\n"
  935. " _lt_resv1 = 0x%08lx\n"
  936. ),
  937. src_addr,
  938. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  939. header.size, header.size,
  940. header.count, header.count,
  941. header.checksum,
  942. header.code, header.code >> 8, header.code & 0xff,
  943. header.signature
  944. );
  945. #if 0
  946. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  947. for (uint16_t i = 0; i < 1024; i++)
  948. {
  949. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  950. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  951. if ((i % 16) == 15) putchar('\n');
  952. }
  953. #endif
  954. uint16_t sum = 0;
  955. for (uint16_t i = 0; i < header.size; i++)
  956. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  957. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  958. sum -= header.checksum; //subtract checksum
  959. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  960. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  961. if (sum == header.checksum)
  962. puts_P(_n("Checksum OK"));
  963. else
  964. puts_P(_n("Checksum NG"));
  965. }
  966. else
  967. puts_P(_n("lang_get_header failed!"));
  968. #if 0
  969. for (uint16_t i = 0; i < 1024*10; i++)
  970. {
  971. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  972. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  973. if ((i % 16) == 15) putchar('\n');
  974. }
  975. #endif
  976. #if 0
  977. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  978. for (int i = 0; i < 4096; ++i) {
  979. int b = eeprom_read_byte((unsigned char*)i);
  980. if (b != 255) {
  981. SERIAL_ECHO(i);
  982. SERIAL_ECHO(":");
  983. SERIAL_ECHO(b);
  984. SERIAL_ECHOLN("");
  985. }
  986. }
  987. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  988. #endif
  989. #endif //DEBUG_SEC_LANG
  990. // Check startup - does nothing if bootloader sets MCUSR to 0
  991. byte mcu = MCUSR;
  992. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  993. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  994. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  995. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  996. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  997. if (mcu & 1) puts_P(MSG_POWERUP);
  998. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  999. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1000. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1001. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1002. MCUSR = 0;
  1003. //SERIAL_ECHORPGM(MSG_MARLIN);
  1004. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1005. #ifdef STRING_VERSION_CONFIG_H
  1006. #ifdef STRING_CONFIG_H_AUTHOR
  1007. SERIAL_ECHO_START;
  1008. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1009. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1010. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1011. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1012. #endif
  1013. #endif
  1014. SERIAL_ECHO_START;
  1015. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1016. SERIAL_ECHO(freeMemory());
  1017. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1018. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1019. //lcd_update_enable(false); // why do we need this?? - andre
  1020. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1021. bool previous_settings_retrieved = false;
  1022. uint8_t hw_changed = check_printer_version();
  1023. 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
  1024. previous_settings_retrieved = Config_RetrieveSettings();
  1025. }
  1026. else { //printer version was changed so use default settings
  1027. Config_ResetDefault();
  1028. }
  1029. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1030. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1031. // performed inside the soft_pwm_isr)
  1032. SdFatUtil::set_stack_guard();
  1033. // Initialize pwm/temperature loops
  1034. soft_pwm_init();
  1035. temp_mgr_init();
  1036. #ifdef EXTRUDER_ALTFAN_DETECT
  1037. SERIAL_ECHORPGM(_n("Hotend fan type: "));
  1038. if (extruder_altfan_detect())
  1039. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1040. else
  1041. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1042. #endif //EXTRUDER_ALTFAN_DETECT
  1043. plan_init(); // Initialize planner;
  1044. factory_reset();
  1045. eeprom_init_default_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1046. eeprom_init_default_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard if uninitialized
  1047. lcd_encoder_diff=0;
  1048. #ifdef TMC2130
  1049. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1050. if (silentMode == 0xff) silentMode = 0;
  1051. tmc2130_mode = TMC2130_MODE_NORMAL;
  1052. if (lcd_crash_detect_enabled() && !farm_mode)
  1053. {
  1054. lcd_crash_detect_enable();
  1055. puts_P(_N("CrashDetect ENABLED!"));
  1056. }
  1057. else
  1058. {
  1059. lcd_crash_detect_disable();
  1060. puts_P(_N("CrashDetect DISABLED"));
  1061. }
  1062. #ifdef TMC2130_LINEARITY_CORRECTION
  1063. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1064. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1065. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1066. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1067. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1068. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1069. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1070. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1071. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1072. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1073. #endif //TMC2130_LINEARITY_CORRECTION
  1074. #ifdef TMC2130_VARIABLE_RESOLUTION
  1075. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1076. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1077. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1078. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1079. #else //TMC2130_VARIABLE_RESOLUTION
  1080. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1081. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1082. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1083. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1084. #endif //TMC2130_VARIABLE_RESOLUTION
  1085. #endif //TMC2130
  1086. st_init(); // Initialize stepper, this enables interrupts!
  1087. #ifdef TMC2130
  1088. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1089. update_mode_profile();
  1090. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1091. #endif //TMC2130
  1092. #ifdef PSU_Delta
  1093. init_force_z(); // ! important for correct Z-axis initialization
  1094. #endif // PSU_Delta
  1095. setup_photpin();
  1096. #if 0
  1097. servo_init();
  1098. #endif
  1099. // Reset the machine correction matrix.
  1100. // It does not make sense to load the correction matrix until the machine is homed.
  1101. world2machine_reset();
  1102. // Initialize current_position accounting for software endstops to
  1103. // avoid unexpected initial shifts on the first move
  1104. clamp_to_software_endstops(current_position);
  1105. plan_set_position_curposXYZE();
  1106. // Show the xflash error message now that serial, lcd and encoder are available
  1107. if (!xflash_success)
  1108. xflash_err_msg();
  1109. #ifdef FILAMENT_SENSOR
  1110. fsensor.init();
  1111. #endif //FILAMENT_SENSOR
  1112. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1113. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1114. #endif
  1115. setup_homepin();
  1116. #if defined(Z_AXIS_ALWAYS_ON)
  1117. enable_z();
  1118. #endif
  1119. // The farm monitoring SW may accidentally expect
  1120. // 2 messages of "printer started" to consider a printer working.
  1121. prusa_statistics(8);
  1122. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1123. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1124. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1125. // but this times out if a blocking dialog is shown in setup().
  1126. card.initsd();
  1127. #ifdef DEBUG_SD_SPEED_TEST
  1128. if (card.cardOK)
  1129. {
  1130. uint8_t* buff = (uint8_t*)block_buffer;
  1131. uint32_t block = 0;
  1132. uint32_t sumr = 0;
  1133. uint32_t sumw = 0;
  1134. for (int i = 0; i < 1024; i++)
  1135. {
  1136. uint32_t u = _micros();
  1137. bool res = card.card.readBlock(i, buff);
  1138. u = _micros() - u;
  1139. if (res)
  1140. {
  1141. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1142. sumr += u;
  1143. u = _micros();
  1144. res = card.card.writeBlock(i, buff);
  1145. u = _micros() - u;
  1146. if (res)
  1147. {
  1148. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1149. sumw += u;
  1150. }
  1151. else
  1152. {
  1153. printf_P(PSTR("writeBlock %4d error\n"), i);
  1154. break;
  1155. }
  1156. }
  1157. else
  1158. {
  1159. printf_P(PSTR("readBlock %4d error\n"), i);
  1160. break;
  1161. }
  1162. }
  1163. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1164. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1165. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1166. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1167. }
  1168. else
  1169. printf_P(PSTR("Card NG!\n"));
  1170. #endif //DEBUG_SD_SPEED_TEST
  1171. eeprom_init();
  1172. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1173. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1174. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1175. #if (LANG_MODE != 0) //secondary language support
  1176. #ifdef DEBUG_XFLASH
  1177. XFLASH_SPI_ENTER();
  1178. uint8_t uid[8]; // 64bit unique id
  1179. xflash_rd_uid(uid);
  1180. puts_P(_n("XFLASH UID="));
  1181. for (uint8_t i = 0; i < 8; i ++)
  1182. printf_P(PSTR("%02x"), uid[i]);
  1183. putchar('\n');
  1184. list_sec_lang_from_external_flash();
  1185. #endif //DEBUG_XFLASH
  1186. // lang_reset();
  1187. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1188. lcd_language();
  1189. #ifdef DEBUG_SEC_LANG
  1190. uint16_t sec_lang_code = lang_get_code(1);
  1191. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1192. 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);
  1193. lang_print_sec_lang(uartout);
  1194. #endif //DEBUG_SEC_LANG
  1195. #endif //(LANG_MODE != 0)
  1196. eeprom_init_default_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1197. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1198. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1199. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1200. int16_t z_shift = 0;
  1201. for (uint8_t i = 0; i < 5; i++) {
  1202. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1203. }
  1204. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1205. }
  1206. eeprom_init_default_byte((uint8_t*)EEPROM_UVLO, 0);
  1207. eeprom_init_default_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1208. //mbl_mode_init();
  1209. mbl_settings_init();
  1210. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1211. if (SilentModeMenu_MMU == 255) {
  1212. SilentModeMenu_MMU = 1;
  1213. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1214. }
  1215. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1216. setup_fan_interrupt();
  1217. #endif //DEBUG_DISABLE_FANCHECK
  1218. #ifndef DEBUG_DISABLE_STARTMSGS
  1219. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1220. if (!farm_mode) {
  1221. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1222. check_if_fw_is_on_right_printer();
  1223. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1224. #if 0
  1225. show_fw_version_warnings();
  1226. #endif
  1227. }
  1228. switch (hw_changed) {
  1229. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1230. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1231. case(0b01):
  1232. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1233. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1234. break;
  1235. case(0b10):
  1236. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1237. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1238. break;
  1239. case(0b11):
  1240. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1241. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1242. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1243. break;
  1244. default: break; //no change, show no message
  1245. }
  1246. if (!previous_settings_retrieved) {
  1247. 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
  1248. Config_StoreSettings();
  1249. }
  1250. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1251. lcd_wizard(WizState::Run);
  1252. }
  1253. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1254. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1255. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1256. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1257. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1258. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1259. // Show the message.
  1260. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1261. }
  1262. #ifdef TEMP_MODEL
  1263. else if (calibration_status() == CALIBRATION_STATUS_TEMP_MODEL_CALIBRATION) {
  1264. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TM_NOT_CAL));
  1265. lcd_update_enable(true);
  1266. }
  1267. #endif //TEMP_MODEL
  1268. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1269. // Show the message.
  1270. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1271. lcd_update_enable(true);
  1272. }
  1273. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1274. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1275. lcd_update_enable(true);
  1276. }
  1277. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1278. // Show the message.
  1279. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1280. }
  1281. }
  1282. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1283. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1284. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1285. update_current_firmware_version_to_eeprom();
  1286. lcd_selftest();
  1287. }
  1288. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1289. KEEPALIVE_STATE(IN_PROCESS);
  1290. #endif //DEBUG_DISABLE_STARTMSGS
  1291. lcd_update_enable(true);
  1292. lcd_clear();
  1293. lcd_update(2);
  1294. // Store the currently running firmware into an eeprom,
  1295. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1296. update_current_firmware_version_to_eeprom();
  1297. #ifdef TMC2130
  1298. tmc2130_home_origin[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN, 0);
  1299. tmc2130_home_bsteps[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS, 48);
  1300. tmc2130_home_fsteps[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS, 48);
  1301. tmc2130_home_origin[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN, 0);
  1302. tmc2130_home_bsteps[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS, 48);
  1303. tmc2130_home_fsteps[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS, 48);
  1304. tmc2130_home_enabled = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED, 0);
  1305. #endif //TMC2130
  1306. // report crash failures
  1307. fw_crash_init();
  1308. #ifdef UVLO_SUPPORT
  1309. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1310. /*
  1311. if (!lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1312. else {
  1313. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1314. lcd_update_enable(true);
  1315. lcd_update(2);
  1316. lcd_setstatuspgm(MSG_WELCOME);
  1317. }
  1318. */
  1319. manage_heater(); // Update temperatures
  1320. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1321. 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));
  1322. #endif
  1323. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1324. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1325. puts_P(_N("Automatic recovery!"));
  1326. #endif
  1327. recover_print(1);
  1328. }
  1329. else{
  1330. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1331. puts_P(_N("Normal recovery!"));
  1332. #endif
  1333. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) == LCD_LEFT_BUTTON_CHOICE) {
  1334. recover_print(0);
  1335. } else {
  1336. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1337. lcd_update_enable(true);
  1338. lcd_update(2);
  1339. lcd_setstatuspgm(MSG_WELCOME);
  1340. }
  1341. }
  1342. }
  1343. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1344. // the entire state machine initialized.
  1345. setup_uvlo_interrupt();
  1346. #endif //UVLO_SUPPORT
  1347. fCheckModeInit();
  1348. KEEPALIVE_STATE(NOT_BUSY);
  1349. #ifdef WATCHDOG
  1350. wdt_enable(WDTO_4S);
  1351. #ifdef EMERGENCY_HANDLERS
  1352. WDTCSR |= (1 << WDIE);
  1353. #endif //EMERGENCY_HANDLERS
  1354. #endif //WATCHDOG
  1355. }
  1356. static inline void crash_and_burn(dump_crash_reason reason)
  1357. {
  1358. WRITE(BEEPER, HIGH);
  1359. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1360. #ifdef EMERGENCY_DUMP
  1361. xfdump_full_dump_and_reset(reason);
  1362. #elif defined(EMERGENCY_SERIAL_DUMP)
  1363. if(emergency_serial_dump)
  1364. serial_dump_and_reset(reason);
  1365. #endif
  1366. softReset();
  1367. }
  1368. #ifdef EMERGENCY_HANDLERS
  1369. #ifdef WATCHDOG
  1370. ISR(WDT_vect)
  1371. {
  1372. crash_and_burn(dump_crash_reason::watchdog);
  1373. }
  1374. #endif
  1375. ISR(BADISR_vect)
  1376. {
  1377. crash_and_burn(dump_crash_reason::bad_isr);
  1378. }
  1379. #endif //EMERGENCY_HANDLERS
  1380. void stack_error() {
  1381. crash_and_burn(dump_crash_reason::stack_error);
  1382. }
  1383. /**
  1384. * Output autoreport values according to features requested in M155
  1385. */
  1386. #if defined(AUTO_REPORT)
  1387. void host_autoreport()
  1388. {
  1389. if (autoReportFeatures.TimerExpired())
  1390. {
  1391. if(autoReportFeatures.Temp()){
  1392. gcode_M105(active_extruder);
  1393. }
  1394. if(autoReportFeatures.Pos()){
  1395. gcode_M114();
  1396. }
  1397. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1398. if(autoReportFeatures.Fans()){
  1399. gcode_M123();
  1400. }
  1401. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1402. autoReportFeatures.TimerStart();
  1403. }
  1404. }
  1405. #endif //AUTO_REPORT
  1406. /**
  1407. * Output a "busy" message at regular intervals
  1408. * while the machine is not accepting commands.
  1409. */
  1410. void host_keepalive() {
  1411. #ifndef HOST_KEEPALIVE_FEATURE
  1412. return;
  1413. #endif //HOST_KEEPALIVE_FEATURE
  1414. if (farm_mode) return;
  1415. long ms = _millis();
  1416. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1417. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1418. switch (busy_state) {
  1419. case IN_HANDLER:
  1420. case IN_PROCESS:
  1421. SERIAL_ECHO_START;
  1422. SERIAL_ECHOLNPGM("busy: processing");
  1423. break;
  1424. case PAUSED_FOR_USER:
  1425. SERIAL_ECHO_START;
  1426. SERIAL_ECHOLNPGM("busy: paused for user");
  1427. break;
  1428. case PAUSED_FOR_INPUT:
  1429. SERIAL_ECHO_START;
  1430. SERIAL_ECHOLNPGM("busy: paused for input");
  1431. break;
  1432. default:
  1433. break;
  1434. }
  1435. }
  1436. prev_busy_signal_ms = ms;
  1437. }
  1438. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1439. // Before loop(), the setup() function is called by the main() routine.
  1440. void loop()
  1441. {
  1442. // Reset a previously aborted command, we can now start processing motion again
  1443. planner_aborted = false;
  1444. if(Stopped) {
  1445. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1446. // Signal to the host that we're currently busy waiting for supervision.
  1447. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1448. } else {
  1449. // Printer is available for processing, reset state
  1450. KEEPALIVE_STATE(NOT_BUSY);
  1451. }
  1452. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1453. usb_timer.start();
  1454. }
  1455. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1456. ;
  1457. }
  1458. #ifdef PRUSA_M28
  1459. if (prusa_sd_card_upload)
  1460. {
  1461. //we read byte-by byte
  1462. serial_read_stream();
  1463. }
  1464. else
  1465. #endif
  1466. {
  1467. get_command();
  1468. #ifdef SDSUPPORT
  1469. card.checkautostart(false);
  1470. #endif
  1471. if(buflen)
  1472. {
  1473. cmdbuffer_front_already_processed = false;
  1474. #ifdef SDSUPPORT
  1475. if(card.saving)
  1476. {
  1477. // Saving a G-code file onto an SD-card is in progress.
  1478. // Saving starts with M28, saving until M29 is seen.
  1479. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1480. card.write_command(CMDBUFFER_CURRENT_STRING);
  1481. if(card.logging)
  1482. process_commands();
  1483. else
  1484. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1485. } else {
  1486. card.closefile();
  1487. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1488. }
  1489. } else {
  1490. process_commands();
  1491. }
  1492. #else
  1493. process_commands();
  1494. #endif //SDSUPPORT
  1495. if (! cmdbuffer_front_already_processed && buflen)
  1496. {
  1497. // ptr points to the start of the block currently being processed.
  1498. // The first character in the block is the block type.
  1499. char *ptr = cmdbuffer + bufindr;
  1500. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1501. // To support power panic, move the length of the command on the SD card to a planner buffer.
  1502. union {
  1503. struct {
  1504. char lo;
  1505. char hi;
  1506. } lohi;
  1507. uint16_t value;
  1508. } sdlen;
  1509. sdlen.value = 0;
  1510. {
  1511. // This block locks the interrupts globally for 3.25 us,
  1512. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1513. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1514. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1515. cli();
  1516. // Reset the command to something, which will be ignored by the power panic routine,
  1517. // so this buffer length will not be counted twice.
  1518. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1519. // Extract the current buffer length.
  1520. sdlen.lohi.lo = *ptr ++;
  1521. sdlen.lohi.hi = *ptr;
  1522. // and pass it to the planner queue.
  1523. planner_add_sd_length(sdlen.value);
  1524. sei();
  1525. }
  1526. }
  1527. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1528. cli();
  1529. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1530. // and one for each command to previous block in the planner queue.
  1531. planner_add_sd_length(1);
  1532. sei();
  1533. }
  1534. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1535. // this block's SD card length will not be counted twice as its command type has been replaced
  1536. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1537. cmdqueue_pop_front();
  1538. }
  1539. host_keepalive();
  1540. }
  1541. }
  1542. //check heater every n milliseconds
  1543. manage_heater();
  1544. manage_inactivity(isPrintPaused);
  1545. checkHitEndstops();
  1546. lcd_update(0);
  1547. #ifdef TMC2130
  1548. tmc2130_check_overtemp();
  1549. if (tmc2130_sg_crash)
  1550. {
  1551. uint8_t crash = tmc2130_sg_crash;
  1552. tmc2130_sg_crash = 0;
  1553. // crashdet_stop_and_save_print();
  1554. switch (crash)
  1555. {
  1556. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1557. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1558. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1559. }
  1560. }
  1561. #endif //TMC2130
  1562. MMU2::mmu2.mmu_loop();
  1563. }
  1564. #define DEFINE_PGM_READ_ANY(type, reader) \
  1565. static inline type pgm_read_any(const type *p) \
  1566. { return pgm_read_##reader##_near(p); }
  1567. DEFINE_PGM_READ_ANY(float, float);
  1568. DEFINE_PGM_READ_ANY(signed char, byte);
  1569. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1570. static const PROGMEM type array##_P[3] = \
  1571. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1572. static inline type array(uint8_t axis) \
  1573. { return pgm_read_any(&array##_P[axis]); } \
  1574. type array##_ext(uint8_t axis) \
  1575. { return pgm_read_any(&array##_P[axis]); }
  1576. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1577. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1578. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1579. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1580. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1581. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1582. static void axis_is_at_home(uint8_t axis) {
  1583. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1584. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1585. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1586. }
  1587. //! @return original feedmultiply
  1588. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1589. saved_feedrate = feedrate;
  1590. int l_feedmultiply = feedmultiply;
  1591. feedmultiply = 100;
  1592. previous_millis_cmd.start();
  1593. enable_endstops(enable_endstops_now);
  1594. return l_feedmultiply;
  1595. }
  1596. //! @param original_feedmultiply feedmultiply to restore
  1597. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1598. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1599. enable_endstops(false);
  1600. #endif
  1601. feedrate = saved_feedrate;
  1602. feedmultiply = original_feedmultiply;
  1603. previous_millis_cmd.start();
  1604. }
  1605. #ifdef ENABLE_AUTO_BED_LEVELING
  1606. #ifdef AUTO_BED_LEVELING_GRID
  1607. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1608. {
  1609. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1610. planeNormal.debug("planeNormal");
  1611. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1612. //bedLevel.debug("bedLevel");
  1613. //plan_bed_level_matrix.debug("bed level before");
  1614. //vector_3 uncorrected_position = plan_get_position_mm();
  1615. //uncorrected_position.debug("position before");
  1616. vector_3 corrected_position = plan_get_position();
  1617. // corrected_position.debug("position after");
  1618. current_position[X_AXIS] = corrected_position.x;
  1619. current_position[Y_AXIS] = corrected_position.y;
  1620. current_position[Z_AXIS] = corrected_position.z;
  1621. // put the bed at 0 so we don't go below it.
  1622. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1623. plan_set_position_curposXYZE();
  1624. }
  1625. #else // not AUTO_BED_LEVELING_GRID
  1626. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1627. plan_bed_level_matrix.set_to_identity();
  1628. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1629. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1630. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1631. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1632. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1633. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1634. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1635. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1636. vector_3 corrected_position = plan_get_position();
  1637. current_position[X_AXIS] = corrected_position.x;
  1638. current_position[Y_AXIS] = corrected_position.y;
  1639. current_position[Z_AXIS] = corrected_position.z;
  1640. // put the bed at 0 so we don't go below it.
  1641. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1642. plan_set_position_curposXYZE();
  1643. }
  1644. #endif // AUTO_BED_LEVELING_GRID
  1645. static void run_z_probe() {
  1646. plan_bed_level_matrix.set_to_identity();
  1647. feedrate = homing_feedrate[Z_AXIS];
  1648. // move down until you find the bed
  1649. float zPosition = -10;
  1650. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1651. st_synchronize();
  1652. // we have to let the planner know where we are right now as it is not where we said to go.
  1653. zPosition = st_get_position_mm(Z_AXIS);
  1654. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1655. // move up the retract distance
  1656. zPosition += home_retract_mm(Z_AXIS);
  1657. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1658. st_synchronize();
  1659. // move back down slowly to find bed
  1660. feedrate = homing_feedrate[Z_AXIS]/4;
  1661. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1662. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1663. st_synchronize();
  1664. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1665. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1666. plan_set_position_curposXYZE();
  1667. }
  1668. static void do_blocking_move_to(float x, float y, float z) {
  1669. float oldFeedRate = feedrate;
  1670. feedrate = homing_feedrate[Z_AXIS];
  1671. current_position[Z_AXIS] = z;
  1672. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1673. st_synchronize();
  1674. feedrate = XY_TRAVEL_SPEED;
  1675. current_position[X_AXIS] = x;
  1676. current_position[Y_AXIS] = y;
  1677. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1678. st_synchronize();
  1679. feedrate = oldFeedRate;
  1680. }
  1681. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1682. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1683. }
  1684. /// Probe bed height at position (x,y), returns the measured z value
  1685. static float probe_pt(float x, float y, float z_before) {
  1686. // move to right place
  1687. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1688. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1689. run_z_probe();
  1690. float measured_z = current_position[Z_AXIS];
  1691. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1692. SERIAL_PROTOCOLPGM(" x: ");
  1693. SERIAL_PROTOCOL(x);
  1694. SERIAL_PROTOCOLPGM(" y: ");
  1695. SERIAL_PROTOCOL(y);
  1696. SERIAL_PROTOCOLPGM(" z: ");
  1697. SERIAL_PROTOCOL(measured_z);
  1698. SERIAL_PROTOCOLPGM("\n");
  1699. return measured_z;
  1700. }
  1701. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1702. #ifdef LIN_ADVANCE
  1703. /**
  1704. * M900: Set and/or Get advance K factor
  1705. *
  1706. * K<factor> Set advance K factor
  1707. */
  1708. inline void gcode_M900() {
  1709. float newK = code_seen('K') ? code_value_float() : -2;
  1710. #ifdef LA_NOCOMPAT
  1711. if (newK >= 0 && newK < LA_K_MAX)
  1712. extruder_advance_K = newK;
  1713. else
  1714. SERIAL_ECHOLNPGM("K out of allowed range!");
  1715. #else
  1716. if (newK == 0)
  1717. {
  1718. extruder_advance_K = 0;
  1719. la10c_reset();
  1720. }
  1721. else
  1722. {
  1723. newK = la10c_value(newK);
  1724. if (newK < 0)
  1725. SERIAL_ECHOLNPGM("K out of allowed range!");
  1726. else
  1727. extruder_advance_K = newK;
  1728. }
  1729. #endif
  1730. SERIAL_ECHO_START;
  1731. SERIAL_ECHOPGM("Advance K=");
  1732. SERIAL_ECHOLN(extruder_advance_K);
  1733. }
  1734. #endif // LIN_ADVANCE
  1735. bool check_commands() {
  1736. bool end_command_found = false;
  1737. while (buflen)
  1738. {
  1739. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1740. if (!cmdbuffer_front_already_processed)
  1741. cmdqueue_pop_front();
  1742. cmdbuffer_front_already_processed = false;
  1743. }
  1744. return end_command_found;
  1745. }
  1746. /// @brief Safely move Z-axis by distance delta (mm)
  1747. /// @param delta travel distance in mm
  1748. /// @returns The actual travel distance in mm. Endstop may limit the requested move.
  1749. float raise_z(float delta)
  1750. {
  1751. float travel_z = current_position[Z_AXIS];
  1752. // Prepare to move Z axis
  1753. current_position[Z_AXIS] += delta;
  1754. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1755. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1756. #else
  1757. bool z_min_endstop = false;
  1758. #endif
  1759. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1760. {
  1761. // current position is known or very low, it's safe to raise Z
  1762. clamp_to_software_endstops(current_position);
  1763. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1764. st_synchronize();
  1765. // Get the final travel distance
  1766. travel_z = current_position[Z_AXIS] - travel_z;
  1767. } else {
  1768. // ensure Z is powered in normal mode to overcome initial load
  1769. enable_z();
  1770. st_synchronize();
  1771. // rely on crashguard to limit damage
  1772. bool z_endstop_enabled = enable_z_endstop(true);
  1773. #ifdef TMC2130
  1774. tmc2130_home_enter(Z_AXIS_MASK);
  1775. #endif //TMC2130
  1776. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1777. st_synchronize();
  1778. // Get the final travel distance
  1779. travel_z = st_get_position_mm(Z_AXIS) - travel_z;
  1780. #ifdef TMC2130
  1781. if (endstop_z_hit_on_purpose())
  1782. {
  1783. // not necessarily exact, but will avoid further vertical moves
  1784. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1785. plan_set_position_curposXYZE();
  1786. }
  1787. tmc2130_home_exit();
  1788. #endif //TMC2130
  1789. enable_z_endstop(z_endstop_enabled);
  1790. }
  1791. return travel_z;
  1792. }
  1793. // raise_z_above: slowly raise Z to the requested height
  1794. //
  1795. // contrarily to a simple move, this function will carefully plan a move
  1796. // when the current Z position is unknown. In such cases, stallguard is
  1797. // enabled and will prevent prolonged pushing against the Z tops
  1798. void raise_z_above(float target)
  1799. {
  1800. if (current_position[Z_AXIS] >= target)
  1801. return;
  1802. // Use absolute value in case the current position is unknown
  1803. raise_z(fabs(current_position[Z_AXIS] - target));
  1804. }
  1805. #ifdef TMC2130
  1806. bool calibrate_z_auto()
  1807. {
  1808. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1809. lcd_clear();
  1810. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1811. bool endstops_enabled = enable_endstops(true);
  1812. int axis_up_dir = -home_dir(Z_AXIS);
  1813. tmc2130_home_enter(Z_AXIS_MASK);
  1814. current_position[Z_AXIS] = 0;
  1815. plan_set_position_curposXYZE();
  1816. set_destination_to_current();
  1817. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1818. feedrate = homing_feedrate[Z_AXIS];
  1819. plan_buffer_line_destinationXYZE(feedrate / 60);
  1820. st_synchronize();
  1821. // current_position[axis] = 0;
  1822. // plan_set_position_curposXYZE();
  1823. tmc2130_home_exit();
  1824. enable_endstops(false);
  1825. current_position[Z_AXIS] = 0;
  1826. plan_set_position_curposXYZE();
  1827. set_destination_to_current();
  1828. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1829. feedrate = homing_feedrate[Z_AXIS] / 2;
  1830. plan_buffer_line_destinationXYZE(feedrate / 60);
  1831. st_synchronize();
  1832. enable_endstops(endstops_enabled);
  1833. if (PRINTER_TYPE == PRINTER_MK3) {
  1834. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1835. }
  1836. else {
  1837. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1838. }
  1839. plan_set_position_curposXYZE();
  1840. return true;
  1841. }
  1842. #endif //TMC2130
  1843. #ifdef TMC2130
  1844. static void check_Z_crash(void)
  1845. {
  1846. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1847. FORCE_HIGH_POWER_END;
  1848. current_position[Z_AXIS] = 0;
  1849. plan_set_position_curposXYZE();
  1850. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1851. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1852. st_synchronize();
  1853. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1854. }
  1855. }
  1856. #endif //TMC2130
  1857. #ifdef TMC2130
  1858. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1859. #else
  1860. void homeaxis(uint8_t axis, uint8_t cnt)
  1861. #endif //TMC2130
  1862. {
  1863. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1864. #define HOMEAXIS_DO(LETTER) \
  1865. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1866. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1867. {
  1868. int axis_home_dir = home_dir(axis);
  1869. feedrate = homing_feedrate[axis];
  1870. #ifdef TMC2130
  1871. tmc2130_home_enter(X_AXIS_MASK << axis);
  1872. #endif //TMC2130
  1873. // Move away a bit, so that the print head does not touch the end position,
  1874. // and the following movement to endstop has a chance to achieve the required velocity
  1875. // for the stall guard to work.
  1876. current_position[axis] = 0;
  1877. plan_set_position_curposXYZE();
  1878. set_destination_to_current();
  1879. // destination[axis] = 11.f;
  1880. destination[axis] = -3.f * axis_home_dir;
  1881. plan_buffer_line_destinationXYZE(feedrate/60);
  1882. st_synchronize();
  1883. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1884. endstops_hit_on_purpose();
  1885. enable_endstops(false);
  1886. current_position[axis] = 0;
  1887. plan_set_position_curposXYZE();
  1888. destination[axis] = 1. * axis_home_dir;
  1889. plan_buffer_line_destinationXYZE(feedrate/60);
  1890. st_synchronize();
  1891. // Now continue to move up to the left end stop with the collision detection enabled.
  1892. enable_endstops(true);
  1893. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1894. plan_buffer_line_destinationXYZE(feedrate/60);
  1895. st_synchronize();
  1896. for (uint8_t i = 0; i < cnt; i++)
  1897. {
  1898. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1899. endstops_hit_on_purpose();
  1900. enable_endstops(false);
  1901. current_position[axis] = 0;
  1902. plan_set_position_curposXYZE();
  1903. destination[axis] = -10.f * axis_home_dir;
  1904. plan_buffer_line_destinationXYZE(feedrate/60);
  1905. st_synchronize();
  1906. endstops_hit_on_purpose();
  1907. // Now move left up to the collision, this time with a repeatable velocity.
  1908. enable_endstops(true);
  1909. destination[axis] = 11.f * axis_home_dir;
  1910. #ifdef TMC2130
  1911. feedrate = homing_feedrate[axis];
  1912. #else //TMC2130
  1913. feedrate = homing_feedrate[axis] / 2;
  1914. #endif //TMC2130
  1915. plan_buffer_line_destinationXYZE(feedrate/60);
  1916. st_synchronize();
  1917. #ifdef TMC2130
  1918. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1919. if (pstep) pstep[i] = mscnt >> 4;
  1920. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1921. #endif //TMC2130
  1922. }
  1923. endstops_hit_on_purpose();
  1924. enable_endstops(false);
  1925. #ifdef TMC2130
  1926. uint8_t orig = tmc2130_home_origin[axis];
  1927. uint8_t back = tmc2130_home_bsteps[axis];
  1928. if (tmc2130_home_enabled && (orig <= 63))
  1929. {
  1930. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1931. if (back > 0)
  1932. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1933. }
  1934. else
  1935. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1936. tmc2130_home_exit();
  1937. #endif //TMC2130
  1938. axis_is_at_home(axis);
  1939. axis_known_position[axis] = true;
  1940. // Move from minimum
  1941. #ifdef TMC2130
  1942. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1943. #else //TMC2130
  1944. float dist = - axis_home_dir * 0.01f * 64;
  1945. #endif //TMC2130
  1946. current_position[axis] -= dist;
  1947. plan_set_position_curposXYZE();
  1948. current_position[axis] += dist;
  1949. destination[axis] = current_position[axis];
  1950. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1951. st_synchronize();
  1952. feedrate = 0.0;
  1953. }
  1954. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1955. {
  1956. #ifdef TMC2130
  1957. FORCE_HIGH_POWER_START;
  1958. #endif
  1959. int axis_home_dir = home_dir(axis);
  1960. current_position[axis] = 0;
  1961. plan_set_position_curposXYZE();
  1962. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1963. feedrate = homing_feedrate[axis];
  1964. plan_buffer_line_destinationXYZE(feedrate/60);
  1965. st_synchronize();
  1966. #ifdef TMC2130
  1967. check_Z_crash();
  1968. #endif //TMC2130
  1969. current_position[axis] = 0;
  1970. plan_set_position_curposXYZE();
  1971. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1972. plan_buffer_line_destinationXYZE(feedrate/60);
  1973. st_synchronize();
  1974. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1975. feedrate = homing_feedrate[axis]/2 ;
  1976. plan_buffer_line_destinationXYZE(feedrate/60);
  1977. st_synchronize();
  1978. #ifdef TMC2130
  1979. check_Z_crash();
  1980. #endif //TMC2130
  1981. axis_is_at_home(axis);
  1982. destination[axis] = current_position[axis];
  1983. feedrate = 0.0;
  1984. endstops_hit_on_purpose();
  1985. axis_known_position[axis] = true;
  1986. #ifdef TMC2130
  1987. FORCE_HIGH_POWER_END;
  1988. #endif
  1989. }
  1990. enable_endstops(endstops_enabled);
  1991. }
  1992. /**/
  1993. void home_xy()
  1994. {
  1995. set_destination_to_current();
  1996. homeaxis(X_AXIS);
  1997. homeaxis(Y_AXIS);
  1998. plan_set_position_curposXYZE();
  1999. endstops_hit_on_purpose();
  2000. }
  2001. void refresh_cmd_timeout(void)
  2002. {
  2003. previous_millis_cmd.start();
  2004. }
  2005. #ifdef FWRETRACT
  2006. void retract(bool retracting, bool swapretract = false) {
  2007. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2008. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2009. // position, which requires a sync
  2010. if(retracting && !retracted[active_extruder]) {
  2011. st_synchronize();
  2012. set_destination_to_current();
  2013. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2014. plan_set_e_position(current_position[E_AXIS]);
  2015. float oldFeedrate = feedrate;
  2016. feedrate=cs.retract_feedrate*60;
  2017. retracted[active_extruder]=true;
  2018. prepare_move();
  2019. if(cs.retract_zlift) {
  2020. st_synchronize();
  2021. current_position[Z_AXIS]-=cs.retract_zlift;
  2022. plan_set_position_curposXYZE();
  2023. prepare_move();
  2024. }
  2025. feedrate = oldFeedrate;
  2026. } else if(!retracting && retracted[active_extruder]) {
  2027. st_synchronize();
  2028. set_destination_to_current();
  2029. float oldFeedrate = feedrate;
  2030. feedrate=cs.retract_recover_feedrate*60;
  2031. if(cs.retract_zlift) {
  2032. current_position[Z_AXIS]+=cs.retract_zlift;
  2033. plan_set_position_curposXYZE();
  2034. prepare_move();
  2035. st_synchronize();
  2036. }
  2037. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2038. plan_set_e_position(current_position[E_AXIS]);
  2039. retracted[active_extruder]=false;
  2040. prepare_move();
  2041. feedrate = oldFeedrate;
  2042. }
  2043. } //retract
  2044. #endif //FWRETRACT
  2045. #ifdef TMC2130
  2046. void force_high_power_mode(bool start_high_power_section) {
  2047. #ifdef PSU_Delta
  2048. if (start_high_power_section == true) enable_force_z();
  2049. #endif //PSU_Delta
  2050. uint8_t silent;
  2051. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2052. if (silent == 1) {
  2053. //we are in silent mode, set to normal mode to enable crash detection
  2054. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2055. st_synchronize();
  2056. cli();
  2057. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2058. update_mode_profile();
  2059. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2060. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2061. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2062. st_reset_timer();
  2063. sei();
  2064. }
  2065. }
  2066. #endif //TMC2130
  2067. void gcode_M105(uint8_t extruder)
  2068. {
  2069. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2070. SERIAL_PROTOCOLPGM("T:");
  2071. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2072. SERIAL_PROTOCOLPGM(" /");
  2073. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2074. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2075. SERIAL_PROTOCOLPGM(" B:");
  2076. SERIAL_PROTOCOL_F(degBed(),1);
  2077. SERIAL_PROTOCOLPGM(" /");
  2078. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2079. #endif //TEMP_BED_PIN
  2080. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2081. SERIAL_PROTOCOLPGM(" T");
  2082. SERIAL_PROTOCOL(cur_extruder);
  2083. SERIAL_PROTOCOL(':');
  2084. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2085. SERIAL_PROTOCOLPGM(" /");
  2086. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2087. }
  2088. #else
  2089. SERIAL_ERROR_START;
  2090. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2091. #endif
  2092. SERIAL_PROTOCOLPGM(" @:");
  2093. #ifdef EXTRUDER_WATTS
  2094. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2095. SERIAL_PROTOCOLPGM("W");
  2096. #else
  2097. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2098. #endif
  2099. SERIAL_PROTOCOLPGM(" B@:");
  2100. #ifdef BED_WATTS
  2101. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2102. SERIAL_PROTOCOLPGM("W");
  2103. #else
  2104. SERIAL_PROTOCOL(getHeaterPower(-1));
  2105. #endif
  2106. #ifdef PINDA_THERMISTOR
  2107. SERIAL_PROTOCOLPGM(" P:");
  2108. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2109. #endif //PINDA_THERMISTOR
  2110. #ifdef AMBIENT_THERMISTOR
  2111. SERIAL_PROTOCOLPGM(" A:");
  2112. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2113. #endif //AMBIENT_THERMISTOR
  2114. #ifdef SHOW_TEMP_ADC_VALUES
  2115. {
  2116. float raw = 0.0;
  2117. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2118. SERIAL_PROTOCOLPGM(" ADC B:");
  2119. SERIAL_PROTOCOL_F(degBed(),1);
  2120. SERIAL_PROTOCOLPGM("C->");
  2121. raw = rawBedTemp();
  2122. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2123. SERIAL_PROTOCOLPGM(" Rb->");
  2124. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2125. SERIAL_PROTOCOLPGM(" Rxb->");
  2126. SERIAL_PROTOCOL_F(raw, 5);
  2127. #endif
  2128. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2129. SERIAL_PROTOCOLPGM(" T");
  2130. SERIAL_PROTOCOL(cur_extruder);
  2131. SERIAL_PROTOCOLPGM(":");
  2132. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2133. SERIAL_PROTOCOLPGM("C->");
  2134. raw = rawHotendTemp(cur_extruder);
  2135. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2136. SERIAL_PROTOCOLPGM(" Rt");
  2137. SERIAL_PROTOCOL(cur_extruder);
  2138. SERIAL_PROTOCOLPGM("->");
  2139. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2140. SERIAL_PROTOCOLPGM(" Rx");
  2141. SERIAL_PROTOCOL(cur_extruder);
  2142. SERIAL_PROTOCOLPGM("->");
  2143. SERIAL_PROTOCOL_F(raw, 5);
  2144. }
  2145. }
  2146. #endif
  2147. SERIAL_PROTOCOLLN();
  2148. }
  2149. #ifdef TMC2130
  2150. 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)
  2151. #else
  2152. 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)
  2153. #endif //TMC2130
  2154. {
  2155. // Flag for the display update routine and to disable the print cancelation during homing.
  2156. st_synchronize();
  2157. homing_flag = true;
  2158. #if 0
  2159. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2160. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2161. #endif
  2162. // Which axes should be homed?
  2163. bool home_x = home_x_axis;
  2164. bool home_y = home_y_axis;
  2165. bool home_z = home_z_axis;
  2166. // Either all X,Y,Z codes are present, or none of them.
  2167. bool home_all_axes = home_x == home_y && home_x == home_z;
  2168. if (home_all_axes)
  2169. // No X/Y/Z code provided means to home all axes.
  2170. home_x = home_y = home_z = true;
  2171. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2172. if (home_all_axes) {
  2173. raise_z_above(MESH_HOME_Z_SEARCH);
  2174. }
  2175. #ifdef ENABLE_AUTO_BED_LEVELING
  2176. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2177. #endif //ENABLE_AUTO_BED_LEVELING
  2178. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2179. // the planner will not perform any adjustments in the XY plane.
  2180. // Wait for the motors to stop and update the current position with the absolute values.
  2181. world2machine_revert_to_uncorrected();
  2182. // For mesh bed leveling deactivate the matrix temporarily.
  2183. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2184. // in a single axis only.
  2185. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2186. #ifdef MESH_BED_LEVELING
  2187. uint8_t mbl_was_active = mbl.active;
  2188. mbl.active = 0;
  2189. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2190. #endif
  2191. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2192. if (home_z)
  2193. babystep_undo();
  2194. int l_feedmultiply = setup_for_endstop_move();
  2195. set_destination_to_current();
  2196. feedrate = 0.0;
  2197. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2198. if(home_z)
  2199. homeaxis(Z_AXIS);
  2200. #endif
  2201. #ifdef QUICK_HOME
  2202. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2203. if(home_x && home_y) //first diagonal move
  2204. {
  2205. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2206. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2207. plan_set_position_curposXYZE();
  2208. 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);
  2209. feedrate = homing_feedrate[X_AXIS];
  2210. if(homing_feedrate[Y_AXIS]<feedrate)
  2211. feedrate = homing_feedrate[Y_AXIS];
  2212. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2213. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2214. } else {
  2215. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2216. }
  2217. plan_buffer_line_destinationXYZE(feedrate/60);
  2218. st_synchronize();
  2219. axis_is_at_home(X_AXIS);
  2220. axis_is_at_home(Y_AXIS);
  2221. plan_set_position_curposXYZE();
  2222. destination[X_AXIS] = current_position[X_AXIS];
  2223. destination[Y_AXIS] = current_position[Y_AXIS];
  2224. plan_buffer_line_destinationXYZE(feedrate/60);
  2225. feedrate = 0.0;
  2226. st_synchronize();
  2227. endstops_hit_on_purpose();
  2228. current_position[X_AXIS] = destination[X_AXIS];
  2229. current_position[Y_AXIS] = destination[Y_AXIS];
  2230. current_position[Z_AXIS] = destination[Z_AXIS];
  2231. }
  2232. #endif /* QUICK_HOME */
  2233. #ifdef TMC2130
  2234. if(home_x)
  2235. {
  2236. if (!calib)
  2237. homeaxis(X_AXIS);
  2238. else
  2239. tmc2130_home_calibrate(X_AXIS);
  2240. }
  2241. if(home_y)
  2242. {
  2243. if (!calib)
  2244. homeaxis(Y_AXIS);
  2245. else
  2246. tmc2130_home_calibrate(Y_AXIS);
  2247. }
  2248. #else //TMC2130
  2249. if(home_x) homeaxis(X_AXIS);
  2250. if(home_y) homeaxis(Y_AXIS);
  2251. #endif //TMC2130
  2252. if(home_x_axis && home_x_value != 0)
  2253. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2254. if(home_y_axis && home_y_value != 0)
  2255. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2256. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2257. #ifndef Z_SAFE_HOMING
  2258. if(home_z) {
  2259. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2260. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2261. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2262. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2263. raise_z_above(MESH_HOME_Z_SEARCH);
  2264. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2265. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2266. // 1st mesh bed leveling measurement point, corrected.
  2267. world2machine_initialize();
  2268. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2269. world2machine_reset();
  2270. if (destination[Y_AXIS] < Y_MIN_POS)
  2271. destination[Y_AXIS] = Y_MIN_POS;
  2272. feedrate = homing_feedrate[X_AXIS] / 20;
  2273. enable_endstops(false);
  2274. #ifdef DEBUG_BUILD
  2275. SERIAL_ECHOLNPGM("plan_set_position()");
  2276. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2277. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2278. #endif
  2279. plan_set_position_curposXYZE();
  2280. #ifdef DEBUG_BUILD
  2281. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2282. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2283. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2284. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2285. #endif
  2286. plan_buffer_line_destinationXYZE(feedrate);
  2287. st_synchronize();
  2288. current_position[X_AXIS] = destination[X_AXIS];
  2289. current_position[Y_AXIS] = destination[Y_AXIS];
  2290. enable_endstops(true);
  2291. endstops_hit_on_purpose();
  2292. homeaxis(Z_AXIS);
  2293. #else // MESH_BED_LEVELING
  2294. homeaxis(Z_AXIS);
  2295. #endif // MESH_BED_LEVELING
  2296. }
  2297. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2298. if(home_all_axes) {
  2299. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2300. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2301. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2302. feedrate = XY_TRAVEL_SPEED/60;
  2303. current_position[Z_AXIS] = 0;
  2304. plan_set_position_curposXYZE();
  2305. plan_buffer_line_destinationXYZE(feedrate);
  2306. st_synchronize();
  2307. current_position[X_AXIS] = destination[X_AXIS];
  2308. current_position[Y_AXIS] = destination[Y_AXIS];
  2309. homeaxis(Z_AXIS);
  2310. }
  2311. // Let's see if X and Y are homed and probe is inside bed area.
  2312. if(home_z) {
  2313. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2314. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2315. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2316. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2317. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2318. current_position[Z_AXIS] = 0;
  2319. plan_set_position_curposXYZE();
  2320. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2321. feedrate = max_feedrate[Z_AXIS];
  2322. plan_buffer_line_destinationXYZE(feedrate);
  2323. st_synchronize();
  2324. homeaxis(Z_AXIS);
  2325. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2326. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2327. SERIAL_ECHO_START;
  2328. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2329. } else {
  2330. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2331. SERIAL_ECHO_START;
  2332. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2333. }
  2334. }
  2335. #endif // Z_SAFE_HOMING
  2336. #endif // Z_HOME_DIR < 0
  2337. if(home_z_axis && home_z_value != 0)
  2338. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2339. #ifdef ENABLE_AUTO_BED_LEVELING
  2340. if(home_z)
  2341. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2342. #endif
  2343. // Set the planner and stepper routine positions.
  2344. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2345. // contains the machine coordinates.
  2346. plan_set_position_curposXYZE();
  2347. clean_up_after_endstop_move(l_feedmultiply);
  2348. endstops_hit_on_purpose();
  2349. // Load the machine correction matrix
  2350. world2machine_initialize();
  2351. // and correct the current_position XY axes to match the transformed coordinate system.
  2352. world2machine_update_current();
  2353. #ifdef MESH_BED_LEVELING
  2354. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2355. {
  2356. if (! home_z && mbl_was_active) {
  2357. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2358. mbl.active = true;
  2359. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2360. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2361. }
  2362. }
  2363. #endif
  2364. prusa_statistics(20);
  2365. st_synchronize();
  2366. homing_flag = false;
  2367. #if 0
  2368. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2369. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2370. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2371. #endif
  2372. }
  2373. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2374. {
  2375. #ifdef TMC2130
  2376. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2377. #else
  2378. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2379. #endif //TMC2130
  2380. }
  2381. // G80 - Automatic mesh bed leveling
  2382. static void gcode_G80()
  2383. {
  2384. st_synchronize();
  2385. if (planner_aborted)
  2386. return;
  2387. mesh_bed_leveling_flag = true;
  2388. #ifndef PINDA_THERMISTOR
  2389. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2390. #endif // ndef PINDA_THERMISTOR
  2391. #ifdef SUPPORT_VERBOSITY
  2392. int8_t verbosity_level = 0;
  2393. if (code_seen('V')) {
  2394. // Just 'V' without a number counts as V1.
  2395. char c = strchr_pointer[1];
  2396. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2397. }
  2398. #endif //SUPPORT_VERBOSITY
  2399. // Firstly check if we know where we are
  2400. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2401. // We don't know where we are! HOME!
  2402. // Push the commands to the front of the message queue in the reverse order!
  2403. // There shall be always enough space reserved for these commands.
  2404. repeatcommand_front(); // repeat G80 with all its parameters
  2405. enquecommand_front_P(G28W0);
  2406. return;
  2407. }
  2408. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2409. if (code_seen('N')) {
  2410. nMeasPoints = code_value_uint8();
  2411. if (nMeasPoints != 7) {
  2412. nMeasPoints = 3;
  2413. }
  2414. }
  2415. else {
  2416. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2417. }
  2418. uint8_t nProbeRetry = 3;
  2419. if (code_seen('R')) {
  2420. nProbeRetry = code_value_uint8();
  2421. if (nProbeRetry > 10) {
  2422. nProbeRetry = 10;
  2423. }
  2424. }
  2425. else {
  2426. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2427. }
  2428. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2429. #ifndef PINDA_THERMISTOR
  2430. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2431. {
  2432. temp_compensation_start();
  2433. run = true;
  2434. repeatcommand_front(); // repeat G80 with all its parameters
  2435. enquecommand_front_P(G28W0);
  2436. break;
  2437. }
  2438. run = false;
  2439. #endif //PINDA_THERMISTOR
  2440. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2441. CustomMsg custom_message_type_old = custom_message_type;
  2442. uint8_t custom_message_state_old = custom_message_state;
  2443. custom_message_type = CustomMsg::MeshBedLeveling;
  2444. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2445. lcd_update(1);
  2446. mbl.reset(); //reset mesh bed leveling
  2447. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2448. babystep_undo();
  2449. // Cycle through all points and probe them
  2450. // First move up. During this first movement, the babystepping will be reverted.
  2451. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2452. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2453. // The move to the first calibration point.
  2454. current_position[X_AXIS] = BED_X0;
  2455. current_position[Y_AXIS] = BED_Y0;
  2456. #ifdef SUPPORT_VERBOSITY
  2457. if (verbosity_level >= 1)
  2458. {
  2459. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2460. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2461. }
  2462. #else //SUPPORT_VERBOSITY
  2463. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2464. #endif //SUPPORT_VERBOSITY
  2465. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2466. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2467. // Wait until the move is finished.
  2468. st_synchronize();
  2469. if (planner_aborted)
  2470. {
  2471. custom_message_type = custom_message_type_old;
  2472. custom_message_state = custom_message_state_old;
  2473. return;
  2474. }
  2475. uint8_t mesh_point = 0; //index number of calibration point
  2476. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2477. 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)
  2478. #ifdef SUPPORT_VERBOSITY
  2479. if (verbosity_level >= 1) {
  2480. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2481. }
  2482. #endif // SUPPORT_VERBOSITY
  2483. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2484. while (mesh_point != nMeasPoints * nMeasPoints) {
  2485. // Get coords of a measuring point.
  2486. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2487. uint8_t iy = mesh_point / nMeasPoints;
  2488. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2489. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2490. custom_message_state--;
  2491. mesh_point++;
  2492. continue; //skip
  2493. }*/
  2494. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2495. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2496. {
  2497. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2498. }
  2499. float z0 = 0.f;
  2500. if (has_z && (mesh_point > 0)) {
  2501. uint16_t z_offset_u = 0;
  2502. if (nMeasPoints == 7) {
  2503. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2504. }
  2505. else {
  2506. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2507. }
  2508. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2509. #ifdef SUPPORT_VERBOSITY
  2510. if (verbosity_level >= 1) {
  2511. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2512. }
  2513. #endif // SUPPORT_VERBOSITY
  2514. }
  2515. // Move Z up to MESH_HOME_Z_SEARCH.
  2516. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2517. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2518. float init_z_bckp = current_position[Z_AXIS];
  2519. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2520. st_synchronize();
  2521. // Move to XY position of the sensor point.
  2522. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2523. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2524. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2525. #ifdef SUPPORT_VERBOSITY
  2526. if (verbosity_level >= 1) {
  2527. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2528. SERIAL_PROTOCOL(mesh_point);
  2529. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2530. }
  2531. #else //SUPPORT_VERBOSITY
  2532. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2533. #endif // SUPPORT_VERBOSITY
  2534. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2535. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2536. st_synchronize();
  2537. if (planner_aborted)
  2538. {
  2539. custom_message_type = custom_message_type_old;
  2540. custom_message_state = custom_message_state_old;
  2541. return;
  2542. }
  2543. // Go down until endstop is hit
  2544. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2545. 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
  2546. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2547. break;
  2548. }
  2549. 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.
  2550. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2551. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2552. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2553. st_synchronize();
  2554. 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
  2555. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2556. break;
  2557. }
  2558. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2559. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2560. break;
  2561. }
  2562. }
  2563. 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
  2564. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2565. break;
  2566. }
  2567. #ifdef SUPPORT_VERBOSITY
  2568. if (verbosity_level >= 10) {
  2569. SERIAL_ECHOPGM("X: ");
  2570. MYSERIAL.print(current_position[X_AXIS], 5);
  2571. SERIAL_ECHOLNPGM("");
  2572. SERIAL_ECHOPGM("Y: ");
  2573. MYSERIAL.print(current_position[Y_AXIS], 5);
  2574. SERIAL_PROTOCOLPGM("\n");
  2575. }
  2576. #endif // SUPPORT_VERBOSITY
  2577. float offset_z = 0;
  2578. #ifdef PINDA_THERMISTOR
  2579. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2580. #endif //PINDA_THERMISTOR
  2581. // #ifdef SUPPORT_VERBOSITY
  2582. /* if (verbosity_level >= 1)
  2583. {
  2584. SERIAL_ECHOPGM("mesh bed leveling: ");
  2585. MYSERIAL.print(current_position[Z_AXIS], 5);
  2586. SERIAL_ECHOPGM(" offset: ");
  2587. MYSERIAL.print(offset_z, 5);
  2588. SERIAL_ECHOLNPGM("");
  2589. }*/
  2590. // #endif // SUPPORT_VERBOSITY
  2591. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2592. custom_message_state--;
  2593. mesh_point++;
  2594. lcd_update(1);
  2595. }
  2596. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2597. #ifdef SUPPORT_VERBOSITY
  2598. if (verbosity_level >= 20) {
  2599. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2600. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2601. MYSERIAL.print(current_position[Z_AXIS], 5);
  2602. }
  2603. #endif // SUPPORT_VERBOSITY
  2604. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2605. st_synchronize();
  2606. if (mesh_point != nMeasPoints * nMeasPoints) {
  2607. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2608. bool bState;
  2609. do { // repeat until Z-leveling o.k.
  2610. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2611. #ifdef TMC2130
  2612. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2613. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2614. #else // TMC2130
  2615. lcd_wait_for_click_delay(0); // ~ no timeout
  2616. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2617. #endif // TMC2130
  2618. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2619. bState=enable_z_endstop(false);
  2620. raise_z(-1);
  2621. enable_z_endstop(true);
  2622. #ifdef TMC2130
  2623. tmc2130_home_enter(Z_AXIS_MASK);
  2624. #endif // TMC2130
  2625. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2626. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2627. st_synchronize();
  2628. #ifdef TMC2130
  2629. tmc2130_home_exit();
  2630. #endif // TMC2130
  2631. enable_z_endstop(bState);
  2632. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2633. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2634. custom_message_type = custom_message_type_old;
  2635. custom_message_state = custom_message_state_old;
  2636. lcd_update_enable(true); // display / status-line recovery
  2637. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2638. repeatcommand_front(); // re-run (i.e. of "G80")
  2639. return;
  2640. }
  2641. clean_up_after_endstop_move(l_feedmultiply);
  2642. // SERIAL_ECHOLNPGM("clean up finished ");
  2643. #ifndef PINDA_THERMISTOR
  2644. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2645. #endif
  2646. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2647. // SERIAL_ECHOLNPGM("babystep applied");
  2648. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2649. #ifdef SUPPORT_VERBOSITY
  2650. if (verbosity_level >= 1) {
  2651. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2652. }
  2653. #endif // SUPPORT_VERBOSITY
  2654. for (uint8_t i = 0; i < 4; ++i) {
  2655. static const char codes[4] PROGMEM = { 'L', 'R', 'F', 'B' };
  2656. static uint8_t *const eep_addresses[4] PROGMEM = {
  2657. (uint8_t*)EEPROM_BED_CORRECTION_LEFT,
  2658. (uint8_t*)EEPROM_BED_CORRECTION_RIGHT,
  2659. (uint8_t*)EEPROM_BED_CORRECTION_FRONT,
  2660. (uint8_t*)EEPROM_BED_CORRECTION_REAR,
  2661. };
  2662. long correction = 0;
  2663. if (code_seen(pgm_read_byte(&codes[i])))
  2664. correction = code_value_long();
  2665. else if (eeprom_bed_correction_valid)
  2666. correction = (int8_t)eeprom_read_byte((uint8_t*)pgm_read_ptr(&eep_addresses[i]));
  2667. if (correction == 0)
  2668. continue;
  2669. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2670. SERIAL_ERROR_START;
  2671. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2672. SERIAL_ECHO(correction);
  2673. SERIAL_ECHOLNPGM(" microns");
  2674. }
  2675. else {
  2676. float offset = float(correction) * 0.001f;
  2677. switch (i) {
  2678. case 0:
  2679. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2680. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2681. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2682. }
  2683. }
  2684. break;
  2685. case 1:
  2686. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2687. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2688. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2689. }
  2690. }
  2691. break;
  2692. case 2:
  2693. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2694. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2695. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2696. }
  2697. }
  2698. break;
  2699. case 3:
  2700. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2701. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2702. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2703. }
  2704. }
  2705. break;
  2706. }
  2707. }
  2708. }
  2709. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2710. if (nMeasPoints == 3) {
  2711. 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)
  2712. }
  2713. /*
  2714. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2715. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2716. SERIAL_PROTOCOLPGM(",");
  2717. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2718. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2719. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2720. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2721. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2722. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2723. SERIAL_PROTOCOLPGM(" ");
  2724. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2725. }
  2726. SERIAL_PROTOCOLPGM("\n");
  2727. }
  2728. */
  2729. if (nMeasPoints == 7 && magnet_elimination) {
  2730. mbl_interpolation(nMeasPoints);
  2731. }
  2732. /*
  2733. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2734. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2735. SERIAL_PROTOCOLPGM(",");
  2736. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2737. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2738. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2739. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2740. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2741. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2742. SERIAL_PROTOCOLPGM(" ");
  2743. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2744. }
  2745. SERIAL_PROTOCOLPGM("\n");
  2746. }
  2747. */
  2748. // SERIAL_ECHOLNPGM("Upsample finished");
  2749. mbl.active = 1; //activate mesh bed leveling
  2750. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2751. go_home_with_z_lift();
  2752. // SERIAL_ECHOLNPGM("Go home finished");
  2753. //unretract (after PINDA preheat retraction)
  2754. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2755. current_position[E_AXIS] += default_retraction;
  2756. plan_buffer_line_curposXYZE(400);
  2757. }
  2758. KEEPALIVE_STATE(NOT_BUSY);
  2759. // Restore custom message state
  2760. lcd_setstatuspgm(MSG_WELCOME);
  2761. custom_message_type = custom_message_type_old;
  2762. custom_message_state = custom_message_state_old;
  2763. lcd_update(2);
  2764. st_synchronize();
  2765. mesh_bed_leveling_flag = false;
  2766. }
  2767. void adjust_bed_reset()
  2768. {
  2769. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2770. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2771. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2772. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2773. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2774. }
  2775. //! @brief Calibrate XYZ
  2776. //! @param onlyZ if true, calibrate only Z axis
  2777. //! @param verbosity_level
  2778. //! @retval true Succeeded
  2779. //! @retval false Failed
  2780. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2781. {
  2782. bool final_result = false;
  2783. #ifdef TMC2130
  2784. FORCE_HIGH_POWER_START;
  2785. #endif // TMC2130
  2786. FORCE_BL_ON_START;
  2787. // Only Z calibration?
  2788. if (!onlyZ)
  2789. {
  2790. setTargetBed(0);
  2791. setAllTargetHotends(0);
  2792. adjust_bed_reset(); //reset bed level correction
  2793. }
  2794. // Disable the default update procedure of the display. We will do a modal dialog.
  2795. lcd_update_enable(false);
  2796. // Let the planner use the uncorrected coordinates.
  2797. mbl.reset();
  2798. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2799. // the planner will not perform any adjustments in the XY plane.
  2800. // Wait for the motors to stop and update the current position with the absolute values.
  2801. world2machine_revert_to_uncorrected();
  2802. // Reset the baby step value applied without moving the axes.
  2803. babystep_reset();
  2804. // Mark all axes as in a need for homing.
  2805. memset(axis_known_position, 0, sizeof(axis_known_position));
  2806. // Home in the XY plane.
  2807. //set_destination_to_current();
  2808. int l_feedmultiply = setup_for_endstop_move();
  2809. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2810. raise_z_above(MESH_HOME_Z_SEARCH);
  2811. home_xy();
  2812. enable_endstops(false);
  2813. current_position[X_AXIS] += 5;
  2814. current_position[Y_AXIS] += 5;
  2815. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2816. st_synchronize();
  2817. // Let the user move the Z axes up to the end stoppers.
  2818. #ifdef TMC2130
  2819. if (calibrate_z_auto())
  2820. {
  2821. #else //TMC2130
  2822. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2823. {
  2824. #endif //TMC2130
  2825. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2826. if(onlyZ){
  2827. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2828. lcd_puts_at_P(0,3,_n("1/9"));
  2829. }else{
  2830. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2831. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2832. lcd_puts_at_P(0,3,_n("1/4"));
  2833. }
  2834. refresh_cmd_timeout();
  2835. #ifndef STEEL_SHEET
  2836. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2837. {
  2838. lcd_wait_for_cool_down();
  2839. }
  2840. #endif //STEEL_SHEET
  2841. if(!onlyZ)
  2842. {
  2843. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2844. #ifdef STEEL_SHEET
  2845. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  2846. if(result == LCD_LEFT_BUTTON_CHOICE) {
  2847. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2848. }
  2849. #endif //STEEL_SHEET
  2850. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2851. KEEPALIVE_STATE(IN_HANDLER);
  2852. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2853. lcd_puts_at_P(0,3,_n("1/4"));
  2854. }
  2855. bool endstops_enabled = enable_endstops(false);
  2856. raise_z(-1);
  2857. // Move the print head close to the bed.
  2858. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2859. enable_endstops(true);
  2860. #ifdef TMC2130
  2861. tmc2130_home_enter(Z_AXIS_MASK);
  2862. #endif //TMC2130
  2863. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2864. st_synchronize();
  2865. #ifdef TMC2130
  2866. tmc2130_home_exit();
  2867. #endif //TMC2130
  2868. enable_endstops(endstops_enabled);
  2869. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2870. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2871. {
  2872. if (onlyZ)
  2873. {
  2874. clean_up_after_endstop_move(l_feedmultiply);
  2875. // Z only calibration.
  2876. // Load the machine correction matrix
  2877. world2machine_initialize();
  2878. // and correct the current_position to match the transformed coordinate system.
  2879. world2machine_update_current();
  2880. //FIXME
  2881. bool result = sample_mesh_and_store_reference();
  2882. if (result)
  2883. {
  2884. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2885. {
  2886. // Shipped, the nozzle height has been set already. The user can start printing now.
  2887. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2888. }
  2889. final_result = true;
  2890. // babystep_apply();
  2891. }
  2892. }
  2893. else
  2894. {
  2895. // Reset the baby step value and the baby step applied flag.
  2896. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2897. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2898. // Complete XYZ calibration.
  2899. uint8_t point_too_far_mask = 0;
  2900. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2901. clean_up_after_endstop_move(l_feedmultiply);
  2902. // Print head up.
  2903. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2904. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2905. st_synchronize();
  2906. //#ifndef NEW_XYZCAL
  2907. if (result >= 0)
  2908. {
  2909. #ifdef HEATBED_V2
  2910. sample_z();
  2911. #else //HEATBED_V2
  2912. point_too_far_mask = 0;
  2913. // Second half: The fine adjustment.
  2914. // Let the planner use the uncorrected coordinates.
  2915. mbl.reset();
  2916. world2machine_reset();
  2917. // Home in the XY plane.
  2918. int l_feedmultiply = setup_for_endstop_move();
  2919. home_xy();
  2920. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2921. clean_up_after_endstop_move(l_feedmultiply);
  2922. // Print head up.
  2923. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2924. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2925. st_synchronize();
  2926. // if (result >= 0) babystep_apply();
  2927. #endif //HEATBED_V2
  2928. }
  2929. //#endif //NEW_XYZCAL
  2930. lcd_update_enable(true);
  2931. lcd_update(2);
  2932. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2933. if (result >= 0)
  2934. {
  2935. #ifdef TEMP_MODEL
  2936. calibration_status_store(CALIBRATION_STATUS_TEMP_MODEL_CALIBRATION);
  2937. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_TM_NOT_CAL));
  2938. #else
  2939. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2940. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2941. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2942. #endif //TEMP_MODEL
  2943. final_result = true;
  2944. }
  2945. }
  2946. #ifdef TMC2130
  2947. tmc2130_home_exit();
  2948. #endif
  2949. }
  2950. else
  2951. {
  2952. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2953. final_result = false;
  2954. }
  2955. }
  2956. else
  2957. {
  2958. // Timeouted.
  2959. }
  2960. lcd_update_enable(true);
  2961. #ifdef TMC2130
  2962. FORCE_HIGH_POWER_END;
  2963. #endif // TMC2130
  2964. FORCE_BL_ON_END;
  2965. return final_result;
  2966. }
  2967. void gcode_M114()
  2968. {
  2969. SERIAL_PROTOCOLPGM("X:");
  2970. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2971. SERIAL_PROTOCOLPGM(" Y:");
  2972. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2973. SERIAL_PROTOCOLPGM(" Z:");
  2974. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2975. SERIAL_PROTOCOLPGM(" E:");
  2976. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2977. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2978. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2979. SERIAL_PROTOCOLPGM(" Y:");
  2980. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2981. SERIAL_PROTOCOLPGM(" Z:");
  2982. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2983. SERIAL_PROTOCOLPGM(" E:");
  2984. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  2985. }
  2986. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  2987. void gcode_M123()
  2988. {
  2989. 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);
  2990. }
  2991. #endif //FANCHECK and TACH_0 or TACH_1
  2992. static void mmu_M600_wait_and_beep() {
  2993. // Beep and wait for user to remove old filament and prepare new filament for load
  2994. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2995. int counterBeep = 0;
  2996. 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
  2997. bool bFirst = true;
  2998. while (!lcd_clicked()) {
  2999. manage_heater();
  3000. manage_inactivity(true);
  3001. #if BEEPER > 0
  3002. if (counterBeep == 500) {
  3003. counterBeep = 0;
  3004. }
  3005. SET_OUTPUT(BEEPER);
  3006. if (counterBeep == 0) {
  3007. if ((eSoundMode == e_SOUND_MODE_BLIND) || (eSoundMode == e_SOUND_MODE_LOUD) || ((eSoundMode == e_SOUND_MODE_ONCE) && bFirst)) {
  3008. bFirst = false;
  3009. WRITE(BEEPER, HIGH);
  3010. }
  3011. }
  3012. if (counterBeep == 20) {
  3013. WRITE(BEEPER, LOW);
  3014. }
  3015. counterBeep++;
  3016. #endif // BEEPER > 0
  3017. delay_keep_alive(4);
  3018. }
  3019. WRITE(BEEPER, LOW);
  3020. }
  3021. /**
  3022. * @brief Handling of unload when using MMU with M600
  3023. * A fullscreen message showing "Unloading Filament x"
  3024. * should be shown on the LCD and LCD updates should be
  3025. * are disabled in the meantime.
  3026. */
  3027. static void mmu_M600_unload_filament() {
  3028. if (MMU2::mmu2.get_current_tool() == (uint8_t)MMU2::FILAMENT_UNKNOWN) return;
  3029. lcd_update_enable(false);
  3030. lcd_clear();
  3031. lcd_puts_at_P(0, 1, _T(MSG_UNLOADING_FILAMENT));
  3032. lcd_print(' ');
  3033. lcd_print(MMU2::mmu2.get_current_tool() + 1);
  3034. // unload just current filament for multimaterial printers (used also in M702)
  3035. MMU2::mmu2.unload();
  3036. lcd_update_enable(true);
  3037. }
  3038. /// @brief load filament for mmu v2
  3039. /// @par nozzle_temp nozzle temperature to load filament
  3040. static void mmu_M600_load_filament(bool automatic, float nozzle_temp) {
  3041. uint8_t slot;
  3042. if (automatic) {
  3043. slot = SpoolJoin::spooljoin.nextSlot();
  3044. } else {
  3045. // Only ask for the slot if automatic/SpoolJoin is off
  3046. slot = choose_menu_P(_T(MSG_SELECT_EXTRUDER), _T(MSG_EXTRUDER));
  3047. }
  3048. setTargetHotend(nozzle_temp, active_extruder);
  3049. MMU2::mmu2.load_filament_to_nozzle(slot);
  3050. load_filament_final_feed(); // @@TODO verify
  3051. st_synchronize();
  3052. }
  3053. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3054. st_synchronize();
  3055. float lastpos[4];
  3056. prusa_statistics(22);
  3057. //First backup current position and settings
  3058. int feedmultiplyBckp = feedmultiply;
  3059. float HotendTempBckp = degTargetHotend(active_extruder);
  3060. int fanSpeedBckp = fanSpeed;
  3061. memcpy(lastpos, current_position, sizeof(lastpos));
  3062. // Turn off the fan
  3063. fanSpeed = 0;
  3064. // Retract E
  3065. current_position[E_AXIS] += e_shift;
  3066. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3067. st_synchronize();
  3068. // Raise the Z axis
  3069. raise_z(z_shift);
  3070. // Move XY to side
  3071. current_position[X_AXIS] = x_position;
  3072. current_position[Y_AXIS] = y_position;
  3073. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3074. st_synchronize();
  3075. // Beep, manage nozzle heater and wait for user to start unload filament
  3076. if (!MMU2::mmu2.Enabled())
  3077. M600_wait_for_user(HotendTempBckp);
  3078. // Unload filament
  3079. if (MMU2::mmu2.Enabled())
  3080. mmu_M600_unload_filament();
  3081. else
  3082. unload_filament(FILAMENTCHANGE_FINALRETRACT, true); // unload filament for single material (used also in M702)
  3083. st_synchronize(); // finish moves
  3084. {
  3085. FSensorBlockRunout fsBlockRunout;
  3086. if (!MMU2::mmu2.Enabled())
  3087. {
  3088. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3089. uint8_t choice =
  3090. 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
  3091. if (choice == LCD_MIDDLE_BUTTON_CHOICE) {
  3092. lcd_clear();
  3093. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3094. current_position[X_AXIS] -= 100;
  3095. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3096. st_synchronize();
  3097. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually.")); ////MSG_CHECK_IDLER c=20 r=5
  3098. }
  3099. M600_load_filament();
  3100. }
  3101. else // MMU is enabled
  3102. {
  3103. if (!automatic) {
  3104. if (saved_printing){
  3105. // if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3106. MMU2::mmu2.eject_filament(MMU2::mmu2.get_current_tool(), false);
  3107. }
  3108. mmu_M600_wait_and_beep();
  3109. if (saved_printing) {
  3110. lcd_clear();
  3111. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3112. //@@TODO mmu_command(MmuCmd::R0);
  3113. // manage_response(false, false);
  3114. }
  3115. }
  3116. mmu_M600_load_filament(automatic, HotendTempBckp);
  3117. }
  3118. if (!automatic)
  3119. M600_check_state(HotendTempBckp);
  3120. lcd_update_enable(true);
  3121. // Not let's go back to print
  3122. fanSpeed = fanSpeedBckp;
  3123. // Feed a little of filament to stabilize pressure
  3124. if (!automatic) {
  3125. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3126. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3127. }
  3128. // Move XY back
  3129. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3130. st_synchronize();
  3131. // Move Z back
  3132. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3133. st_synchronize();
  3134. // Set E position to original
  3135. plan_set_e_position(lastpos[E_AXIS]);
  3136. memcpy(current_position, lastpos, sizeof(lastpos));
  3137. set_destination_to_current();
  3138. // Recover feed rate
  3139. feedmultiply = feedmultiplyBckp;
  3140. char cmd[9];
  3141. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3142. enquecommand(cmd);
  3143. }
  3144. lcd_setstatuspgm(MSG_WELCOME);
  3145. custom_message_type = CustomMsg::Status;
  3146. }
  3147. void gcode_M701(float fastLoadLength, uint8_t mmuSlotIndex){
  3148. FSensorBlockRunout fsBlockRunout;
  3149. prusa_statistics(22);
  3150. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3151. MMU2::mmu2.load_filament_to_nozzle(mmuSlotIndex);
  3152. } else {
  3153. custom_message_type = CustomMsg::FilamentLoading;
  3154. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3155. current_position[E_AXIS] += fastLoadLength;
  3156. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3157. load_filament_final_feed(); // slow sequence
  3158. st_synchronize();
  3159. Sound_MakeCustom(50, 500, false);
  3160. if (!farm_mode && loading_flag) {
  3161. lcd_load_filament_color_check();
  3162. }
  3163. lcd_update_enable(true);
  3164. lcd_update(2);
  3165. lcd_setstatuspgm(MSG_WELCOME);
  3166. loading_flag = false;
  3167. custom_message_type = CustomMsg::Status;
  3168. }
  3169. eFilamentAction = FilamentAction::None;
  3170. }
  3171. // Common gcode shared by the gcodes. This saves some flash memory
  3172. static void gcodes_M704_M705_M706(uint16_t gcode)
  3173. {
  3174. uint8_t mmuSlotIndex = 0xffU;
  3175. if (MMU2::mmu2.Enabled() && code_seen('P'))
  3176. {
  3177. mmuSlotIndex = code_value_uint8();
  3178. if (mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3179. switch (gcode)
  3180. {
  3181. case 704:
  3182. MMU2::mmu2.load_filament(mmuSlotIndex);
  3183. break;
  3184. case 705:
  3185. MMU2::mmu2.eject_filament(mmuSlotIndex, false);
  3186. break;
  3187. case 706:
  3188. #ifdef MMU_HAS_CUTTER
  3189. if (eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED) != 0){
  3190. MMU2::mmu2.cut_filament(mmuSlotIndex);
  3191. }
  3192. #endif // MMU_HAS_CUTTER
  3193. break;
  3194. default:
  3195. break;
  3196. }
  3197. }
  3198. }
  3199. }
  3200. /**
  3201. * @brief Get serial number from 32U2 processor
  3202. *
  3203. * Typical format of S/N is:CZPX0917X003XC13518
  3204. *
  3205. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3206. * reply is stored in *SN.
  3207. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3208. * and returns a general failure flag.
  3209. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3210. * In that case the value that is stored in the EEPROM should be used instead.
  3211. *
  3212. * @return 0 on success
  3213. * @return 1 on general failure
  3214. */
  3215. #ifdef PRUSA_SN_SUPPORT
  3216. static uint8_t get_PRUSA_SN(char* SN)
  3217. {
  3218. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3219. uint8_t rxIndex;
  3220. bool SN_valid = false;
  3221. ShortTimer timeout;
  3222. selectedSerialPort = 0;
  3223. timeout.start();
  3224. while (!SN_valid)
  3225. {
  3226. rxIndex = 0;
  3227. _delay(50);
  3228. MYSERIAL.flush(); //clear RX buffer
  3229. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3230. while (rxIndex < 19)
  3231. {
  3232. if (timeout.expired(250u))
  3233. goto exit;
  3234. if (MYSERIAL.available() > 0)
  3235. {
  3236. SN[rxIndex] = MYSERIAL.read();
  3237. rxIndex++;
  3238. }
  3239. }
  3240. SN[rxIndex] = 0;
  3241. // printf_P(PSTR("SN:%s\n"), SN);
  3242. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3243. }
  3244. exit:
  3245. selectedSerialPort = selectedSerialPort_bak;
  3246. return !SN_valid;
  3247. }
  3248. #endif //PRUSA_SN_SUPPORT
  3249. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3250. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3251. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3252. //! it may even interfere with other functions of the printer! You have been warned!
  3253. //! The test idea is to measure the time necessary to charge the capacitor.
  3254. //! So the algorithm is as follows:
  3255. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3256. //! 2. Wait a few ms
  3257. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3258. //! Repeat 1.-3. several times
  3259. //! Good RAMBo's times are in the range of approx. 260-320 us
  3260. //! Bad RAMBo's times are approx. 260-1200 us
  3261. //! So basically we are interested in maximum time, the minima are mostly the same.
  3262. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3263. static void gcode_PRUSA_BadRAMBoFanTest(){
  3264. //printf_P(PSTR("Enter fan pin test\n"));
  3265. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3266. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3267. unsigned long tach1max = 0;
  3268. uint8_t tach1cntr = 0;
  3269. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3270. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3271. SET_OUTPUT(TACH_1);
  3272. WRITE(TACH_1, LOW);
  3273. _delay(20); // the delay may be lower
  3274. unsigned long tachMeasure = _micros();
  3275. cli();
  3276. SET_INPUT(TACH_1);
  3277. // just wait brutally in an endless cycle until we reach HIGH
  3278. // if this becomes a problem it may be improved to non-endless cycle
  3279. while( READ(TACH_1) == 0 ) ;
  3280. sei();
  3281. tachMeasure = _micros() - tachMeasure;
  3282. if( tach1max < tachMeasure )
  3283. tach1max = tachMeasure;
  3284. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3285. }
  3286. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3287. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3288. if( tach1max > 500 ){
  3289. // bad RAMBo
  3290. SERIAL_PROTOCOLLNPGM("BAD");
  3291. } else {
  3292. SERIAL_PROTOCOLLNPGM("OK");
  3293. }
  3294. // cleanup after the test function
  3295. SET_INPUT(TACH_1);
  3296. WRITE(TACH_1, HIGH);
  3297. #endif
  3298. }
  3299. // G92 - Set current position to coordinates given
  3300. static void gcode_G92()
  3301. {
  3302. bool codes[NUM_AXIS];
  3303. float values[NUM_AXIS];
  3304. // Check which axes need to be set
  3305. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3306. {
  3307. codes[i] = code_seen(axis_codes[i]);
  3308. if(codes[i])
  3309. values[i] = code_value();
  3310. }
  3311. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3312. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3313. {
  3314. // As a special optimization, when _just_ clearing the E position
  3315. // we schedule a flag asynchronously along with the next block to
  3316. // reset the starting E position instead of stopping the planner
  3317. current_position[E_AXIS] = 0;
  3318. plan_reset_next_e();
  3319. }
  3320. else
  3321. {
  3322. // In any other case we're forced to synchronize
  3323. st_synchronize();
  3324. for(uint8_t i = 0; i < 3; ++i)
  3325. {
  3326. if(codes[i])
  3327. current_position[i] = values[i] + cs.add_homing[i];
  3328. }
  3329. if(codes[E_AXIS])
  3330. current_position[E_AXIS] = values[E_AXIS];
  3331. // Set all at once
  3332. plan_set_position_curposXYZE();
  3333. }
  3334. }
  3335. #ifdef EXTENDED_CAPABILITIES_REPORT
  3336. static void cap_line(const char* name, bool ena = false) {
  3337. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3338. }
  3339. static void extended_capabilities_report()
  3340. {
  3341. // AUTOREPORT_TEMP (M155)
  3342. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3343. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3344. // AUTOREPORT_FANS (M123)
  3345. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3346. #endif //FANCHECK and TACH_0 or TACH_1
  3347. // AUTOREPORT_POSITION (M114)
  3348. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3349. // EXTENDED_M20 (support for L and T parameters)
  3350. cap_line(PSTR("EXTENDED_M20"), 1);
  3351. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3352. }
  3353. #endif //EXTENDED_CAPABILITIES_REPORT
  3354. #ifdef BACKLASH_X
  3355. extern uint8_t st_backlash_x;
  3356. #endif //BACKLASH_X
  3357. #ifdef BACKLASH_Y
  3358. extern uint8_t st_backlash_y;
  3359. #endif //BACKLASH_Y
  3360. //! \ingroup marlin_main
  3361. //! @brief Parse and process commands
  3362. //!
  3363. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3364. //!
  3365. //!
  3366. //! Implemented Codes
  3367. //! -------------------
  3368. //!
  3369. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3370. //!
  3371. //!@n PRUSA CODES
  3372. //!@n P F - Returns FW versions
  3373. //!@n P R - Returns revision of printer
  3374. //!
  3375. //!@n G0 -> G1
  3376. //!@n G1 - Coordinated Movement X Y Z E
  3377. //!@n G2 - CW ARC
  3378. //!@n G3 - CCW ARC
  3379. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3380. //!@n G10 - retract filament according to settings of M207
  3381. //!@n G11 - retract recover filament according to settings of M208
  3382. //!@n G28 - Home all Axes
  3383. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3384. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3385. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3386. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3387. //!@n G80 - Automatic mesh bed leveling
  3388. //!@n G81 - Print bed profile
  3389. //!@n G90 - Use Absolute Coordinates
  3390. //!@n G91 - Use Relative Coordinates
  3391. //!@n G92 - Set current position to coordinates given
  3392. //!
  3393. //!@n M Codes
  3394. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3395. //!@n M1 - Same as M0
  3396. //!@n M17 - Enable/Power all stepper motors
  3397. //!@n M18 - Disable all stepper motors; same as M84
  3398. //!@n M20 - List SD card
  3399. //!@n M21 - Init SD card
  3400. //!@n M22 - Release SD card
  3401. //!@n M23 - Select SD file (M23 filename.g)
  3402. //!@n M24 - Start/resume SD print
  3403. //!@n M25 - Pause SD print
  3404. //!@n M26 - Set SD position in bytes (M26 S12345)
  3405. //!@n M27 - Report SD print status
  3406. //!@n M28 - Start SD write (M28 filename.g)
  3407. //!@n M29 - Stop SD write
  3408. //!@n M30 - Delete file from SD (M30 filename.g)
  3409. //!@n M31 - Output time since last M109 or SD card start to serial
  3410. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3411. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3412. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3413. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3414. //!@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.
  3415. //!@n M73 - Show percent done and print time remaining
  3416. //!@n M80 - Turn on Power Supply
  3417. //!@n M81 - Turn off Power Supply
  3418. //!@n M82 - Set E codes absolute (default)
  3419. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3420. //!@n M84 - Disable steppers until next move,
  3421. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3422. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3423. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3424. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3425. //!@n M104 - Set extruder target temp
  3426. //!@n M105 - Read current temp
  3427. //!@n M106 - Fan on
  3428. //!@n M107 - Fan off
  3429. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3430. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3431. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3432. //!@n M112 - Emergency stop
  3433. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3434. //!@n M114 - Output current position to serial port
  3435. //!@n M115 - Capabilities string
  3436. //!@n M117 - display message
  3437. //!@n M119 - Output Endstop status to serial port
  3438. //!@n M123 - Tachometer value
  3439. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3440. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3441. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3442. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3443. //!@n M140 - Set bed target temp
  3444. //!@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.
  3445. //!@n M155 - Automatically send temperatures, fan speeds, position
  3446. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3447. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3448. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3449. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3450. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3451. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3452. //!@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
  3453. //!@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
  3454. //!@n M206 - set additional homing offset
  3455. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3456. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3457. //!@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.
  3458. //!@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>
  3459. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3460. //!@n M220 S<factor in percent>- set speed factor override percentage
  3461. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3462. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3463. //!@n M240 - Trigger a camera to take a photograph
  3464. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3465. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3466. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3467. //!@n M301 - Set PID parameters P I and D
  3468. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3469. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3470. //!@n M304 - Set bed PID parameters P I and D
  3471. //!@n M310 - Temperature model settings
  3472. //!@n M400 - Finish all moves
  3473. //!@n M401 - Lower z-probe if present
  3474. //!@n M402 - Raise z-probe if present
  3475. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3476. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3477. //!@n M406 - Turn off Filament Sensor extrusion control
  3478. //!@n M407 - Displays measured filament diameter
  3479. //!@n M500 - stores parameters in EEPROM
  3480. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3481. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3482. //!@n M503 - print the current settings (from memory not from EEPROM)
  3483. //!@n M509 - force language selection on next restart
  3484. //!@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)
  3485. //!@n M552 - Set IP address
  3486. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3487. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3488. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3489. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3490. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3491. //!@n M907 - Set digital trimpot motor current using axis codes.
  3492. //!@n M908 - Control digital trimpot directly.
  3493. //!@n M350 - Set microstepping mode.
  3494. //!@n M351 - Toggle MS1 MS2 pins directly.
  3495. //!
  3496. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3497. //!@n M999 - Restart after being stopped by error
  3498. //! <br><br>
  3499. /** @defgroup marlin_main Marlin main */
  3500. /** \ingroup GCodes */
  3501. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3502. /**
  3503. They are shown in order of appearance in the code.
  3504. There are reasons why some G Codes aren't in numerical order.
  3505. */
  3506. void process_commands()
  3507. {
  3508. if (!buflen) return; //empty command
  3509. #ifdef CMDBUFFER_DEBUG
  3510. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3511. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3512. SERIAL_ECHOLNPGM("");
  3513. SERIAL_ECHOPGM("In cmdqueue: ");
  3514. SERIAL_ECHO(buflen);
  3515. SERIAL_ECHOLNPGM("");
  3516. #endif /* CMDBUFFER_DEBUG */
  3517. unsigned long codenum; //throw away variable
  3518. char *starpos = NULL;
  3519. #ifdef ENABLE_AUTO_BED_LEVELING
  3520. float x_tmp, y_tmp, z_tmp, real_z;
  3521. #endif
  3522. // PRUSA GCODES
  3523. KEEPALIVE_STATE(IN_HANDLER);
  3524. /*!
  3525. ---------------------------------------------------------------------------------
  3526. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3527. This causes the given message to be shown in the status line on an attached LCD.
  3528. It is processed early as to allow printing messages that contain G, M, N or T.
  3529. ---------------------------------------------------------------------------------
  3530. ### Special internal commands
  3531. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3532. They are processed early as the commands are complex (strings).
  3533. These are only available on the MK3(S) as these require TMC2130 drivers:
  3534. - CRASH DETECTED
  3535. - CRASH RECOVER
  3536. - CRASH_CANCEL
  3537. - TMC_SET_WAVE
  3538. - TMC_SET_STEP
  3539. - TMC_SET_CHOP
  3540. */
  3541. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3542. {
  3543. starpos = (strchr(strchr_pointer + 5, '*'));
  3544. if (starpos != NULL)
  3545. *(starpos) = '\0';
  3546. lcd_setstatus(strchr_pointer + 5);
  3547. custom_message_type = CustomMsg::M117;
  3548. }
  3549. /*!
  3550. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3551. #### Usage
  3552. M0 [P<ms<] [S<sec>] [string]
  3553. M1 [P<ms>] [S<sec>] [string]
  3554. #### Parameters
  3555. - `P<ms>` - Expire time, in milliseconds
  3556. - `S<sec>` - Expire time, in seconds
  3557. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3558. */
  3559. 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
  3560. const char *src = strchr_pointer + 2;
  3561. codenum = 0;
  3562. bool hasP = false, hasS = false;
  3563. if (code_seen('P')) {
  3564. codenum = code_value_long(); // milliseconds to wait
  3565. hasP = codenum > 0;
  3566. }
  3567. if (code_seen('S')) {
  3568. codenum = code_value_long() * 1000; // seconds to wait
  3569. hasS = codenum > 0;
  3570. }
  3571. starpos = strchr(src, '*');
  3572. if (starpos != NULL) *(starpos) = '\0';
  3573. while (*src == ' ') ++src;
  3574. custom_message_type = CustomMsg::M0Wait;
  3575. if (!hasP && !hasS && *src != '\0') {
  3576. lcd_setstatus(src);
  3577. } else {
  3578. // farmers want to abuse a bug from the previous firmware releases
  3579. // - they need to see the filename on the status screen instead of "Wait for user..."
  3580. // So we won't update the message in farm mode...
  3581. if( ! farm_mode){
  3582. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3583. } else {
  3584. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3585. }
  3586. }
  3587. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3588. st_synchronize();
  3589. previous_millis_cmd.start();
  3590. if (codenum > 0 ) {
  3591. codenum += _millis(); // keep track of when we started waiting
  3592. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3593. while(_millis() < codenum && !lcd_clicked()) {
  3594. manage_heater();
  3595. manage_inactivity(true);
  3596. lcd_update(0);
  3597. }
  3598. KEEPALIVE_STATE(IN_HANDLER);
  3599. lcd_ignore_click(false);
  3600. } else {
  3601. marlin_wait_for_click();
  3602. }
  3603. if (IS_SD_PRINTING)
  3604. custom_message_type = CustomMsg::Status;
  3605. else
  3606. LCD_MESSAGERPGM(MSG_WELCOME);
  3607. }
  3608. #ifdef TMC2130
  3609. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3610. {
  3611. // ### CRASH_DETECTED - TMC2130
  3612. // ---------------------------------
  3613. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3614. {
  3615. uint8_t mask = 0;
  3616. if (code_seen('X')) mask |= X_AXIS_MASK;
  3617. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3618. crashdet_detected(mask);
  3619. }
  3620. // ### CRASH_RECOVER - TMC2130
  3621. // ----------------------------------
  3622. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3623. crashdet_recover();
  3624. // ### CRASH_CANCEL - TMC2130
  3625. // ----------------------------------
  3626. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3627. crashdet_cancel();
  3628. }
  3629. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3630. {
  3631. // ### TMC_SET_WAVE_
  3632. // --------------------
  3633. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3634. {
  3635. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3636. axis = (axis == 'E')?3:(axis - 'X');
  3637. if (axis < 4)
  3638. {
  3639. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3640. tmc2130_set_wave(axis, 247, fac);
  3641. }
  3642. }
  3643. // ### TMC_SET_STEP_
  3644. // ------------------
  3645. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3646. {
  3647. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3648. axis = (axis == 'E')?3:(axis - 'X');
  3649. if (axis < 4)
  3650. {
  3651. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3652. uint16_t res = tmc2130_get_res(axis);
  3653. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3654. }
  3655. }
  3656. // ### TMC_SET_CHOP_
  3657. // -------------------
  3658. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3659. {
  3660. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3661. axis = (axis == 'E')?3:(axis - 'X');
  3662. if (axis < 4)
  3663. {
  3664. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3665. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3666. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3667. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3668. char* str_end = 0;
  3669. if (CMDBUFFER_CURRENT_STRING[14])
  3670. {
  3671. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3672. if (str_end && *str_end)
  3673. {
  3674. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3675. if (str_end && *str_end)
  3676. {
  3677. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3678. if (str_end && *str_end)
  3679. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3680. }
  3681. }
  3682. }
  3683. tmc2130_chopper_config[axis].toff = chop0;
  3684. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3685. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3686. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3687. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3688. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3689. }
  3690. }
  3691. }
  3692. #ifdef BACKLASH_X
  3693. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3694. {
  3695. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3696. st_backlash_x = bl;
  3697. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3698. }
  3699. #endif //BACKLASH_X
  3700. #ifdef BACKLASH_Y
  3701. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3702. {
  3703. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3704. st_backlash_y = bl;
  3705. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3706. }
  3707. #endif //BACKLASH_Y
  3708. #endif //TMC2130
  3709. else if(code_seen_P(PSTR("PRUSA"))){
  3710. /*!
  3711. ---------------------------------------------------------------------------------
  3712. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3713. Set of internal PRUSA commands
  3714. #### Usage
  3715. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3716. #### Parameters
  3717. - `PRN` - Prints revision of the printer
  3718. - `FAN` - Prints fan details
  3719. - `thx`
  3720. - `uvlo`
  3721. - `MMURES` - Reset MMU
  3722. - `RESET` - (Careful!)
  3723. - `fv` - ?
  3724. - `M28`
  3725. - `SN`
  3726. - `Fir` - Prints firmware version
  3727. - `Rev`- Prints filament size, elelectronics, nozzle type
  3728. - `Lang` - Reset the language
  3729. - `Lz`
  3730. - `FR` - Full factory reset
  3731. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3732. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3733. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3734. */
  3735. if (farm_prusa_code_seen()) {}
  3736. else if(code_seen_P(PSTR("FANPINTST"))) {
  3737. gcode_PRUSA_BadRAMBoFanTest();
  3738. }
  3739. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3740. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3741. }
  3742. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3743. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3744. enquecommand_P(PSTR("M24"));
  3745. }
  3746. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3747. {
  3748. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  3749. }
  3750. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3751. #ifdef WATCHDOG
  3752. #if defined(XFLASH) && defined(BOOTAPP)
  3753. boot_app_magic = BOOT_APP_MAGIC;
  3754. boot_app_flags = BOOT_APP_FLG_RUN;
  3755. #endif //defined(XFLASH) && defined(BOOTAPP)
  3756. softReset();
  3757. #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.
  3758. asm volatile("jmp 0x3E000");
  3759. #endif
  3760. }
  3761. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3762. char SN[20];
  3763. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3764. if (SN[19])
  3765. puts_P(PSTR("SN invalid"));
  3766. else
  3767. puts(SN);
  3768. }
  3769. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3770. SERIAL_PROTOCOLLNPGM(FW_VERSION_FULL);
  3771. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3772. SERIAL_PROTOCOLLNPGM(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3773. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3774. lang_reset();
  3775. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3776. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3777. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3778. // Factory full reset
  3779. factory_reset(0);
  3780. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3781. // Change the MBL status without changing the logical Z position.
  3782. if(code_seen('V')) {
  3783. bool value = code_value_short();
  3784. st_synchronize();
  3785. if(value != mbl.active) {
  3786. mbl.active = value;
  3787. // Use plan_set_z_position to reset the physical values
  3788. plan_set_z_position(current_position[Z_AXIS]);
  3789. }
  3790. }
  3791. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3792. uint16_t nDiameter;
  3793. if(code_seen('D'))
  3794. {
  3795. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3796. nozzle_diameter_check(nDiameter);
  3797. }
  3798. else if(code_seen_P(PSTR("set")) && farm_mode)
  3799. {
  3800. strchr_pointer++; // skip 1st char (~ 's')
  3801. strchr_pointer++; // skip 2nd char (~ 'e')
  3802. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3803. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3804. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3805. }
  3806. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3807. }
  3808. }
  3809. else if(code_seen('G'))
  3810. {
  3811. gcode_in_progress = code_value_short();
  3812. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3813. switch (gcode_in_progress)
  3814. {
  3815. /*!
  3816. ---------------------------------------------------------------------------------
  3817. # G Codes
  3818. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3819. In Prusa Firmware G0 and G1 are the same.
  3820. #### Usage
  3821. G0 [ X | Y | Z | E | F | S ]
  3822. G1 [ X | Y | Z | E | F | S ]
  3823. #### Parameters
  3824. - `X` - The position to move to on the X axis
  3825. - `Y` - The position to move to on the Y axis
  3826. - `Z` - The position to move to on the Z axis
  3827. - `E` - The amount to extrude between the starting point and ending point
  3828. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3829. */
  3830. case 0: // G0 -> G1
  3831. case 1: // G1
  3832. {
  3833. uint16_t start_segment_idx = restore_interrupted_gcode();
  3834. get_coordinates(); // For X Y Z E F
  3835. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3836. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3837. }
  3838. #ifdef FWRETRACT
  3839. if(cs.autoretract_enabled) {
  3840. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3841. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3842. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3843. st_synchronize();
  3844. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3845. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3846. retract(!retracted[active_extruder]);
  3847. return;
  3848. }
  3849. }
  3850. }
  3851. #endif //FWRETRACT
  3852. prepare_move(start_segment_idx);
  3853. //ClearToSend();
  3854. }
  3855. break;
  3856. /*!
  3857. ### 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>
  3858. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3859. #### Usage
  3860. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3861. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3862. #### Parameters
  3863. - `X` - The position to move to on the X axis
  3864. - `Y` - The position to move to on the Y axis
  3865. - 'Z' - The position to move to on the Z axis
  3866. - `I` - The point in X space from the current X position to maintain a constant distance from
  3867. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3868. - `E` - The amount to extrude between the starting point and ending point
  3869. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3870. */
  3871. case 2:
  3872. case 3:
  3873. {
  3874. uint16_t start_segment_idx = restore_interrupted_gcode();
  3875. #ifdef SF_ARC_FIX
  3876. bool relative_mode_backup = relative_mode;
  3877. relative_mode = true;
  3878. #endif
  3879. get_coordinates(); // For X Y Z E F
  3880. #ifdef SF_ARC_FIX
  3881. relative_mode=relative_mode_backup;
  3882. #endif
  3883. offset[0] = code_seen('I') ? code_value() : 0.f;
  3884. offset[1] = code_seen('J') ? code_value() : 0.f;
  3885. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3886. } break;
  3887. /*!
  3888. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3889. Pause the machine for a period of time.
  3890. #### Usage
  3891. G4 [ P | S ]
  3892. #### Parameters
  3893. - `P` - Time to wait, in milliseconds
  3894. - `S` - Time to wait, in seconds
  3895. */
  3896. case 4:
  3897. codenum = 0;
  3898. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3899. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3900. if(codenum != 0)
  3901. {
  3902. if(custom_message_type != CustomMsg::M117)
  3903. {
  3904. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3905. }
  3906. }
  3907. st_synchronize();
  3908. codenum += _millis(); // keep track of when we started waiting
  3909. previous_millis_cmd.start();
  3910. while(_millis() < codenum) {
  3911. manage_heater();
  3912. manage_inactivity();
  3913. lcd_update(0);
  3914. }
  3915. break;
  3916. #ifdef FWRETRACT
  3917. /*!
  3918. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3919. Retracts filament according to settings of `M207`
  3920. */
  3921. case 10:
  3922. #if EXTRUDERS > 1
  3923. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3924. retract(true,retracted_swap[active_extruder]);
  3925. #else
  3926. retract(true);
  3927. #endif
  3928. break;
  3929. /*!
  3930. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3931. Unretracts/recovers filament according to settings of `M208`
  3932. */
  3933. case 11:
  3934. #if EXTRUDERS > 1
  3935. retract(false,retracted_swap[active_extruder]);
  3936. #else
  3937. retract(false);
  3938. #endif
  3939. break;
  3940. #endif //FWRETRACT
  3941. /*!
  3942. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  3943. Units are in millimeters. Prusa doesn't support inches.
  3944. */
  3945. case 21:
  3946. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  3947. /*!
  3948. ### 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>
  3949. 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).
  3950. #### Usage
  3951. G28 [ X | Y | Z | W | C ]
  3952. #### Parameters
  3953. - `X` - Flag to go back to the X axis origin
  3954. - `Y` - Flag to go back to the Y axis origin
  3955. - `Z` - Flag to go back to the Z axis origin
  3956. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  3957. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  3958. */
  3959. case 28:
  3960. {
  3961. long home_x_value = 0;
  3962. long home_y_value = 0;
  3963. long home_z_value = 0;
  3964. // Which axes should be homed?
  3965. bool home_x = code_seen(axis_codes[X_AXIS]);
  3966. if (home_x) home_x_value = code_value_long();
  3967. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3968. if (home_y) home_y_value = code_value_long();
  3969. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3970. if (home_z) home_z_value = code_value_long();
  3971. bool without_mbl = code_seen('W');
  3972. // calibrate?
  3973. #ifdef TMC2130
  3974. bool calib = code_seen('C');
  3975. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  3976. #else
  3977. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  3978. #endif //TMC2130
  3979. if ((home_x || home_y || without_mbl || home_z) == false) {
  3980. gcode_G80();
  3981. }
  3982. break;
  3983. }
  3984. #ifdef ENABLE_AUTO_BED_LEVELING
  3985. /*!
  3986. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  3987. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3988. See `G81`
  3989. */
  3990. case 29:
  3991. {
  3992. #if Z_MIN_PIN == -1
  3993. #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."
  3994. #endif
  3995. // Prevent user from running a G29 without first homing in X and Y
  3996. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  3997. {
  3998. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  3999. SERIAL_ECHO_START;
  4000. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4001. break; // abort G29, since we don't know where we are
  4002. }
  4003. st_synchronize();
  4004. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4005. //vector_3 corrected_position = plan_get_position_mm();
  4006. //corrected_position.debug("position before G29");
  4007. plan_bed_level_matrix.set_to_identity();
  4008. vector_3 uncorrected_position = plan_get_position();
  4009. //uncorrected_position.debug("position durring G29");
  4010. current_position[X_AXIS] = uncorrected_position.x;
  4011. current_position[Y_AXIS] = uncorrected_position.y;
  4012. current_position[Z_AXIS] = uncorrected_position.z;
  4013. plan_set_position_curposXYZE();
  4014. int l_feedmultiply = setup_for_endstop_move();
  4015. feedrate = homing_feedrate[Z_AXIS];
  4016. #ifdef AUTO_BED_LEVELING_GRID
  4017. // probe at the points of a lattice grid
  4018. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4019. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4020. // solve the plane equation ax + by + d = z
  4021. // A is the matrix with rows [x y 1] for all the probed points
  4022. // B is the vector of the Z positions
  4023. // 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
  4024. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4025. // "A" matrix of the linear system of equations
  4026. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4027. // "B" vector of Z points
  4028. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4029. int probePointCounter = 0;
  4030. bool zig = true;
  4031. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4032. {
  4033. int xProbe, xInc;
  4034. if (zig)
  4035. {
  4036. xProbe = LEFT_PROBE_BED_POSITION;
  4037. //xEnd = RIGHT_PROBE_BED_POSITION;
  4038. xInc = xGridSpacing;
  4039. zig = false;
  4040. } else // zag
  4041. {
  4042. xProbe = RIGHT_PROBE_BED_POSITION;
  4043. //xEnd = LEFT_PROBE_BED_POSITION;
  4044. xInc = -xGridSpacing;
  4045. zig = true;
  4046. }
  4047. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4048. {
  4049. float z_before;
  4050. if (probePointCounter == 0)
  4051. {
  4052. // raise before probing
  4053. z_before = Z_RAISE_BEFORE_PROBING;
  4054. } else
  4055. {
  4056. // raise extruder
  4057. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4058. }
  4059. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4060. eqnBVector[probePointCounter] = measured_z;
  4061. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4062. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4063. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4064. probePointCounter++;
  4065. xProbe += xInc;
  4066. }
  4067. }
  4068. clean_up_after_endstop_move(l_feedmultiply);
  4069. // solve lsq problem
  4070. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4071. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4072. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4073. SERIAL_PROTOCOLPGM(" b: ");
  4074. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4075. SERIAL_PROTOCOLPGM(" d: ");
  4076. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4077. set_bed_level_equation_lsq(plane_equation_coefficients);
  4078. free(plane_equation_coefficients);
  4079. #else // AUTO_BED_LEVELING_GRID not defined
  4080. // Probe at 3 arbitrary points
  4081. // probe 1
  4082. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4083. // probe 2
  4084. 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);
  4085. // probe 3
  4086. 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);
  4087. clean_up_after_endstop_move(l_feedmultiply);
  4088. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4089. #endif // AUTO_BED_LEVELING_GRID
  4090. st_synchronize();
  4091. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4092. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4093. // When the bed is uneven, this height must be corrected.
  4094. 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)
  4095. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4096. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4097. z_tmp = current_position[Z_AXIS];
  4098. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4099. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4100. plan_set_position_curposXYZE();
  4101. }
  4102. break;
  4103. #ifndef Z_PROBE_SLED
  4104. /*!
  4105. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4106. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4107. */
  4108. case 30:
  4109. {
  4110. st_synchronize();
  4111. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4112. int l_feedmultiply = setup_for_endstop_move();
  4113. feedrate = homing_feedrate[Z_AXIS];
  4114. run_z_probe();
  4115. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4116. SERIAL_PROTOCOLPGM(" X: ");
  4117. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4118. SERIAL_PROTOCOLPGM(" Y: ");
  4119. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4120. SERIAL_PROTOCOLPGM(" Z: ");
  4121. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4122. SERIAL_PROTOCOLPGM("\n");
  4123. clean_up_after_endstop_move(l_feedmultiply);
  4124. }
  4125. break;
  4126. #else
  4127. /*!
  4128. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4129. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4130. */
  4131. case 31:
  4132. dock_sled(true);
  4133. break;
  4134. /*!
  4135. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4136. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4137. */
  4138. case 32:
  4139. dock_sled(false);
  4140. break;
  4141. #endif // Z_PROBE_SLED
  4142. #endif // ENABLE_AUTO_BED_LEVELING
  4143. #ifdef MESH_BED_LEVELING
  4144. /*!
  4145. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4146. Sensor must be over the bed.
  4147. The maximum travel distance before an error is triggered is 10mm.
  4148. */
  4149. case 30:
  4150. {
  4151. st_synchronize();
  4152. homing_flag = true;
  4153. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4154. int l_feedmultiply = setup_for_endstop_move();
  4155. feedrate = homing_feedrate[Z_AXIS];
  4156. find_bed_induction_sensor_point_z(-10.f, 3);
  4157. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4158. clean_up_after_endstop_move(l_feedmultiply);
  4159. homing_flag = false;
  4160. }
  4161. break;
  4162. /*!
  4163. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4164. Show/print PINDA temperature interpolating.
  4165. */
  4166. case 75:
  4167. {
  4168. for (uint8_t i = 40; i <= 110; i++)
  4169. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4170. }
  4171. break;
  4172. /*!
  4173. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4174. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4175. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4176. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4177. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4178. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4179. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4180. #### Example
  4181. ```
  4182. G76
  4183. echo PINDA probe calibration start
  4184. echo start temperature: 35.0°
  4185. echo ...
  4186. echo PINDA temperature -- Z shift (mm): 0.---
  4187. ```
  4188. */
  4189. case 76:
  4190. {
  4191. #ifdef PINDA_THERMISTOR
  4192. if (!has_temperature_compensation())
  4193. {
  4194. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4195. break;
  4196. }
  4197. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4198. //we need to know accurate position of first calibration point
  4199. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4200. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4201. break;
  4202. }
  4203. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4204. {
  4205. // We don't know where we are! HOME!
  4206. // Push the commands to the front of the message queue in the reverse order!
  4207. // There shall be always enough space reserved for these commands.
  4208. repeatcommand_front(); // repeat G76 with all its parameters
  4209. enquecommand_front_P(G28W0);
  4210. break;
  4211. }
  4212. 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
  4213. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  4214. if (result == LCD_LEFT_BUTTON_CHOICE)
  4215. {
  4216. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4217. plan_buffer_line_curposXYZE(3000 / 60);
  4218. current_position[Z_AXIS] = 50;
  4219. current_position[Y_AXIS] = 180;
  4220. plan_buffer_line_curposXYZE(3000 / 60);
  4221. st_synchronize();
  4222. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4223. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4224. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4225. plan_buffer_line_curposXYZE(3000 / 60);
  4226. st_synchronize();
  4227. gcode_G28(false, false, true);
  4228. }
  4229. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4230. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4231. current_position[Z_AXIS] = 100;
  4232. plan_buffer_line_curposXYZE(3000 / 60);
  4233. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4234. lcd_temp_cal_show_result(false);
  4235. break;
  4236. }
  4237. }
  4238. st_synchronize();
  4239. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4240. lcd_update_enable(true);
  4241. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4242. float zero_z;
  4243. int z_shift = 0; //unit: steps
  4244. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4245. if (start_temp < 35) start_temp = 35;
  4246. if (start_temp < current_temperature_pinda) start_temp += 5;
  4247. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4248. // setTargetHotend(200, 0);
  4249. setTargetBed(70 + (start_temp - 30));
  4250. custom_message_type = CustomMsg::TempCal;
  4251. custom_message_state = 1;
  4252. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4253. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4254. plan_buffer_line_curposXYZE(3000 / 60);
  4255. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4256. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4257. plan_buffer_line_curposXYZE(3000 / 60);
  4258. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4259. plan_buffer_line_curposXYZE(3000 / 60);
  4260. st_synchronize();
  4261. while (current_temperature_pinda < start_temp)
  4262. {
  4263. delay_keep_alive(1000);
  4264. serialecho_temperatures();
  4265. }
  4266. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4267. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4268. plan_buffer_line_curposXYZE(3000 / 60);
  4269. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4270. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4271. plan_buffer_line_curposXYZE(3000 / 60);
  4272. st_synchronize();
  4273. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4274. if (find_z_result == false) {
  4275. lcd_temp_cal_show_result(find_z_result);
  4276. homing_flag = false;
  4277. break;
  4278. }
  4279. zero_z = current_position[Z_AXIS];
  4280. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4281. int i = -1; for (; i < 5; i++)
  4282. {
  4283. float temp = (40 + i * 5);
  4284. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4285. if (i >= 0) {
  4286. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4287. }
  4288. if (start_temp <= temp) break;
  4289. }
  4290. for (i++; i < 5; i++)
  4291. {
  4292. float temp = (40 + i * 5);
  4293. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4294. custom_message_state = i + 2;
  4295. setTargetBed(50 + 10 * (temp - 30) / 5);
  4296. // setTargetHotend(255, 0);
  4297. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4298. plan_buffer_line_curposXYZE(3000 / 60);
  4299. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4300. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4301. plan_buffer_line_curposXYZE(3000 / 60);
  4302. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4303. plan_buffer_line_curposXYZE(3000 / 60);
  4304. st_synchronize();
  4305. while (current_temperature_pinda < temp)
  4306. {
  4307. delay_keep_alive(1000);
  4308. serialecho_temperatures();
  4309. }
  4310. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4311. plan_buffer_line_curposXYZE(3000 / 60);
  4312. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4313. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4314. plan_buffer_line_curposXYZE(3000 / 60);
  4315. st_synchronize();
  4316. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4317. if (find_z_result == false) {
  4318. lcd_temp_cal_show_result(find_z_result);
  4319. break;
  4320. }
  4321. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4322. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4323. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4324. }
  4325. lcd_temp_cal_show_result(true);
  4326. homing_flag = false;
  4327. #else //PINDA_THERMISTOR
  4328. setTargetBed(PINDA_MIN_T);
  4329. float zero_z;
  4330. int z_shift = 0; //unit: steps
  4331. int t_c; // temperature
  4332. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4333. // We don't know where we are! HOME!
  4334. // Push the commands to the front of the message queue in the reverse order!
  4335. // There shall be always enough space reserved for these commands.
  4336. repeatcommand_front(); // repeat G76 with all its parameters
  4337. enquecommand_front_P(G28W0);
  4338. break;
  4339. }
  4340. puts_P(_N("PINDA probe calibration start"));
  4341. custom_message_type = CustomMsg::TempCal;
  4342. custom_message_state = 1;
  4343. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4344. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4345. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4346. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4347. plan_buffer_line_curposXYZE(3000 / 60);
  4348. st_synchronize();
  4349. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4350. delay_keep_alive(1000);
  4351. serialecho_temperatures();
  4352. }
  4353. //enquecommand_P(PSTR("M190 S50"));
  4354. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4355. delay_keep_alive(1000);
  4356. serialecho_temperatures();
  4357. }
  4358. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4359. current_position[Z_AXIS] = 5;
  4360. plan_buffer_line_curposXYZE(3000 / 60);
  4361. current_position[X_AXIS] = BED_X0;
  4362. current_position[Y_AXIS] = BED_Y0;
  4363. plan_buffer_line_curposXYZE(3000 / 60);
  4364. st_synchronize();
  4365. find_bed_induction_sensor_point_z(-1.f);
  4366. zero_z = current_position[Z_AXIS];
  4367. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4368. for (int i = 0; i<5; i++) {
  4369. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4370. custom_message_state = i + 2;
  4371. t_c = 60 + i * 10;
  4372. setTargetBed(t_c);
  4373. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4374. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4375. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4376. plan_buffer_line_curposXYZE(3000 / 60);
  4377. st_synchronize();
  4378. while (degBed() < t_c) {
  4379. delay_keep_alive(1000);
  4380. serialecho_temperatures();
  4381. }
  4382. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4383. delay_keep_alive(1000);
  4384. serialecho_temperatures();
  4385. }
  4386. current_position[Z_AXIS] = 5;
  4387. plan_buffer_line_curposXYZE(3000 / 60);
  4388. current_position[X_AXIS] = BED_X0;
  4389. current_position[Y_AXIS] = BED_Y0;
  4390. plan_buffer_line_curposXYZE(3000 / 60);
  4391. st_synchronize();
  4392. find_bed_induction_sensor_point_z(-1.f);
  4393. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4394. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4395. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4396. }
  4397. custom_message_type = CustomMsg::Status;
  4398. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4399. puts_P(_N("Temperature calibration done."));
  4400. disable_x();
  4401. disable_y();
  4402. disable_z();
  4403. disable_e0();
  4404. disable_e1();
  4405. disable_e2();
  4406. setTargetBed(0); //set bed target temperature back to 0
  4407. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4408. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4409. lcd_update_enable(true);
  4410. lcd_update(2);
  4411. #endif //PINDA_THERMISTOR
  4412. }
  4413. break;
  4414. /*!
  4415. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4416. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4417. #### Usage
  4418. G80 [ N | R | V | L | R | F | B ]
  4419. #### Parameters
  4420. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4421. - `R` - Probe retries. Default 3 max. 10
  4422. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4423. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4424. #### Additional Parameters
  4425. - `L` - Left Bed Level correct value in um.
  4426. - `R` - Right Bed Level correct value in um.
  4427. - `F` - Front Bed Level correct value in um.
  4428. - `B` - Back Bed Level correct value in um.
  4429. */
  4430. /*
  4431. * Probes a grid and produces a mesh to compensate for variable bed height
  4432. * The S0 report the points as below
  4433. * +----> X-axis
  4434. * |
  4435. * |
  4436. * v Y-axis
  4437. */
  4438. case 80: {
  4439. gcode_G80();
  4440. }
  4441. break;
  4442. /*!
  4443. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4444. Prints mesh bed leveling status and bed profile if activated.
  4445. */
  4446. case 81:
  4447. if (mbl.active) {
  4448. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4449. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4450. SERIAL_PROTOCOL(',');
  4451. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4452. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4453. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4454. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4455. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4456. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4457. SERIAL_PROTOCOLPGM(" ");
  4458. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4459. }
  4460. SERIAL_PROTOCOLLN();
  4461. }
  4462. }
  4463. else
  4464. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4465. break;
  4466. #if 0
  4467. /*!
  4468. ### 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>
  4469. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4470. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4471. */
  4472. case 82:
  4473. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4474. int l_feedmultiply = setup_for_endstop_move();
  4475. find_bed_induction_sensor_point_z();
  4476. clean_up_after_endstop_move(l_feedmultiply);
  4477. SERIAL_PROTOCOLPGM("Bed found at: ");
  4478. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4479. SERIAL_PROTOCOLPGM("\n");
  4480. break;
  4481. /*!
  4482. ### 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>
  4483. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4484. */
  4485. case 83:
  4486. {
  4487. int babystepz = code_seen('S') ? code_value() : 0;
  4488. int BabyPosition = code_seen('P') ? code_value() : 0;
  4489. if (babystepz != 0) {
  4490. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4491. // Is the axis indexed starting with zero or one?
  4492. if (BabyPosition > 4) {
  4493. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4494. }else{
  4495. // Save it to the eeprom
  4496. babystepLoadZ = babystepz;
  4497. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4498. // adjust the Z
  4499. babystepsTodoZadd(babystepLoadZ);
  4500. }
  4501. }
  4502. }
  4503. break;
  4504. /*!
  4505. ### 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>
  4506. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4507. */
  4508. case 84:
  4509. babystepsTodoZsubtract(babystepLoadZ);
  4510. // babystepLoadZ = 0;
  4511. break;
  4512. /*!
  4513. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4514. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4515. */
  4516. case 85:
  4517. lcd_pick_babystep();
  4518. break;
  4519. #endif
  4520. /*!
  4521. ### 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>
  4522. This G-code will be performed at the start of a calibration script.
  4523. (Prusa3D specific)
  4524. */
  4525. case 86:
  4526. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4527. break;
  4528. /*!
  4529. ### 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>
  4530. This G-code will be performed at the end of a calibration script.
  4531. (Prusa3D specific)
  4532. */
  4533. case 87:
  4534. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4535. break;
  4536. /*!
  4537. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4538. Currently has no effect.
  4539. */
  4540. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4541. case 88:
  4542. break;
  4543. #endif // ENABLE_MESH_BED_LEVELING
  4544. /*!
  4545. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4546. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4547. */
  4548. case 90: {
  4549. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4550. }
  4551. break;
  4552. /*!
  4553. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4554. All coordinates from now on are relative to the last position. E axis is left intact.
  4555. */
  4556. case 91: {
  4557. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4558. }
  4559. break;
  4560. /*!
  4561. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4562. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4563. If a parameter is omitted, that axis will not be affected.
  4564. 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`).
  4565. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4566. #### Usage
  4567. G92 [ X | Y | Z | E ]
  4568. #### Parameters
  4569. - `X` - new X axis position
  4570. - `Y` - new Y axis position
  4571. - `Z` - new Z axis position
  4572. - `E` - new extruder position
  4573. */
  4574. case 92: {
  4575. gcode_G92();
  4576. }
  4577. break;
  4578. #ifdef PRUSA_FARM
  4579. /*!
  4580. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4581. Enable Prusa-specific Farm functions and g-code.
  4582. See Internal Prusa commands.
  4583. */
  4584. case 98:
  4585. farm_gcode_g98();
  4586. break;
  4587. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4588. Disables Prusa-specific Farm functions and g-code.
  4589. */
  4590. case 99:
  4591. farm_gcode_g99();
  4592. break;
  4593. #endif //PRUSA_FARM
  4594. default:
  4595. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4596. }
  4597. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4598. gcode_in_progress = 0;
  4599. } // end if(code_seen('G'))
  4600. /*!
  4601. ### End of G-Codes
  4602. */
  4603. /*!
  4604. ---------------------------------------------------------------------------------
  4605. # M Commands
  4606. */
  4607. else if(code_seen('M'))
  4608. {
  4609. int index;
  4610. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4611. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4612. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4613. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4614. } else
  4615. {
  4616. mcode_in_progress = code_value_short();
  4617. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4618. switch(mcode_in_progress)
  4619. {
  4620. /*!
  4621. ### 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>
  4622. */
  4623. case 17:
  4624. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4625. enable_x();
  4626. enable_y();
  4627. enable_z();
  4628. enable_e0();
  4629. enable_e1();
  4630. enable_e2();
  4631. break;
  4632. #ifdef SDSUPPORT
  4633. /*!
  4634. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4635. #### Usage
  4636. M20 [ L | T ]
  4637. #### Parameters
  4638. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4639. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4640. */
  4641. case 20:
  4642. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4643. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4644. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4645. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4646. break;
  4647. /*!
  4648. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4649. */
  4650. case 21:
  4651. card.initsd();
  4652. break;
  4653. /*!
  4654. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4655. */
  4656. case 22:
  4657. card.release();
  4658. break;
  4659. /*!
  4660. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4661. #### Usage
  4662. M23 [filename]
  4663. */
  4664. case 23:
  4665. starpos = (strchr(strchr_pointer + 4,'*'));
  4666. if(starpos!=NULL)
  4667. *(starpos)='\0';
  4668. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4669. break;
  4670. /*!
  4671. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4672. */
  4673. case 24:
  4674. if (isPrintPaused)
  4675. lcd_resume_print();
  4676. else
  4677. {
  4678. if (!card.get_sdpos())
  4679. {
  4680. // A new print has started from scratch, reset stats
  4681. failstats_reset_print();
  4682. sdpos_atomic = 0;
  4683. #ifndef LA_NOCOMPAT
  4684. la10c_reset();
  4685. #endif
  4686. }
  4687. card.startFileprint();
  4688. starttime=_millis();
  4689. if (MMU2::mmu2.Enabled())
  4690. {
  4691. if (MMU2::mmu2.FindaDetectsFilament() && !fsensor.getFilamentPresent())
  4692. { // Filament only half way into the PTFE. Unload the filament.
  4693. MMU2::mmu2.unload();
  4694. // Tx and Tc gcodes take care of loading the filament to the nozzle.
  4695. }
  4696. }
  4697. }
  4698. break;
  4699. /*!
  4700. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4701. Set position in SD card file to index in bytes.
  4702. This command is expected to be called after M23 and before M24.
  4703. Otherwise effect of this command is undefined.
  4704. #### Usage
  4705. M26 [ S ]
  4706. #### Parameters
  4707. - `S` - Index in bytes
  4708. */
  4709. case 26:
  4710. if(card.cardOK && code_seen('S')) {
  4711. long index = code_value_long();
  4712. card.setIndex(index);
  4713. // We don't disable interrupt during update of sdpos_atomic
  4714. // as we expect, that SD card print is not active in this moment
  4715. sdpos_atomic = index;
  4716. }
  4717. break;
  4718. /*!
  4719. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4720. #### Usage
  4721. M27 [ P ]
  4722. #### Parameters
  4723. - `P` - Show full SFN path instead of LFN only.
  4724. */
  4725. case 27:
  4726. card.getStatus(code_seen('P'));
  4727. break;
  4728. /*!
  4729. ### 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>
  4730. */
  4731. case 28:
  4732. starpos = (strchr(strchr_pointer + 4,'*'));
  4733. if(starpos != NULL){
  4734. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4735. strchr_pointer = strchr(npos,' ') + 1;
  4736. *(starpos) = '\0';
  4737. }
  4738. card.openFileWrite(strchr_pointer+4);
  4739. break;
  4740. /*! ### 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>
  4741. 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.
  4742. */
  4743. case 29:
  4744. //processed in write to file routine above
  4745. //card,saving = false;
  4746. break;
  4747. /*!
  4748. ### 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>
  4749. #### Usage
  4750. M30 [filename]
  4751. */
  4752. case 30:
  4753. if (card.cardOK){
  4754. card.closefile();
  4755. starpos = (strchr(strchr_pointer + 4,'*'));
  4756. if(starpos != NULL){
  4757. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4758. strchr_pointer = strchr(npos,' ') + 1;
  4759. *(starpos) = '\0';
  4760. }
  4761. card.removeFile(strchr_pointer + 4);
  4762. }
  4763. break;
  4764. /*!
  4765. ### 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>
  4766. @todo What are the parameters P and S for in M32?
  4767. */
  4768. case 32:
  4769. {
  4770. if(card.sdprinting) {
  4771. st_synchronize();
  4772. }
  4773. starpos = (strchr(strchr_pointer + 4,'*'));
  4774. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4775. if(namestartpos==NULL)
  4776. {
  4777. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4778. }
  4779. else
  4780. namestartpos++; //to skip the '!'
  4781. if(starpos!=NULL)
  4782. *(starpos)='\0';
  4783. bool call_procedure=(code_seen('P'));
  4784. if(strchr_pointer>namestartpos)
  4785. call_procedure=false; //false alert, 'P' found within filename
  4786. if( card.cardOK )
  4787. {
  4788. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4789. if(code_seen('S'))
  4790. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4791. card.setIndex(code_value_long());
  4792. card.startFileprint();
  4793. if(!call_procedure)
  4794. {
  4795. if(!card.get_sdpos())
  4796. {
  4797. // A new print has started from scratch, reset stats
  4798. failstats_reset_print();
  4799. sdpos_atomic = 0;
  4800. #ifndef LA_NOCOMPAT
  4801. la10c_reset();
  4802. #endif
  4803. }
  4804. starttime=_millis(); // procedure calls count as normal print time.
  4805. }
  4806. }
  4807. } break;
  4808. /*!
  4809. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4810. #### Usage
  4811. M928 [filename]
  4812. */
  4813. case 928:
  4814. starpos = (strchr(strchr_pointer + 5,'*'));
  4815. if(starpos != NULL){
  4816. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4817. strchr_pointer = strchr(npos,' ') + 1;
  4818. *(starpos) = '\0';
  4819. }
  4820. card.openLogFile(strchr_pointer+5);
  4821. break;
  4822. #endif //SDSUPPORT
  4823. /*!
  4824. ### 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>
  4825. */
  4826. case 31: //M31 take time since the start of the SD print or an M109 command
  4827. {
  4828. stoptime=_millis();
  4829. char time[30];
  4830. unsigned long t=(stoptime-starttime)/1000;
  4831. int sec,min;
  4832. min=t/60;
  4833. sec=t%60;
  4834. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4835. SERIAL_ECHO_START;
  4836. SERIAL_ECHOLN(time);
  4837. lcd_setstatus(time);
  4838. autotempShutdown();
  4839. }
  4840. break;
  4841. /*!
  4842. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4843. #### Usage
  4844. M42 [ P | S ]
  4845. #### Parameters
  4846. - `P` - Pin number.
  4847. - `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.
  4848. */
  4849. case 42:
  4850. if (code_seen('S'))
  4851. {
  4852. uint8_t pin_status = code_value_uint8();
  4853. int8_t pin_number = LED_PIN;
  4854. if (code_seen('P'))
  4855. pin_number = code_value_uint8();
  4856. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4857. {
  4858. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4859. {
  4860. pin_number = -1;
  4861. break;
  4862. }
  4863. }
  4864. #if defined(FAN_PIN) && FAN_PIN > -1
  4865. if (pin_number == FAN_PIN)
  4866. fanSpeed = pin_status;
  4867. #endif
  4868. if (pin_number > -1)
  4869. {
  4870. pinMode(pin_number, OUTPUT);
  4871. digitalWrite(pin_number, pin_status);
  4872. analogWrite(pin_number, pin_status);
  4873. }
  4874. }
  4875. break;
  4876. /*!
  4877. ### 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>
  4878. */
  4879. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4880. // Reset the baby step value and the baby step applied flag.
  4881. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4882. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4883. // Reset the skew and offset in both RAM and EEPROM.
  4884. reset_bed_offset_and_skew();
  4885. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4886. // the planner will not perform any adjustments in the XY plane.
  4887. // Wait for the motors to stop and update the current position with the absolute values.
  4888. world2machine_revert_to_uncorrected();
  4889. break;
  4890. /*!
  4891. ### 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>
  4892. #### Usage
  4893. M45 [ V ]
  4894. #### Parameters
  4895. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4896. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4897. */
  4898. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4899. {
  4900. int8_t verbosity_level = 0;
  4901. bool only_Z = code_seen('Z');
  4902. #ifdef SUPPORT_VERBOSITY
  4903. if (code_seen('V'))
  4904. {
  4905. // Just 'V' without a number counts as V1.
  4906. char c = strchr_pointer[1];
  4907. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4908. }
  4909. #endif //SUPPORT_VERBOSITY
  4910. gcode_M45(only_Z, verbosity_level);
  4911. }
  4912. break;
  4913. /*!
  4914. ### 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>
  4915. */
  4916. case 46:
  4917. {
  4918. // M46: Prusa3D: Show the assigned IP address.
  4919. if (card.ToshibaFlashAir_isEnabled()) {
  4920. uint8_t ip[4];
  4921. if (card.ToshibaFlashAir_GetIP(ip)) {
  4922. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  4923. SERIAL_PROTOCOL(uint8_t(ip[0]));
  4924. SERIAL_PROTOCOL('.');
  4925. SERIAL_PROTOCOL(uint8_t(ip[1]));
  4926. SERIAL_PROTOCOL('.');
  4927. SERIAL_PROTOCOL(uint8_t(ip[2]));
  4928. SERIAL_PROTOCOL('.');
  4929. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  4930. } else {
  4931. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  4932. }
  4933. } else {
  4934. SERIAL_PROTOCOLLNPGM("n/a");
  4935. }
  4936. break;
  4937. }
  4938. /*!
  4939. ### 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>
  4940. */
  4941. case 47:
  4942. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4943. lcd_diag_show_end_stops();
  4944. KEEPALIVE_STATE(IN_HANDLER);
  4945. break;
  4946. #if 0
  4947. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4948. {
  4949. // Disable the default update procedure of the display. We will do a modal dialog.
  4950. lcd_update_enable(false);
  4951. // Let the planner use the uncorrected coordinates.
  4952. mbl.reset();
  4953. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4954. // the planner will not perform any adjustments in the XY plane.
  4955. // Wait for the motors to stop and update the current position with the absolute values.
  4956. world2machine_revert_to_uncorrected();
  4957. // Move the print head close to the bed.
  4958. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4959. 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);
  4960. st_synchronize();
  4961. // Home in the XY plane.
  4962. set_destination_to_current();
  4963. int l_feedmultiply = setup_for_endstop_move();
  4964. home_xy();
  4965. int8_t verbosity_level = 0;
  4966. if (code_seen('V')) {
  4967. // Just 'V' without a number counts as V1.
  4968. char c = strchr_pointer[1];
  4969. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4970. }
  4971. bool success = scan_bed_induction_points(verbosity_level);
  4972. clean_up_after_endstop_move(l_feedmultiply);
  4973. // Print head up.
  4974. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4975. 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);
  4976. st_synchronize();
  4977. lcd_update_enable(true);
  4978. break;
  4979. }
  4980. #endif
  4981. #ifdef ENABLE_AUTO_BED_LEVELING
  4982. #ifdef Z_PROBE_REPEATABILITY_TEST
  4983. /*!
  4984. ### 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>
  4985. 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.
  4986. 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.
  4987. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  4988. #### Usage
  4989. M48 [ n | X | Y | V | L ]
  4990. #### Parameters
  4991. - `n` - Number of samples. Valid values 4-50
  4992. - `X` - X position for samples
  4993. - `Y` - Y position for samples
  4994. - `V` - Verbose level. Valid values 1-4
  4995. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  4996. */
  4997. case 48: // M48 Z-Probe repeatability
  4998. {
  4999. #if Z_MIN_PIN == -1
  5000. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5001. #endif
  5002. double sum=0.0;
  5003. double mean=0.0;
  5004. double sigma=0.0;
  5005. double sample_set[50];
  5006. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5007. double X_current, Y_current, Z_current;
  5008. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5009. if (code_seen('V') || code_seen('v')) {
  5010. verbose_level = code_value();
  5011. if (verbose_level<0 || verbose_level>4 ) {
  5012. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5013. goto Sigma_Exit;
  5014. }
  5015. }
  5016. if (verbose_level > 0) {
  5017. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5018. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5019. }
  5020. if (code_seen('n')) {
  5021. n_samples = code_value();
  5022. if (n_samples<4 || n_samples>50 ) {
  5023. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5024. goto Sigma_Exit;
  5025. }
  5026. }
  5027. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5028. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5029. Z_current = st_get_position_mm(Z_AXIS);
  5030. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5031. ext_position = st_get_position_mm(E_AXIS);
  5032. if (code_seen('X') || code_seen('x') ) {
  5033. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5034. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5035. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5036. goto Sigma_Exit;
  5037. }
  5038. }
  5039. if (code_seen('Y') || code_seen('y') ) {
  5040. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5041. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5042. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5043. goto Sigma_Exit;
  5044. }
  5045. }
  5046. if (code_seen('L') || code_seen('l') ) {
  5047. n_legs = code_value();
  5048. if ( n_legs==1 )
  5049. n_legs = 2;
  5050. if ( n_legs<0 || n_legs>15 ) {
  5051. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5052. goto Sigma_Exit;
  5053. }
  5054. }
  5055. //
  5056. // Do all the preliminary setup work. First raise the probe.
  5057. //
  5058. st_synchronize();
  5059. plan_bed_level_matrix.set_to_identity();
  5060. plan_buffer_line( X_current, Y_current, Z_start_location,
  5061. ext_position,
  5062. homing_feedrate[Z_AXIS]/60,
  5063. active_extruder);
  5064. st_synchronize();
  5065. //
  5066. // Now get everything to the specified probe point So we can safely do a probe to
  5067. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5068. // use that as a starting point for each probe.
  5069. //
  5070. if (verbose_level > 2)
  5071. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5072. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5073. ext_position,
  5074. homing_feedrate[X_AXIS]/60,
  5075. active_extruder);
  5076. st_synchronize();
  5077. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5078. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5079. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5080. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5081. //
  5082. // OK, do the inital probe to get us close to the bed.
  5083. // Then retrace the right amount and use that in subsequent probes
  5084. //
  5085. int l_feedmultiply = setup_for_endstop_move();
  5086. run_z_probe();
  5087. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5088. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5089. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5090. ext_position,
  5091. homing_feedrate[X_AXIS]/60,
  5092. active_extruder);
  5093. st_synchronize();
  5094. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5095. for( n=0; n<n_samples; n++) {
  5096. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5097. if ( n_legs) {
  5098. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5099. int rotational_direction, l;
  5100. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5101. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5102. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5103. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5104. //SERIAL_ECHOPAIR(" theta: ",theta);
  5105. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5106. //SERIAL_PROTOCOLLNPGM("");
  5107. for( l=0; l<n_legs-1; l++) {
  5108. if (rotational_direction==1)
  5109. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5110. else
  5111. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5112. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5113. if ( radius<0.0 )
  5114. radius = -radius;
  5115. X_current = X_probe_location + cos(theta) * radius;
  5116. Y_current = Y_probe_location + sin(theta) * radius;
  5117. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5118. X_current = X_MIN_POS;
  5119. if ( X_current>X_MAX_POS)
  5120. X_current = X_MAX_POS;
  5121. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5122. Y_current = Y_MIN_POS;
  5123. if ( Y_current>Y_MAX_POS)
  5124. Y_current = Y_MAX_POS;
  5125. if (verbose_level>3 ) {
  5126. SERIAL_ECHOPAIR("x: ", X_current);
  5127. SERIAL_ECHOPAIR("y: ", Y_current);
  5128. SERIAL_PROTOCOLLNPGM("");
  5129. }
  5130. do_blocking_move_to( X_current, Y_current, Z_current );
  5131. }
  5132. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5133. }
  5134. int l_feedmultiply = setup_for_endstop_move();
  5135. run_z_probe();
  5136. sample_set[n] = current_position[Z_AXIS];
  5137. //
  5138. // Get the current mean for the data points we have so far
  5139. //
  5140. sum=0.0;
  5141. for( j=0; j<=n; j++) {
  5142. sum = sum + sample_set[j];
  5143. }
  5144. mean = sum / (double (n+1));
  5145. //
  5146. // Now, use that mean to calculate the standard deviation for the
  5147. // data points we have so far
  5148. //
  5149. sum=0.0;
  5150. for( j=0; j<=n; j++) {
  5151. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5152. }
  5153. sigma = sqrt( sum / (double (n+1)) );
  5154. if (verbose_level > 1) {
  5155. SERIAL_PROTOCOL(n+1);
  5156. SERIAL_PROTOCOL(" of ");
  5157. SERIAL_PROTOCOL(n_samples);
  5158. SERIAL_PROTOCOLPGM(" z: ");
  5159. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5160. }
  5161. if (verbose_level > 2) {
  5162. SERIAL_PROTOCOL(" mean: ");
  5163. SERIAL_PROTOCOL_F(mean,6);
  5164. SERIAL_PROTOCOL(" sigma: ");
  5165. SERIAL_PROTOCOL_F(sigma,6);
  5166. }
  5167. if (verbose_level > 0)
  5168. SERIAL_PROTOCOLPGM("\n");
  5169. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5170. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5171. st_synchronize();
  5172. }
  5173. _delay(1000);
  5174. clean_up_after_endstop_move(l_feedmultiply);
  5175. // enable_endstops(true);
  5176. if (verbose_level > 0) {
  5177. SERIAL_PROTOCOLPGM("Mean: ");
  5178. SERIAL_PROTOCOL_F(mean, 6);
  5179. SERIAL_PROTOCOLPGM("\n");
  5180. }
  5181. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5182. SERIAL_PROTOCOL_F(sigma, 6);
  5183. SERIAL_PROTOCOLPGM("\n\n");
  5184. Sigma_Exit:
  5185. break;
  5186. }
  5187. #endif // Z_PROBE_REPEATABILITY_TEST
  5188. #endif // ENABLE_AUTO_BED_LEVELING
  5189. /*!
  5190. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5191. #### Usage
  5192. M73 [ P | R | Q | S | C | D ]
  5193. #### Parameters
  5194. - `P` - Percent in normal mode
  5195. - `R` - Time remaining in normal mode
  5196. - `Q` - Percent in silent mode
  5197. - `S` - Time in silent mode
  5198. - `C` - Time to change/pause/user interaction in normal mode
  5199. - `D` - Time to change/pause/user interaction in silent mode
  5200. */
  5201. case 73: //M73 show percent done, time remaining and time to change/pause
  5202. {
  5203. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5204. if(code_seen('R')) print_time_remaining_normal = code_value();
  5205. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5206. if(code_seen('S')) print_time_remaining_silent = code_value();
  5207. if(code_seen('C')){
  5208. float print_time_to_change_normal_f = code_value_float();
  5209. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5210. }
  5211. if(code_seen('D')){
  5212. float print_time_to_change_silent_f = code_value_float();
  5213. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5214. }
  5215. {
  5216. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5217. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5218. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5219. }
  5220. break;
  5221. }
  5222. /*!
  5223. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5224. #### Usage
  5225. M104 [ S ]
  5226. #### Parameters
  5227. - `S` - Target temperature
  5228. */
  5229. case 104: // M104
  5230. {
  5231. uint8_t extruder;
  5232. if(setTargetedHotend(104,extruder)){
  5233. break;
  5234. }
  5235. if (code_seen('S'))
  5236. {
  5237. setTargetHotendSafe(code_value(), extruder);
  5238. }
  5239. break;
  5240. }
  5241. /*!
  5242. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5243. It is processed much earlier as to bypass the cmdqueue.
  5244. */
  5245. case 112:
  5246. kill(MSG_M112_KILL, 3);
  5247. break;
  5248. /*!
  5249. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5250. #### Usage
  5251. M140 [ S ]
  5252. #### Parameters
  5253. - `S` - Target temperature
  5254. */
  5255. case 140:
  5256. if (code_seen('S')) setTargetBed(code_value());
  5257. break;
  5258. /*!
  5259. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5260. Prints temperatures:
  5261. - `T:` - Hotend (actual / target)
  5262. - `B:` - Bed (actual / target)
  5263. - `Tx:` - x Tool (actual / target)
  5264. - `@:` - Hotend power
  5265. - `B@:` - Bed power
  5266. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5267. - `A:` - Ambient actual (only MK3/s)
  5268. _Example:_
  5269. 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
  5270. */
  5271. case 105:
  5272. {
  5273. uint8_t extruder;
  5274. if(setTargetedHotend(105, extruder)){
  5275. break;
  5276. }
  5277. SERIAL_PROTOCOLPGM("ok ");
  5278. gcode_M105(extruder);
  5279. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5280. cmdbuffer_front_already_processed = true;
  5281. break;
  5282. }
  5283. #if defined(AUTO_REPORT)
  5284. /*!
  5285. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5286. #### Usage
  5287. M155 [ S ] [ C ]
  5288. #### Parameters
  5289. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5290. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5291. bit 0 = Auto-report temperatures
  5292. bit 1 = Auto-report fans
  5293. bit 2 = Auto-report position
  5294. bit 3 = free
  5295. bit 4 = free
  5296. bit 5 = free
  5297. bit 6 = free
  5298. bit 7 = free
  5299. */
  5300. case 155:
  5301. {
  5302. if (code_seen('S')){
  5303. autoReportFeatures.SetPeriod( code_value_uint8() );
  5304. }
  5305. if (code_seen('C')){
  5306. autoReportFeatures.SetMask(code_value_uint8());
  5307. } else{
  5308. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5309. }
  5310. }
  5311. break;
  5312. #endif //AUTO_REPORT
  5313. /*!
  5314. ### 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>
  5315. #### Usage
  5316. M104 [ B | R | S ]
  5317. #### Parameters (not mandatory)
  5318. - `S` - Set extruder temperature
  5319. - `R` - Set extruder temperature
  5320. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5321. Parameters S and R are treated identically.
  5322. Command always waits for both cool down and heat up.
  5323. If no parameters are supplied waits for previously set extruder temperature.
  5324. */
  5325. case 109:
  5326. {
  5327. uint8_t extruder;
  5328. if(setTargetedHotend(109, extruder)){
  5329. break;
  5330. }
  5331. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5332. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5333. prusa_statistics(1);
  5334. #ifdef AUTOTEMP
  5335. autotemp_enabled=false;
  5336. #endif
  5337. if (code_seen('S')) {
  5338. setTargetHotendSafe(code_value(), extruder);
  5339. } else if (code_seen('R')) {
  5340. setTargetHotendSafe(code_value(), extruder);
  5341. }
  5342. #ifdef AUTOTEMP
  5343. if (code_seen('S')) autotemp_min=code_value();
  5344. if (code_seen('B')) autotemp_max=code_value();
  5345. if (code_seen('F'))
  5346. {
  5347. autotemp_factor=code_value();
  5348. autotemp_enabled=true;
  5349. }
  5350. #endif
  5351. codenum = _millis();
  5352. /* See if we are heating up or cooling down */
  5353. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5354. cancel_heatup = false;
  5355. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5356. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5357. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5358. prusa_statistics(2);
  5359. //starttime=_millis();
  5360. previous_millis_cmd.start();
  5361. }
  5362. break;
  5363. /*!
  5364. ### 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>
  5365. #### Usage
  5366. M190 [ R | S ]
  5367. #### Parameters (not mandatory)
  5368. - `S` - Set extruder temperature and wait for heating
  5369. - `R` - Set extruder temperature and wait for heating or cooling
  5370. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5371. */
  5372. case 190:
  5373. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5374. {
  5375. bool CooldownNoWait = false;
  5376. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5377. heating_status = HeatingStatus::BED_HEATING;
  5378. prusa_statistics(1);
  5379. if (code_seen('S'))
  5380. {
  5381. setTargetBed(code_value());
  5382. CooldownNoWait = true;
  5383. }
  5384. else if (code_seen('R'))
  5385. {
  5386. setTargetBed(code_value());
  5387. }
  5388. codenum = _millis();
  5389. cancel_heatup = false;
  5390. target_direction = isHeatingBed(); // true if heating, false if cooling
  5391. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5392. {
  5393. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5394. {
  5395. if (!farm_mode) {
  5396. float tt = degHotend(active_extruder);
  5397. SERIAL_PROTOCOLPGM("T:");
  5398. SERIAL_PROTOCOL(tt);
  5399. SERIAL_PROTOCOLPGM(" E:");
  5400. SERIAL_PROTOCOL((int)active_extruder);
  5401. SERIAL_PROTOCOLPGM(" B:");
  5402. SERIAL_PROTOCOL_F(degBed(), 1);
  5403. SERIAL_PROTOCOLLN();
  5404. }
  5405. codenum = _millis();
  5406. }
  5407. manage_heater();
  5408. manage_inactivity();
  5409. lcd_update(0);
  5410. }
  5411. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5412. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5413. previous_millis_cmd.start();
  5414. }
  5415. #endif
  5416. break;
  5417. #if defined(FAN_PIN) && FAN_PIN > -1
  5418. /*!
  5419. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5420. #### Usage
  5421. M106 [ S ]
  5422. #### Parameters
  5423. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5424. */
  5425. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5426. if (code_seen('S')){
  5427. fanSpeed = code_value_uint8();
  5428. }
  5429. else {
  5430. fanSpeed = 255;
  5431. }
  5432. break;
  5433. /*!
  5434. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5435. */
  5436. case 107:
  5437. fanSpeed = 0;
  5438. break;
  5439. #endif //FAN_PIN
  5440. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5441. /*!
  5442. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5443. Only works if the firmware is compiled with PS_ON_PIN defined.
  5444. */
  5445. case 80:
  5446. SET_OUTPUT(PS_ON_PIN); //GND
  5447. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5448. // If you have a switch on suicide pin, this is useful
  5449. // if you want to start another print with suicide feature after
  5450. // a print without suicide...
  5451. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5452. SET_OUTPUT(SUICIDE_PIN);
  5453. WRITE(SUICIDE_PIN, HIGH);
  5454. #endif
  5455. powersupply = true;
  5456. LCD_MESSAGERPGM(MSG_WELCOME);
  5457. lcd_update(0);
  5458. break;
  5459. /*!
  5460. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5461. Only works if the firmware is compiled with PS_ON_PIN defined.
  5462. */
  5463. case 81:
  5464. disable_heater();
  5465. st_synchronize();
  5466. disable_e0();
  5467. disable_e1();
  5468. disable_e2();
  5469. finishAndDisableSteppers();
  5470. fanSpeed = 0;
  5471. _delay(1000); // Wait a little before to switch off
  5472. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5473. st_synchronize();
  5474. suicide();
  5475. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5476. SET_OUTPUT(PS_ON_PIN);
  5477. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5478. #endif
  5479. powersupply = false;
  5480. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5481. lcd_update(0);
  5482. break;
  5483. #endif
  5484. /*!
  5485. ### 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>
  5486. Makes the extruder interpret extrusion as absolute positions.
  5487. */
  5488. case 82:
  5489. axis_relative_modes &= ~E_AXIS_MASK;
  5490. break;
  5491. /*!
  5492. ### 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>
  5493. Makes the extruder interpret extrusion values as relative positions.
  5494. */
  5495. case 83:
  5496. axis_relative_modes |= E_AXIS_MASK;
  5497. break;
  5498. /*!
  5499. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5500. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5501. This command can be used without any additional parameters. In that case all steppers are disabled.
  5502. 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.
  5503. M84 [ S | X | Y | Z | E ]
  5504. - `S` - Seconds
  5505. - `X` - X axis
  5506. - `Y` - Y axis
  5507. - `Z` - Z axis
  5508. - `E` - Extruder
  5509. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5510. Equal to M84 (compatibility)
  5511. */
  5512. case 18: //compatibility
  5513. case 84: // M84
  5514. if(code_seen('S')){
  5515. stepper_inactive_time = code_value() * 1000;
  5516. }
  5517. else
  5518. {
  5519. 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])));
  5520. if(all_axis)
  5521. {
  5522. st_synchronize();
  5523. disable_e0();
  5524. disable_e1();
  5525. disable_e2();
  5526. finishAndDisableSteppers();
  5527. }
  5528. else
  5529. {
  5530. st_synchronize();
  5531. if (code_seen('X')) disable_x();
  5532. if (code_seen('Y')) disable_y();
  5533. if (code_seen('Z')) disable_z();
  5534. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5535. if (code_seen('E')) {
  5536. disable_e0();
  5537. disable_e1();
  5538. disable_e2();
  5539. }
  5540. #endif
  5541. }
  5542. }
  5543. break;
  5544. /*!
  5545. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5546. #### Usage
  5547. M85 [ S ]
  5548. #### Parameters
  5549. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5550. */
  5551. case 85: // M85
  5552. if(code_seen('S')) {
  5553. max_inactive_time = code_value() * 1000;
  5554. }
  5555. break;
  5556. #ifdef SAFETYTIMER
  5557. /*!
  5558. ### 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>
  5559. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5560. #### Usage
  5561. M86 [ S ]
  5562. #### Parameters
  5563. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5564. */
  5565. case 86:
  5566. if (code_seen('S')) {
  5567. safetytimer_inactive_time = code_value() * 1000;
  5568. safetyTimer.start();
  5569. }
  5570. break;
  5571. #endif
  5572. /*!
  5573. ### 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>
  5574. 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)
  5575. #### Usage
  5576. M92 [ X | Y | Z | E ]
  5577. #### Parameters
  5578. - `X` - Steps per unit for the X drive
  5579. - `Y` - Steps per unit for the Y drive
  5580. - `Z` - Steps per unit for the Z drive
  5581. - `E` - Steps per unit for the extruder drive
  5582. */
  5583. case 92:
  5584. for(int8_t i=0; i < NUM_AXIS; i++)
  5585. {
  5586. if(code_seen(axis_codes[i]))
  5587. {
  5588. if(i == E_AXIS) { // E
  5589. float value = code_value();
  5590. if(value < 20.0) {
  5591. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5592. cs.max_jerk[E_AXIS] *= factor;
  5593. max_feedrate[i] *= factor;
  5594. axis_steps_per_sqr_second[i] *= factor;
  5595. }
  5596. cs.axis_steps_per_unit[i] = value;
  5597. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5598. fsensor.init();
  5599. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5600. }
  5601. else {
  5602. cs.axis_steps_per_unit[i] = code_value();
  5603. }
  5604. }
  5605. }
  5606. reset_acceleration_rates();
  5607. break;
  5608. /*!
  5609. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5610. Sets the line number in G-code
  5611. #### Usage
  5612. M110 [ N ]
  5613. #### Parameters
  5614. - `N` - Line number
  5615. */
  5616. case 110:
  5617. if (code_seen('N'))
  5618. gcode_LastN = code_value_long();
  5619. break;
  5620. /*!
  5621. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5622. 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).
  5623. #### Usage
  5624. M113 [ S ]
  5625. #### Parameters
  5626. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5627. */
  5628. case 113:
  5629. if (code_seen('S')) {
  5630. host_keepalive_interval = code_value_uint8();
  5631. // NOMORE(host_keepalive_interval, 60);
  5632. }
  5633. else {
  5634. SERIAL_ECHO_START;
  5635. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5636. SERIAL_PROTOCOLLN();
  5637. }
  5638. break;
  5639. /*!
  5640. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5641. Print the firmware info and capabilities
  5642. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5643. `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.
  5644. _Examples:_
  5645. `M115` results:
  5646. `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`
  5647. `M115 V` results:
  5648. `3.8.1`
  5649. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5650. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5651. #### Usage
  5652. M115 [ V | U ]
  5653. #### Parameters
  5654. - V - Report current installed firmware version
  5655. - U - Firmware version provided by G-code to be compared to current one.
  5656. */
  5657. case 115: // M115
  5658. if (code_seen('V')) {
  5659. // Report the Prusa version number.
  5660. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5661. } else if (code_seen('U')) {
  5662. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5663. // pause the print for 30s and ask the user to upgrade the firmware.
  5664. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5665. } else {
  5666. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5667. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5668. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5669. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5670. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5671. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5672. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5673. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5674. SERIAL_ECHOPGM(" UUID:");
  5675. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5676. #ifdef EXTENDED_CAPABILITIES_REPORT
  5677. extended_capabilities_report();
  5678. #endif //EXTENDED_CAPABILITIES_REPORT
  5679. }
  5680. break;
  5681. /*!
  5682. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5683. */
  5684. case 114:
  5685. gcode_M114();
  5686. break;
  5687. /*
  5688. M117 moved up to get the high priority
  5689. case 117: // M117 display message
  5690. starpos = (strchr(strchr_pointer + 5,'*'));
  5691. if(starpos!=NULL)
  5692. *(starpos)='\0';
  5693. lcd_setstatus(strchr_pointer + 5);
  5694. break;*/
  5695. #ifdef M120_M121_ENABLED
  5696. /*!
  5697. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5698. */
  5699. case 120:
  5700. enable_endstops(true) ;
  5701. break;
  5702. /*!
  5703. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5704. */
  5705. case 121:
  5706. enable_endstops(false) ;
  5707. break;
  5708. #endif //M120_M121_ENABLED
  5709. /*!
  5710. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5711. 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.
  5712. */
  5713. case 119:
  5714. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5715. SERIAL_PROTOCOLLN();
  5716. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5717. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5718. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5719. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5720. }else{
  5721. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5722. }
  5723. SERIAL_PROTOCOLLN();
  5724. #endif
  5725. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5726. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5727. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5728. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5729. }else{
  5730. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5731. }
  5732. SERIAL_PROTOCOLLN();
  5733. #endif
  5734. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5735. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5736. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5737. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5738. }else{
  5739. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5740. }
  5741. SERIAL_PROTOCOLLN();
  5742. #endif
  5743. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5744. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5745. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5746. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5747. }else{
  5748. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5749. }
  5750. SERIAL_PROTOCOLLN();
  5751. #endif
  5752. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5753. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5754. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5755. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5756. }else{
  5757. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5758. }
  5759. SERIAL_PROTOCOLLN();
  5760. #endif
  5761. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5762. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5763. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5764. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5765. }else{
  5766. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5767. }
  5768. SERIAL_PROTOCOLLN();
  5769. #endif
  5770. break;
  5771. //!@todo update for all axes, use for loop
  5772. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5773. /*!
  5774. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5775. This command is used to report fan speeds and fan pwm values.
  5776. #### Usage
  5777. M123
  5778. - E0: - Hotend fan speed in RPM
  5779. - PRN1: - Part cooling fans speed in RPM
  5780. - E0@: - Hotend fan PWM value
  5781. - PRN1@: -Part cooling fan PWM value
  5782. _Example:_
  5783. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5784. */
  5785. case 123:
  5786. gcode_M123();
  5787. break;
  5788. #endif //FANCHECK and TACH_0 and TACH_1
  5789. #ifdef BLINKM
  5790. /*!
  5791. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5792. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5793. #### Usage
  5794. M150 [ R | U | B ]
  5795. #### Parameters
  5796. - `R` - Red color value
  5797. - `U` - Green color value. It is NOT `G`!
  5798. - `B` - Blue color value
  5799. */
  5800. case 150:
  5801. {
  5802. byte red;
  5803. byte grn;
  5804. byte blu;
  5805. if(code_seen('R')) red = code_value();
  5806. if(code_seen('U')) grn = code_value();
  5807. if(code_seen('B')) blu = code_value();
  5808. SendColors(red,grn,blu);
  5809. }
  5810. break;
  5811. #endif //BLINKM
  5812. /*!
  5813. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5814. #### Usage
  5815. M200 [ D | T ]
  5816. #### Parameters
  5817. - `D` - Diameter in mm
  5818. - `T` - Number of extruder (MMUs)
  5819. */
  5820. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5821. {
  5822. uint8_t extruder = active_extruder;
  5823. if(code_seen('T')) {
  5824. extruder = code_value_uint8();
  5825. if(extruder >= EXTRUDERS) {
  5826. SERIAL_ECHO_START;
  5827. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5828. break;
  5829. }
  5830. }
  5831. if(code_seen('D')) {
  5832. float diameter = code_value();
  5833. if (diameter == 0.0) {
  5834. // setting any extruder filament size disables volumetric on the assumption that
  5835. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5836. // for all extruders
  5837. cs.volumetric_enabled = false;
  5838. } else {
  5839. cs.filament_size[extruder] = code_value();
  5840. // make sure all extruders have some sane value for the filament size
  5841. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5842. #if EXTRUDERS > 1
  5843. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5844. #if EXTRUDERS > 2
  5845. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5846. #endif
  5847. #endif
  5848. cs.volumetric_enabled = true;
  5849. }
  5850. } else {
  5851. //reserved for setting filament diameter via UFID or filament measuring device
  5852. break;
  5853. }
  5854. calculate_extruder_multipliers();
  5855. }
  5856. break;
  5857. /*!
  5858. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5859. For each axis individually.
  5860. ##### Usage
  5861. M201 [ X | Y | Z | E ]
  5862. ##### Parameters
  5863. - `X` - Acceleration for X axis in units/s^2
  5864. - `Y` - Acceleration for Y axis in units/s^2
  5865. - `Z` - Acceleration for Z axis in units/s^2
  5866. - `E` - Acceleration for the active or specified extruder in units/s^2
  5867. */
  5868. case 201:
  5869. for (int8_t i = 0; i < NUM_AXIS; i++)
  5870. {
  5871. if (code_seen(axis_codes[i]))
  5872. {
  5873. unsigned long val = code_value();
  5874. #ifdef TMC2130
  5875. unsigned long val_silent = val;
  5876. if ((i == X_AXIS) || (i == Y_AXIS))
  5877. {
  5878. if (val > NORMAL_MAX_ACCEL_XY)
  5879. val = NORMAL_MAX_ACCEL_XY;
  5880. if (val_silent > SILENT_MAX_ACCEL_XY)
  5881. val_silent = SILENT_MAX_ACCEL_XY;
  5882. }
  5883. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5884. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5885. #else //TMC2130
  5886. max_acceleration_units_per_sq_second[i] = val;
  5887. #endif //TMC2130
  5888. }
  5889. }
  5890. // 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)
  5891. reset_acceleration_rates();
  5892. break;
  5893. #if 0 // Not used for Sprinter/grbl gen6
  5894. case 202: // M202
  5895. for(int8_t i=0; i < NUM_AXIS; i++) {
  5896. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5897. }
  5898. break;
  5899. #endif
  5900. /*!
  5901. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5902. For each axis individually.
  5903. ##### Usage
  5904. M203 [ X | Y | Z | E ]
  5905. ##### Parameters
  5906. - `X` - Maximum feedrate for X axis
  5907. - `Y` - Maximum feedrate for Y axis
  5908. - `Z` - Maximum feedrate for Z axis
  5909. - `E` - Maximum feedrate for extruder drives
  5910. */
  5911. case 203: // M203 max feedrate mm/sec
  5912. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5913. {
  5914. if (code_seen(axis_codes[i]))
  5915. {
  5916. float val = code_value();
  5917. #ifdef TMC2130
  5918. float val_silent = val;
  5919. if ((i == X_AXIS) || (i == Y_AXIS))
  5920. {
  5921. if (val > NORMAL_MAX_FEEDRATE_XY)
  5922. val = NORMAL_MAX_FEEDRATE_XY;
  5923. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5924. val_silent = SILENT_MAX_FEEDRATE_XY;
  5925. }
  5926. cs.max_feedrate_normal[i] = val;
  5927. cs.max_feedrate_silent[i] = val_silent;
  5928. #else //TMC2130
  5929. max_feedrate[i] = val;
  5930. #endif //TMC2130
  5931. }
  5932. }
  5933. break;
  5934. /*!
  5935. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  5936. #### Old format:
  5937. ##### Usage
  5938. M204 [ S | T ]
  5939. ##### Parameters
  5940. - `S` - normal moves
  5941. - `T` - filmanent only moves
  5942. #### New format:
  5943. ##### Usage
  5944. M204 [ P | R | T ]
  5945. ##### Parameters
  5946. - `P` - printing moves
  5947. - `R` - filmanent only moves
  5948. - `T` - travel moves (as of now T is ignored)
  5949. */
  5950. case 204:
  5951. {
  5952. if(code_seen('S')) {
  5953. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5954. // and it is also generated by Slic3r to control acceleration per extrusion type
  5955. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5956. cs.acceleration = cs.travel_acceleration = code_value();
  5957. // Interpret the T value as retract acceleration in the old Marlin format.
  5958. if(code_seen('T'))
  5959. cs.retract_acceleration = code_value();
  5960. } else {
  5961. // New acceleration format, compatible with the upstream Marlin.
  5962. if(code_seen('P'))
  5963. cs.acceleration = code_value();
  5964. if(code_seen('R'))
  5965. cs.retract_acceleration = code_value();
  5966. if(code_seen('T'))
  5967. cs.travel_acceleration = code_value();
  5968. }
  5969. }
  5970. break;
  5971. /*!
  5972. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  5973. Set some advanced settings related to movement.
  5974. #### Usage
  5975. M205 [ S | T | B | X | Y | Z | E ]
  5976. #### Parameters
  5977. - `S` - Minimum feedrate for print moves (unit/s)
  5978. - `T` - Minimum feedrate for travel moves (units/s)
  5979. - `B` - Minimum segment time (us)
  5980. - `X` - Maximum X jerk (units/s)
  5981. - `Y` - Maximum Y jerk (units/s)
  5982. - `Z` - Maximum Z jerk (units/s)
  5983. - `E` - Maximum E jerk (units/s)
  5984. */
  5985. case 205:
  5986. {
  5987. if(code_seen('S')) cs.minimumfeedrate = code_value();
  5988. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  5989. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  5990. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  5991. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  5992. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  5993. if(code_seen('E'))
  5994. {
  5995. float e = code_value();
  5996. #ifndef LA_NOCOMPAT
  5997. e = la10c_jerk(e);
  5998. #endif
  5999. cs.max_jerk[E_AXIS] = e;
  6000. }
  6001. }
  6002. break;
  6003. /*!
  6004. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6005. #### Usage
  6006. M206 [ X | Y | Z ]
  6007. #### Parameters
  6008. - `X` - X axis offset
  6009. - `Y` - Y axis offset
  6010. - `Z` - Z axis offset
  6011. */
  6012. case 206:
  6013. for(uint8_t i=0; i < 3; i++)
  6014. {
  6015. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6016. }
  6017. break;
  6018. #ifdef FWRETRACT
  6019. /*!
  6020. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6021. #### Usage
  6022. M207 [ S | F | Z ]
  6023. #### Parameters
  6024. - `S` - positive length to retract, in mm
  6025. - `F` - retraction feedrate, in mm/min
  6026. - `Z` - additional zlift/hop
  6027. */
  6028. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6029. {
  6030. if(code_seen('S'))
  6031. {
  6032. cs.retract_length = code_value() ;
  6033. }
  6034. if(code_seen('F'))
  6035. {
  6036. cs.retract_feedrate = code_value()/60 ;
  6037. }
  6038. if(code_seen('Z'))
  6039. {
  6040. cs.retract_zlift = code_value() ;
  6041. }
  6042. }break;
  6043. /*!
  6044. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6045. #### Usage
  6046. M208 [ S | F ]
  6047. #### Parameters
  6048. - `S` - positive length surplus to the M207 Snnn, in mm
  6049. - `F` - feedrate, in mm/sec
  6050. */
  6051. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6052. {
  6053. if(code_seen('S'))
  6054. {
  6055. cs.retract_recover_length = code_value() ;
  6056. }
  6057. if(code_seen('F'))
  6058. {
  6059. cs.retract_recover_feedrate = code_value()/60 ;
  6060. }
  6061. }break;
  6062. /*!
  6063. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6064. 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.
  6065. #### Usage
  6066. M209 [ S ]
  6067. #### Parameters
  6068. - `S` - 1=true or 0=false
  6069. */
  6070. 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.
  6071. {
  6072. if(code_seen('S'))
  6073. {
  6074. switch(code_value_uint8())
  6075. {
  6076. case 0:
  6077. {
  6078. cs.autoretract_enabled=false;
  6079. retracted[0]=false;
  6080. #if EXTRUDERS > 1
  6081. retracted[1]=false;
  6082. #endif
  6083. #if EXTRUDERS > 2
  6084. retracted[2]=false;
  6085. #endif
  6086. }break;
  6087. case 1:
  6088. {
  6089. cs.autoretract_enabled=true;
  6090. retracted[0]=false;
  6091. #if EXTRUDERS > 1
  6092. retracted[1]=false;
  6093. #endif
  6094. #if EXTRUDERS > 2
  6095. retracted[2]=false;
  6096. #endif
  6097. }break;
  6098. default:
  6099. SERIAL_ECHO_START;
  6100. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6101. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6102. SERIAL_ECHOLNPGM("\"(1)");
  6103. }
  6104. }
  6105. }break;
  6106. #endif // FWRETRACT
  6107. /*!
  6108. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6109. #### Usage
  6110. M214 [P] [S] [N] [R] [F]
  6111. #### Parameters
  6112. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6113. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6114. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6115. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6116. except when the results in segment lengths greater than or less than the minimum
  6117. and maximum segment length. Set to 0 to disable.
  6118. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6119. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6120. */
  6121. 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>
  6122. {
  6123. // Extract all possible parameters if they appear
  6124. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6125. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6126. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6127. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6128. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6129. // 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
  6130. if (p <=0 || s < 0 || p < s)
  6131. {
  6132. // Should we display some error here?
  6133. break;
  6134. }
  6135. cs.mm_per_arc_segment = p;
  6136. cs.min_mm_per_arc_segment = s;
  6137. cs.n_arc_correction = n;
  6138. cs.min_arc_segments = r;
  6139. cs.arc_segments_per_sec = f;
  6140. }break;
  6141. #if EXTRUDERS > 1
  6142. /*!
  6143. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6144. 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.
  6145. #### Usage
  6146. M218 [ X | Y ]
  6147. #### Parameters
  6148. - `X` - X offset
  6149. - `Y` - Y offset
  6150. */
  6151. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6152. {
  6153. uint8_t extruder;
  6154. if(setTargetedHotend(218, extruder)){
  6155. break;
  6156. }
  6157. if(code_seen('X'))
  6158. {
  6159. extruder_offset[X_AXIS][extruder] = code_value();
  6160. }
  6161. if(code_seen('Y'))
  6162. {
  6163. extruder_offset[Y_AXIS][extruder] = code_value();
  6164. }
  6165. SERIAL_ECHO_START;
  6166. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6167. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6168. {
  6169. SERIAL_ECHO(" ");
  6170. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6171. SERIAL_ECHO(",");
  6172. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6173. }
  6174. SERIAL_ECHOLN("");
  6175. }break;
  6176. #endif
  6177. /*!
  6178. ### 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>
  6179. #### Usage
  6180. M220 [ B | S | R ]
  6181. #### Parameters
  6182. - `B` - Backup current speed factor
  6183. - `S` - Speed factor override percentage (0..100 or higher)
  6184. - `R` - Restore previous speed factor
  6185. */
  6186. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6187. {
  6188. bool codesWereSeen = false;
  6189. if (code_seen('B')) //backup current speed factor
  6190. {
  6191. saved_feedmultiply_mm = feedmultiply;
  6192. codesWereSeen = true;
  6193. }
  6194. if (code_seen('S'))
  6195. {
  6196. feedmultiply = code_value_short();
  6197. codesWereSeen = true;
  6198. }
  6199. if (code_seen('R')) //restore previous feedmultiply
  6200. {
  6201. feedmultiply = saved_feedmultiply_mm;
  6202. codesWereSeen = true;
  6203. }
  6204. if (!codesWereSeen)
  6205. {
  6206. printf_P(PSTR("%i%%\n"), feedmultiply);
  6207. }
  6208. }
  6209. break;
  6210. /*!
  6211. ### 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>
  6212. #### Usage
  6213. M221 [ S | T ]
  6214. #### Parameters
  6215. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6216. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6217. */
  6218. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6219. {
  6220. if (code_seen('S'))
  6221. {
  6222. int tmp_code = code_value_short();
  6223. if (code_seen('T'))
  6224. {
  6225. uint8_t extruder;
  6226. if (setTargetedHotend(221, extruder))
  6227. break;
  6228. extruder_multiply[extruder] = tmp_code;
  6229. }
  6230. else
  6231. {
  6232. extrudemultiply = tmp_code ;
  6233. }
  6234. }
  6235. else
  6236. {
  6237. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6238. }
  6239. calculate_extruder_multipliers();
  6240. }
  6241. break;
  6242. /*!
  6243. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6244. Wait until the specified pin reaches the state required
  6245. #### Usage
  6246. M226 [ P | S ]
  6247. #### Parameters
  6248. - `P` - pin number
  6249. - `S` - pin state
  6250. */
  6251. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6252. {
  6253. if(code_seen('P')){
  6254. int pin_number = code_value_short(); // pin number
  6255. int pin_state = -1; // required pin state - default is inverted
  6256. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6257. if(pin_state >= -1 && pin_state <= 1){
  6258. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6259. {
  6260. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6261. {
  6262. pin_number = -1;
  6263. break;
  6264. }
  6265. }
  6266. if (pin_number > -1)
  6267. {
  6268. int target = LOW;
  6269. st_synchronize();
  6270. pinMode(pin_number, INPUT);
  6271. switch(pin_state){
  6272. case 1:
  6273. target = HIGH;
  6274. break;
  6275. case 0:
  6276. target = LOW;
  6277. break;
  6278. case -1:
  6279. target = !digitalRead(pin_number);
  6280. break;
  6281. }
  6282. while(digitalRead(pin_number) != target){
  6283. manage_heater();
  6284. manage_inactivity();
  6285. lcd_update(0);
  6286. }
  6287. }
  6288. }
  6289. }
  6290. }
  6291. break;
  6292. #if NUM_SERVOS > 0
  6293. /*!
  6294. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6295. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6296. #### Usage
  6297. M280 [ P | S ]
  6298. #### Parameters
  6299. - `P` - Servo index (id)
  6300. - `S` - Target position
  6301. */
  6302. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6303. {
  6304. int servo_index = -1;
  6305. int servo_position = 0;
  6306. if (code_seen('P'))
  6307. servo_index = code_value();
  6308. if (code_seen('S')) {
  6309. servo_position = code_value();
  6310. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6311. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6312. servos[servo_index].attach(0);
  6313. #endif
  6314. servos[servo_index].write(servo_position);
  6315. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6316. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6317. servos[servo_index].detach();
  6318. #endif
  6319. }
  6320. else {
  6321. SERIAL_ECHO_START;
  6322. SERIAL_ECHO("Servo ");
  6323. SERIAL_ECHO(servo_index);
  6324. SERIAL_ECHOLN(" out of range");
  6325. }
  6326. }
  6327. else if (servo_index >= 0) {
  6328. SERIAL_PROTOCOL(MSG_OK);
  6329. SERIAL_PROTOCOL(" Servo ");
  6330. SERIAL_PROTOCOL(servo_index);
  6331. SERIAL_PROTOCOL(": ");
  6332. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6333. }
  6334. }
  6335. break;
  6336. #endif // NUM_SERVOS > 0
  6337. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6338. /*!
  6339. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6340. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6341. #### Usage
  6342. M300 [ S | P ]
  6343. #### Parameters
  6344. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6345. - `P` - duration in milliseconds
  6346. */
  6347. case 300: // M300
  6348. {
  6349. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6350. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6351. #if BEEPER > 0
  6352. if (beepP > 0)
  6353. Sound_MakeCustom(beepP,beepS,false);
  6354. #endif
  6355. }
  6356. break;
  6357. #endif // M300
  6358. #ifdef PIDTEMP
  6359. /*!
  6360. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6361. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6362. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6363. #### Usage
  6364. M301 [ P | I | D ]
  6365. #### Parameters
  6366. - `P` - proportional (Kp)
  6367. - `I` - integral (Ki)
  6368. - `D` - derivative (Kd)
  6369. */
  6370. case 301:
  6371. {
  6372. if(code_seen('P')) cs.Kp = code_value();
  6373. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6374. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6375. updatePID();
  6376. SERIAL_PROTOCOLRPGM(MSG_OK);
  6377. SERIAL_PROTOCOLPGM(" p:");
  6378. SERIAL_PROTOCOL(cs.Kp);
  6379. SERIAL_PROTOCOLPGM(" i:");
  6380. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6381. SERIAL_PROTOCOLPGM(" d:");
  6382. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6383. SERIAL_PROTOCOLLN();
  6384. }
  6385. break;
  6386. #endif //PIDTEMP
  6387. #ifdef PIDTEMPBED
  6388. /*!
  6389. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6390. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6391. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6392. #### Usage
  6393. M304 [ P | I | D ]
  6394. #### Parameters
  6395. - `P` - proportional (Kp)
  6396. - `I` - integral (Ki)
  6397. - `D` - derivative (Kd)
  6398. */
  6399. case 304:
  6400. {
  6401. if(code_seen('P')) cs.bedKp = code_value();
  6402. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6403. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6404. updatePID();
  6405. SERIAL_PROTOCOLRPGM(MSG_OK);
  6406. SERIAL_PROTOCOLPGM(" p:");
  6407. SERIAL_PROTOCOL(cs.bedKp);
  6408. SERIAL_PROTOCOLPGM(" i:");
  6409. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6410. SERIAL_PROTOCOLPGM(" d:");
  6411. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6412. }
  6413. break;
  6414. #endif //PIDTEMP
  6415. /*!
  6416. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6417. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6418. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6419. */
  6420. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6421. {
  6422. #ifdef CHDK
  6423. SET_OUTPUT(CHDK);
  6424. WRITE(CHDK, HIGH);
  6425. chdkHigh = _millis();
  6426. chdkActive = true;
  6427. #else
  6428. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6429. const uint8_t NUM_PULSES=16;
  6430. const float PULSE_LENGTH=0.01524;
  6431. for(int i=0; i < NUM_PULSES; i++) {
  6432. WRITE(PHOTOGRAPH_PIN, HIGH);
  6433. _delay_ms(PULSE_LENGTH);
  6434. WRITE(PHOTOGRAPH_PIN, LOW);
  6435. _delay_ms(PULSE_LENGTH);
  6436. }
  6437. _delay(7.33);
  6438. for(int i=0; i < NUM_PULSES; i++) {
  6439. WRITE(PHOTOGRAPH_PIN, HIGH);
  6440. _delay_ms(PULSE_LENGTH);
  6441. WRITE(PHOTOGRAPH_PIN, LOW);
  6442. _delay_ms(PULSE_LENGTH);
  6443. }
  6444. #endif
  6445. #endif //chdk end if
  6446. }
  6447. break;
  6448. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6449. /*!
  6450. ### 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>
  6451. 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.
  6452. #### Usage
  6453. M302 [ S ]
  6454. #### Parameters
  6455. - `S` - Cold extrude minimum temperature
  6456. */
  6457. case 302:
  6458. {
  6459. int temp = 0;
  6460. if (code_seen('S')) temp=code_value_short();
  6461. set_extrude_min_temp(temp);
  6462. }
  6463. break;
  6464. #endif
  6465. /*!
  6466. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6467. 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.
  6468. #### Usage
  6469. M303 [ E | S | C ]
  6470. #### Parameters
  6471. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6472. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6473. - `C` - Cycles, default `5`
  6474. */
  6475. case 303:
  6476. {
  6477. float temp = 150.0;
  6478. int e = 0;
  6479. int c = 5;
  6480. if (code_seen('E')) e = code_value_short();
  6481. if (e < 0)
  6482. temp = 70;
  6483. if (code_seen('S')) temp = code_value();
  6484. if (code_seen('C')) c = code_value_short();
  6485. PID_autotune(temp, e, c);
  6486. }
  6487. break;
  6488. #ifdef TEMP_MODEL
  6489. /*!
  6490. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6491. #### Usage
  6492. M310 ; report values
  6493. M310 [ A ] [ F ] ; autotune
  6494. M310 [ S ] ; set 0=disable 1=enable
  6495. M310 [ I ] [ R ] ; set resistance at index
  6496. M310 [ P | C ] ; set power, capacitance
  6497. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6498. M310 [ T ] ; set ambient temperature correction
  6499. #### Parameters
  6500. - `I` - resistance index position (0-15)
  6501. - `R` - resistance value at index (K/W; requires `I`)
  6502. - `P` - power (W)
  6503. - `C` - capacitance (J/K)
  6504. - `S` - set 0=disable 1=enable
  6505. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6506. - `E` - error threshold (K/s; default in variant)
  6507. - `W` - warning threshold (K/s; default in variant)
  6508. - `T` - ambient temperature correction (K; default in variant)
  6509. - `A` - autotune C+R values
  6510. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6511. */
  6512. case 310:
  6513. {
  6514. // parse all parameters
  6515. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6516. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6517. if(code_seen('C')) C = code_value();
  6518. if(code_seen('P')) P = code_value();
  6519. if(code_seen('I')) I = code_value_short();
  6520. if(code_seen('R')) R = code_value();
  6521. if(code_seen('S')) S = code_value_short();
  6522. if(code_seen('B')) B = code_value_short();
  6523. if(code_seen('E')) E = code_value();
  6524. if(code_seen('W')) W = code_value();
  6525. if(code_seen('T')) T = code_value();
  6526. if(code_seen('A')) A = code_value_short();
  6527. if(code_seen('F')) F = code_value_short();
  6528. // report values if nothing has been requested
  6529. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6530. temp_model_report_settings();
  6531. break;
  6532. }
  6533. // update all parameters
  6534. if(B >= 0) temp_model_set_warn_beep(B);
  6535. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6536. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6537. // enable the model last, if requested
  6538. if(S >= 0) temp_model_set_enabled(S);
  6539. // run autotune
  6540. if(A >= 0) temp_model_autotune(A, F > 0);
  6541. }
  6542. break;
  6543. #endif
  6544. /*!
  6545. ### 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>
  6546. Finishes all current moves and and thus clears the buffer.
  6547. Equivalent to `G4` with no parameters.
  6548. */
  6549. case 400:
  6550. {
  6551. st_synchronize();
  6552. }
  6553. break;
  6554. /*!
  6555. ### 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>
  6556. Currently three different materials are needed (default, flex and PVA).
  6557. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6558. #### Usage
  6559. M403 [ E | F ]
  6560. #### Parameters
  6561. - `E` - Extruder number. 0-indexed.
  6562. - `F` - Filament type
  6563. */
  6564. case 403:
  6565. {
  6566. // currently three different materials are needed (default, flex and PVA)
  6567. // add storing this information for different load/unload profiles etc. in the future
  6568. if (MMU2::mmu2.Enabled())
  6569. {
  6570. uint8_t extruder = 255;
  6571. uint8_t filament = FILAMENT_UNDEFINED;
  6572. if(code_seen('E')) extruder = code_value_uint8();
  6573. if(code_seen('F')) filament = code_value_uint8();
  6574. MMU2::mmu2.set_filament_type(extruder, filament);
  6575. }
  6576. }
  6577. break;
  6578. /*!
  6579. ### 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>
  6580. Save current parameters to EEPROM.
  6581. */
  6582. case 500:
  6583. {
  6584. Config_StoreSettings();
  6585. }
  6586. break;
  6587. /*!
  6588. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6589. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6590. */
  6591. case 501:
  6592. {
  6593. Config_RetrieveSettings();
  6594. }
  6595. break;
  6596. /*!
  6597. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6598. 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.
  6599. */
  6600. case 502:
  6601. {
  6602. Config_ResetDefault();
  6603. }
  6604. break;
  6605. /*!
  6606. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6607. 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.
  6608. */
  6609. case 503:
  6610. {
  6611. Config_PrintSettings();
  6612. }
  6613. break;
  6614. /*!
  6615. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6616. Resets the language to English.
  6617. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6618. */
  6619. case 509:
  6620. {
  6621. lang_reset();
  6622. SERIAL_ECHO_START;
  6623. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6624. }
  6625. break;
  6626. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6627. /*!
  6628. ### 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>
  6629. 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`.
  6630. #### Usage
  6631. M540 [ S ]
  6632. #### Parameters
  6633. - `S` - disabled=0, enabled=1
  6634. */
  6635. case 540:
  6636. {
  6637. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6638. }
  6639. break;
  6640. #endif
  6641. #ifdef ENABLE_AUTO_BED_LEVELING
  6642. /*!
  6643. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6644. 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.
  6645. 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.)
  6646. #### Usage
  6647. M851 [ Z ]
  6648. #### Parameters
  6649. - `Z` - Z offset probe to nozzle.
  6650. */
  6651. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6652. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6653. {
  6654. float value;
  6655. if (code_seen('Z'))
  6656. {
  6657. value = code_value();
  6658. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6659. {
  6660. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6661. SERIAL_ECHO_START;
  6662. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6663. SERIAL_PROTOCOLLN();
  6664. }
  6665. else
  6666. {
  6667. SERIAL_ECHO_START;
  6668. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6669. SERIAL_ECHORPGM(MSG_Z_MIN);
  6670. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6671. SERIAL_ECHORPGM(MSG_Z_MAX);
  6672. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6673. SERIAL_PROTOCOLLN();
  6674. }
  6675. }
  6676. else
  6677. {
  6678. SERIAL_ECHO_START;
  6679. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6680. SERIAL_ECHO(-cs.zprobe_zoffset);
  6681. SERIAL_PROTOCOLLN();
  6682. }
  6683. break;
  6684. }
  6685. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6686. #endif // ENABLE_AUTO_BED_LEVELING
  6687. /*!
  6688. ### 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>
  6689. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6690. If P is not specified nothing happens.
  6691. 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.
  6692. #### Usage
  6693. M552 [ P<IP_address> ]
  6694. #### Parameters
  6695. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6696. */
  6697. case 552:
  6698. {
  6699. if (code_seen('P'))
  6700. {
  6701. uint8_t valCnt = 0;
  6702. IP_address = 0;
  6703. do
  6704. {
  6705. *strchr_pointer = '*';
  6706. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6707. valCnt++;
  6708. } while ((valCnt < 4) && code_seen('.'));
  6709. if (valCnt != 4)
  6710. IP_address = 0;
  6711. }
  6712. } break;
  6713. #ifdef FILAMENTCHANGEENABLE
  6714. /*!
  6715. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6716. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6717. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6718. #### Usage
  6719. M600 [ X | Y | Z | E | L | AUTO ]
  6720. - `X` - X position, default 211
  6721. - `Y` - Y position, default 0
  6722. - `Z` - relative lift Z, default MIN_Z_FOR_SWAP.
  6723. - `E` - initial retract, default -2
  6724. - `L` - later retract distance for removal, default -80
  6725. - `AUTO` - Automatically (only with MMU)
  6726. */
  6727. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6728. {
  6729. st_synchronize();
  6730. float x_position = current_position[X_AXIS];
  6731. float y_position = current_position[Y_AXIS];
  6732. float z_shift = MIN_Z_FOR_SWAP;
  6733. float e_shift_init = 0;
  6734. float e_shift_late = 0;
  6735. bool automatic = false;
  6736. //Retract extruder
  6737. if(code_seen('E'))
  6738. {
  6739. e_shift_init = code_value();
  6740. }
  6741. else
  6742. {
  6743. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6744. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6745. #endif
  6746. }
  6747. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6748. if (code_seen('L'))
  6749. {
  6750. e_shift_late = code_value();
  6751. }
  6752. else
  6753. {
  6754. #ifdef FILAMENTCHANGE_FINALRETRACT
  6755. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6756. #endif
  6757. }
  6758. // Z lift. For safety only allow positive values
  6759. if (code_seen('Z')) z_shift = fabs(code_value());
  6760. //Move XY to side
  6761. if(code_seen('X'))
  6762. {
  6763. x_position = code_value();
  6764. }
  6765. else
  6766. {
  6767. #ifdef FILAMENTCHANGE_XPOS
  6768. x_position = FILAMENTCHANGE_XPOS;
  6769. #endif
  6770. }
  6771. if(code_seen('Y'))
  6772. {
  6773. y_position = code_value();
  6774. }
  6775. else
  6776. {
  6777. #ifdef FILAMENTCHANGE_YPOS
  6778. y_position = FILAMENTCHANGE_YPOS ;
  6779. #endif
  6780. }
  6781. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6782. automatic = true;
  6783. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6784. }
  6785. break;
  6786. #endif //FILAMENTCHANGEENABLE
  6787. /*!
  6788. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6789. */
  6790. /*!
  6791. ### M125 - Pause print (TODO: not implemented)
  6792. */
  6793. /*!
  6794. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6795. */
  6796. case 25:
  6797. case 601:
  6798. {
  6799. if (!isPrintPaused) {
  6800. st_synchronize();
  6801. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6802. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6803. lcd_pause_print();
  6804. }
  6805. }
  6806. break;
  6807. /*!
  6808. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6809. */
  6810. case 602:
  6811. {
  6812. if (isPrintPaused) lcd_resume_print();
  6813. }
  6814. break;
  6815. /*!
  6816. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6817. */
  6818. case 603: {
  6819. lcd_print_stop();
  6820. }
  6821. break;
  6822. #ifdef PINDA_THERMISTOR
  6823. /*!
  6824. ### 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>
  6825. Wait for PINDA thermistor to reach target temperature
  6826. #### Usage
  6827. M860 [ S ]
  6828. #### Parameters
  6829. - `S` - Target temperature
  6830. */
  6831. case 860:
  6832. {
  6833. int set_target_pinda = 0;
  6834. if (code_seen('S')) {
  6835. set_target_pinda = code_value_short();
  6836. }
  6837. else {
  6838. break;
  6839. }
  6840. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6841. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6842. SERIAL_PROTOCOLLN(set_target_pinda);
  6843. codenum = _millis();
  6844. cancel_heatup = false;
  6845. bool is_pinda_cooling = false;
  6846. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6847. is_pinda_cooling = true;
  6848. }
  6849. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6850. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6851. {
  6852. SERIAL_PROTOCOLPGM("P:");
  6853. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6854. SERIAL_PROTOCOL('/');
  6855. SERIAL_PROTOCOLLN(set_target_pinda);
  6856. codenum = _millis();
  6857. }
  6858. manage_heater();
  6859. manage_inactivity();
  6860. lcd_update(0);
  6861. }
  6862. LCD_MESSAGERPGM(MSG_OK);
  6863. break;
  6864. }
  6865. /*!
  6866. ### 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>
  6867. Set compensation ustep value `S` for compensation table index `I`.
  6868. #### Usage
  6869. M861 [ ? | ! | Z | S | I ]
  6870. #### Parameters
  6871. - `?` - Print current EEPROM offset values
  6872. - `!` - Set factory default values
  6873. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6874. - `S` - Microsteps
  6875. - `I` - Table index
  6876. */
  6877. case 861: {
  6878. const char * const _header = PSTR("index, temp, ustep, um");
  6879. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6880. int16_t usteps = 0;
  6881. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6882. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6883. SERIAL_PROTOCOLLNRPGM(_header);
  6884. for (uint8_t i = 0; i < 6; i++)
  6885. {
  6886. if(i > 0) {
  6887. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6888. }
  6889. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6890. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6891. SERIAL_PROTOCOLPGM(", ");
  6892. SERIAL_PROTOCOL(35 + (i * 5));
  6893. SERIAL_PROTOCOLPGM(", ");
  6894. SERIAL_PROTOCOL(usteps);
  6895. SERIAL_PROTOCOLPGM(", ");
  6896. SERIAL_PROTOCOLLN(mm * 1000);
  6897. }
  6898. }
  6899. else if (code_seen('!')) { // ! - Set factory default values
  6900. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6901. int16_t z_shift = 8; //40C - 20um - 8usteps
  6902. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6903. z_shift = 24; //45C - 60um - 24usteps
  6904. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6905. z_shift = 48; //50C - 120um - 48usteps
  6906. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6907. z_shift = 80; //55C - 200um - 80usteps
  6908. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6909. z_shift = 120; //60C - 300um - 120usteps
  6910. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6911. SERIAL_PROTOCOLLNPGM("factory restored");
  6912. }
  6913. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6914. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6915. int16_t z_shift = 0;
  6916. for (uint8_t i = 0; i < 5; i++) {
  6917. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  6918. }
  6919. SERIAL_PROTOCOLLNPGM("zerorized");
  6920. }
  6921. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6922. int16_t usteps = code_value_short();
  6923. if (code_seen('I')) {
  6924. uint8_t index = code_value_uint8();
  6925. if (index < 5) {
  6926. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  6927. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6928. SERIAL_PROTOCOLLNRPGM(_header);
  6929. for (uint8_t i = 0; i < 6; i++)
  6930. {
  6931. usteps = 0;
  6932. if (i > 0) {
  6933. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6934. }
  6935. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6936. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6937. SERIAL_PROTOCOLPGM(", ");
  6938. SERIAL_PROTOCOL(35 + (i * 5));
  6939. SERIAL_PROTOCOLPGM(", ");
  6940. SERIAL_PROTOCOL(usteps);
  6941. SERIAL_PROTOCOLPGM(", ");
  6942. SERIAL_PROTOCOLLN(mm * 1000);
  6943. }
  6944. }
  6945. }
  6946. }
  6947. else {
  6948. SERIAL_PROTOCOLLNPGM("no valid command");
  6949. }
  6950. } break;
  6951. #endif //PINDA_THERMISTOR
  6952. /*!
  6953. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  6954. Checks the parameters of the printer and gcode and performs compatibility check
  6955. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  6956. - M862.2 { P<model_code> | Q }
  6957. - M862.3 { P"<model_name>" | Q }
  6958. - M862.4 { P<fw_version> | Q }
  6959. - M862.5 { P<gcode_level> | Q }
  6960. When run with P<> argument, the check is performed against the input value.
  6961. When run with Q argument, the current value is shown.
  6962. M862.3 accepts text identifiers of printer types too.
  6963. The syntax of M862.3 is (note the quotes around the type):
  6964. M862.3 P "MK3S"
  6965. Accepted printer type identifiers and their numeric counterparts:
  6966. - MK1 (100)
  6967. - MK2 (200)
  6968. - MK2MM (201)
  6969. - MK2S (202)
  6970. - MK2SMM (203)
  6971. - MK2.5 (250)
  6972. - MK2.5MMU2 (20250)
  6973. - MK2.5S (252)
  6974. - MK2.5SMMU2S (20252)
  6975. - MK3 (300)
  6976. - MK3MMU2 (20300)
  6977. - MK3S (302)
  6978. - MK3SMMU2S (20302)
  6979. */
  6980. case 862: // M862: print checking
  6981. float nDummy;
  6982. uint8_t nCommand;
  6983. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  6984. switch((ClPrintChecking)nCommand)
  6985. {
  6986. case ClPrintChecking::_Nozzle: // ~ .1
  6987. uint16_t nDiameter;
  6988. if(code_seen('P'))
  6989. {
  6990. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  6991. nozzle_diameter_check(nDiameter);
  6992. }
  6993. else if(code_seen('Q'))
  6994. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  6995. break;
  6996. case ClPrintChecking::_Model: { // ~ .2
  6997. uint16_t type = nPrinterType(MMU2::mmu2.Enabled());
  6998. if(code_seen('P'))
  6999. {
  7000. uint16_t nPrinterModel;
  7001. nPrinterModel=(uint16_t)code_value_long();
  7002. // based on current state of MMU (active/stopped/connecting) perform a runtime update of the printer type
  7003. printer_model_check(nPrinterModel, type);
  7004. }
  7005. else if(code_seen('Q'))
  7006. SERIAL_PROTOCOLLN(type);
  7007. } break;
  7008. case ClPrintChecking::_Smodel: { // ~ .3
  7009. const char *type = sPrinterType(MMU2::mmu2.Enabled());
  7010. if(code_seen('P'))
  7011. {
  7012. printer_smodel_check(strchr_pointer, type);
  7013. }
  7014. else if(code_seen('Q'))
  7015. SERIAL_PROTOCOLLNRPGM(type);
  7016. } break;
  7017. case ClPrintChecking::_Version: // ~ .4
  7018. if(code_seen('P'))
  7019. fw_version_check(++strchr_pointer);
  7020. else if(code_seen('Q'))
  7021. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7022. break;
  7023. case ClPrintChecking::_Gcode: // ~ .5
  7024. if(code_seen('P'))
  7025. {
  7026. uint16_t nGcodeLevel;
  7027. nGcodeLevel=(uint16_t)code_value_long();
  7028. gcode_level_check(nGcodeLevel);
  7029. }
  7030. else if(code_seen('Q'))
  7031. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7032. break;
  7033. }
  7034. break;
  7035. #ifdef LIN_ADVANCE
  7036. /*!
  7037. ### 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>
  7038. 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.
  7039. #### Usage
  7040. M900 [ K | R | W | H | D]
  7041. #### Parameters
  7042. - `K` - Advance K factor
  7043. - `R` - Set ratio directly (overrides WH/D)
  7044. - `W` - Width
  7045. - `H` - Height
  7046. - `D` - Diameter Set ratio from WH/D
  7047. */
  7048. case 900:
  7049. gcode_M900();
  7050. break;
  7051. #endif
  7052. /*!
  7053. ### 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>
  7054. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7055. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7056. #### Usage
  7057. M907 [ X | Y | Z | E | B | S ]
  7058. #### Parameters
  7059. - `X` - X motor driver
  7060. - `Y` - Y motor driver
  7061. - `Z` - Z motor driver
  7062. - `E` - Extruder motor driver
  7063. - `B` - Second Extruder motor driver
  7064. - `S` - All motors
  7065. */
  7066. case 907:
  7067. {
  7068. #ifdef TMC2130
  7069. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7070. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7071. if(code_seen(axis_codes[i])){
  7072. if( i == E_AXIS && FarmOrUserECool() ){
  7073. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7074. SERIAL_ECHOLNPGM(", M907 E ignored");
  7075. continue;
  7076. }
  7077. long cur_mA = code_value_long();
  7078. uint8_t val = tmc2130_cur2val(cur_mA);
  7079. tmc2130_set_current_h(i, val);
  7080. tmc2130_set_current_r(i, val);
  7081. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7082. }
  7083. }
  7084. #else //TMC2130
  7085. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7086. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7087. if(code_seen('B')) st_current_set(4,code_value());
  7088. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7089. #endif
  7090. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7091. if(code_seen('X')) st_current_set(0, code_value());
  7092. #endif
  7093. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7094. if(code_seen('Z')) st_current_set(1, code_value());
  7095. #endif
  7096. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7097. if(code_seen('E')) st_current_set(2, code_value());
  7098. #endif
  7099. #endif //TMC2130
  7100. }
  7101. break;
  7102. /*!
  7103. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7104. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7105. #### Usage
  7106. M908 [ P | S ]
  7107. #### Parameters
  7108. - `P` - channel
  7109. - `S` - current
  7110. */
  7111. case 908:
  7112. {
  7113. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7114. uint8_t channel,current;
  7115. if(code_seen('P')) channel=code_value();
  7116. if(code_seen('S')) current=code_value();
  7117. digitalPotWrite(channel, current);
  7118. #endif
  7119. }
  7120. break;
  7121. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7122. /*!
  7123. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7124. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7125. */
  7126. case 910:
  7127. {
  7128. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7129. }
  7130. break;
  7131. /*!
  7132. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7133. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7134. #### Usage
  7135. M911 [ X | Y | Z | E ]
  7136. #### Parameters
  7137. - `X` - X stepper driver holding current value
  7138. - `Y` - Y stepper driver holding current value
  7139. - `Z` - Z stepper driver holding current value
  7140. - `E` - Extruder stepper driver holding current value
  7141. */
  7142. case 911:
  7143. {
  7144. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7145. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7146. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7147. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7148. }
  7149. break;
  7150. /*!
  7151. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7152. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7153. #### Usage
  7154. M912 [ X | Y | Z | E ]
  7155. #### Parameters
  7156. - `X` - X stepper driver running current value
  7157. - `Y` - Y stepper driver running current value
  7158. - `Z` - Z stepper driver running current value
  7159. - `E` - Extruder stepper driver running current value
  7160. */
  7161. case 912:
  7162. {
  7163. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7164. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7165. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7166. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7167. }
  7168. break;
  7169. /*!
  7170. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7171. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7172. Shows TMC2130 currents.
  7173. */
  7174. case 913:
  7175. {
  7176. tmc2130_print_currents();
  7177. }
  7178. break;
  7179. /*!
  7180. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7181. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7182. */
  7183. case 914:
  7184. {
  7185. tmc2130_mode = TMC2130_MODE_NORMAL;
  7186. update_mode_profile();
  7187. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7188. }
  7189. break;
  7190. /*!
  7191. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7192. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7193. */
  7194. case 915:
  7195. {
  7196. tmc2130_mode = TMC2130_MODE_SILENT;
  7197. update_mode_profile();
  7198. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7199. }
  7200. break;
  7201. /*!
  7202. ### 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>
  7203. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7204. #### Usage
  7205. M916 [ X | Y | Z | E ]
  7206. #### Parameters
  7207. - `X` - X stepper driver stallguard sensitivity threshold value
  7208. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7209. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7210. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7211. */
  7212. case 916:
  7213. {
  7214. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7215. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7216. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7217. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7218. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7219. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7220. }
  7221. break;
  7222. /*!
  7223. ### 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>
  7224. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7225. #### Usage
  7226. M917 [ X | Y | Z | E ]
  7227. #### Parameters
  7228. - `X` - X stepper driver PWM amplitude offset value
  7229. - `Y` - Y stepper driver PWM amplitude offset value
  7230. - `Z` - Z stepper driver PWM amplitude offset value
  7231. - `E` - Extruder stepper driver PWM amplitude offset value
  7232. */
  7233. case 917:
  7234. {
  7235. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7236. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7237. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7238. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7239. }
  7240. break;
  7241. /*!
  7242. ### 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>
  7243. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7244. #### Usage
  7245. M918 [ X | Y | Z | E ]
  7246. #### Parameters
  7247. - `X` - X stepper driver PWM amplitude gradient value
  7248. - `Y` - Y stepper driver PWM amplitude gradient value
  7249. - `Z` - Z stepper driver PWM amplitude gradient value
  7250. - `E` - Extruder stepper driver PWM amplitude gradient value
  7251. */
  7252. case 918:
  7253. {
  7254. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7255. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7256. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7257. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7258. }
  7259. break;
  7260. #endif //TMC2130_SERVICE_CODES_M910_M918
  7261. /*!
  7262. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7263. 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!
  7264. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7265. #### Usage
  7266. M350 [ X | Y | Z | E | B | S ]
  7267. #### Parameters
  7268. - `X` - X new resolution
  7269. - `Y` - Y new resolution
  7270. - `Z` - Z new resolution
  7271. - `E` - E new resolution
  7272. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7273. - `B` - Second extruder new resolution
  7274. - `S` - All axes new resolution
  7275. */
  7276. case 350:
  7277. {
  7278. #ifdef TMC2130
  7279. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7280. {
  7281. if(code_seen(axis_codes[i]))
  7282. {
  7283. uint16_t res_new = code_value();
  7284. #ifdef ALLOW_ALL_MRES
  7285. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7286. #else
  7287. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7288. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7289. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7290. #endif
  7291. if (res_valid)
  7292. {
  7293. st_synchronize();
  7294. uint16_t res = tmc2130_get_res(i);
  7295. tmc2130_set_res(i, res_new);
  7296. cs.axis_ustep_resolution[i] = res_new;
  7297. if (res_new > res)
  7298. {
  7299. uint16_t fac = (res_new / res);
  7300. cs.axis_steps_per_unit[i] *= fac;
  7301. position[i] *= fac;
  7302. }
  7303. else
  7304. {
  7305. uint16_t fac = (res / res_new);
  7306. cs.axis_steps_per_unit[i] /= fac;
  7307. position[i] /= fac;
  7308. }
  7309. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7310. if (i == E_AXIS)
  7311. fsensor.init();
  7312. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7313. }
  7314. }
  7315. }
  7316. reset_acceleration_rates();
  7317. #else //TMC2130
  7318. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7319. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7320. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7321. if(code_seen('B')) microstep_mode(4,code_value());
  7322. microstep_readings();
  7323. #endif
  7324. #endif //TMC2130
  7325. }
  7326. break;
  7327. /*!
  7328. ### 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>
  7329. Toggle MS1 MS2 pins directly.
  7330. #### Usage
  7331. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7332. #### Parameters
  7333. - `X` - Update X axis
  7334. - `Y` - Update Y axis
  7335. - `Z` - Update Z axis
  7336. - `E` - Update E axis
  7337. - `S` - which MSx pin to toggle
  7338. - `B` - new pin value
  7339. */
  7340. case 351:
  7341. {
  7342. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7343. if(code_seen('S')) switch((int)code_value())
  7344. {
  7345. case 1:
  7346. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7347. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7348. break;
  7349. case 2:
  7350. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7351. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7352. break;
  7353. }
  7354. microstep_readings();
  7355. #endif
  7356. }
  7357. break;
  7358. /*!
  7359. ### M701 - Load filament to extruder <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7360. Load filament into the active extruder.
  7361. #### Usage
  7362. M701 [ P | T | L | Z ]
  7363. #### Parameters
  7364. - `P` - n index of MMU slot (zero based, so 0-4 like T0 and T4)
  7365. - `T` - Alias of `P`. Used for compatibility with Marlin
  7366. - `L` - Extrude distance for insertion (positive value)(manual reload)
  7367. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_LOAD
  7368. */
  7369. case 701:
  7370. {
  7371. uint8_t mmuSlotIndex = 0xffU;
  7372. float fastLoadLength = FILAMENTCHANGE_FIRSTFEED; // Only used without MMU
  7373. float z_target = MIN_Z_FOR_LOAD;
  7374. if( MMU2::mmu2.Enabled() )
  7375. {
  7376. if( code_seen('P') || code_seen('T') ) {
  7377. mmuSlotIndex = code_value_uint8();
  7378. }
  7379. }
  7380. if (code_seen('L')) fastLoadLength = code_value();
  7381. // Z lift. For safety only allow positive values
  7382. if (code_seen('Z')) z_target = fabs(code_value());
  7383. // Raise the Z axis
  7384. float delta = raise_z(z_target);
  7385. // Load filament
  7386. gcode_M701(fastLoadLength, mmuSlotIndex);
  7387. // Restore Z axis
  7388. raise_z(-delta);
  7389. }
  7390. break;
  7391. /*!
  7392. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7393. #### Usage
  7394. M702 [ U | Z ]
  7395. #### Parameters
  7396. - `U` - Retract distance for removal (manual reload). Default value is 0.
  7397. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_UNLOAD.
  7398. */
  7399. case 702:
  7400. {
  7401. float z_target = MIN_Z_FOR_UNLOAD;
  7402. float unloadLength = FILAMENTCHANGE_FINALRETRACT;
  7403. if (code_seen('U')) unloadLength = code_value();
  7404. // For safety only allow positive values
  7405. if (code_seen('Z')) z_target = fabs(code_value());
  7406. // Raise the Z axis
  7407. float delta = raise_z(z_target);
  7408. // Unload filament
  7409. if (MMU2::mmu2.Enabled()) MMU2::mmu2.unload();
  7410. else unload_filament(unloadLength);
  7411. // Restore Z axis
  7412. raise_z(-delta);
  7413. }
  7414. break;
  7415. /*!
  7416. ### M704 - Load to MMU <a href="https://reprap.org/wiki/G-code#M704:_Load_to_MMU">M704: Load to MMU</a>
  7417. #### Usage
  7418. M704 [ P ]
  7419. #### Parameters
  7420. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7421. */
  7422. case 704:
  7423. {
  7424. gcodes_M704_M705_M706(704);
  7425. }
  7426. break;
  7427. /*!
  7428. ### M705 - Eject filament <a href="https://reprap.org/wiki/G-code#M705:_Eject_filament">M705: Eject filament</a>
  7429. #### Usage
  7430. M705 [ P ]
  7431. #### Parameters
  7432. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7433. */
  7434. case 705:
  7435. {
  7436. gcodes_M704_M705_M706(705);
  7437. }
  7438. break;
  7439. /*!
  7440. ### M706 - Cut filament <a href="https://reprap.org/wiki/G-code#M706:_Cut_filament">M706: Cut filament</a>
  7441. #### Usage
  7442. M706 [ P ]
  7443. #### Parameters
  7444. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7445. */
  7446. case 706:
  7447. {
  7448. gcodes_M704_M705_M706(706);
  7449. }
  7450. break;
  7451. /*!
  7452. ### M707 - Read from MMU register <a href="https://reprap.org/wiki/G-code#M707:_Read_from_MMU_register">M707: Read from MMU register</a>
  7453. #### Usage
  7454. M707 [ A ]
  7455. #### Parameters
  7456. - `A` - Address of register in hexidecimal.
  7457. #### Example
  7458. M707 A0x1b - Read a 8bit integer from register 0x1b and prints the result onto the serial line.
  7459. Does nothing if the A parameter is not present or if MMU is not enabled.
  7460. */
  7461. case 707: {
  7462. if ( MMU2::mmu2.Enabled() ) {
  7463. if( code_seen('A') ) {
  7464. MMU2::mmu2.ReadRegister(uint8_t(strtol(strchr_pointer+1, NULL, 16)));
  7465. }
  7466. }
  7467. } break;
  7468. /*!
  7469. ### M708 - Write to MMU register <a href="https://reprap.org/wiki/G-code#M708:_Write_to_MMU_register">M707: Write to MMU register</a>
  7470. #### Usage
  7471. M708 [ A | X ]
  7472. #### Parameters
  7473. - `A` - Address of register in hexidecimal.
  7474. - `X` - Data to write (16-bit integer). Default value 0.
  7475. #### Example
  7476. M708 A0x1b X05 - Write to register 0x1b the value 05.
  7477. Does nothing if A parameter is missing or if MMU is not enabled.
  7478. */
  7479. case 708: {
  7480. if ( MMU2::mmu2.Enabled() ){
  7481. uint8_t addr = 0;
  7482. if( code_seen('A') ) {
  7483. addr = uint8_t(strtol(strchr_pointer+1, NULL, 16));
  7484. }
  7485. uint16_t data = 0;
  7486. if( code_seen('X') ) {
  7487. data = code_value_short();
  7488. }
  7489. if(addr){
  7490. MMU2::mmu2.WriteRegister(addr, data);
  7491. }
  7492. }
  7493. } break;
  7494. /*!
  7495. ### M709 - MMU reset <a href="https://reprap.org/wiki/G-code#M709:_MMU_reset">M709: MMU reset</a>
  7496. The MK3S cannot not power off the MMU, for that reason the functionality is not supported.
  7497. #### Usage
  7498. M709 [ X ]
  7499. #### Parameters
  7500. - `X` - Reset MMU (0:soft reset | 1:hardware reset)
  7501. #### Example
  7502. M709 X0 - issue an X0 command via communication into the MMU (soft reset)
  7503. M709 X1 - toggle the MMU's reset pin (hardware reset)
  7504. */
  7505. case 709:
  7506. {
  7507. if (MMU2::mmu2.Enabled() && code_seen('X'))
  7508. {
  7509. switch (code_value_uint8())
  7510. {
  7511. case 0:
  7512. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  7513. break;
  7514. case 1:
  7515. MMU2::mmu2.Reset(MMU2::MMU2::ResetPin);
  7516. break;
  7517. default:
  7518. break;
  7519. }
  7520. }
  7521. }
  7522. break;
  7523. /*!
  7524. #### End of M-Commands
  7525. */
  7526. default:
  7527. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7528. }
  7529. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7530. mcode_in_progress = 0;
  7531. }
  7532. }
  7533. // end if(code_seen('M')) (end of M codes)
  7534. /*!
  7535. -----------------------------------------------------------------------------------------
  7536. # T Codes
  7537. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7538. #### For MMU_V2:
  7539. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7540. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7541. @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.
  7542. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7543. */
  7544. else if(code_seen('T')){
  7545. TCodes(strchr_pointer, code_value_uint8());
  7546. } // end if(code_seen('T')) (end of T codes)
  7547. /*!
  7548. #### End of T-Codes
  7549. */
  7550. /**
  7551. *---------------------------------------------------------------------------------
  7552. *# D codes
  7553. */
  7554. else if (code_seen('D')) // D codes (debug)
  7555. {
  7556. switch(code_value_short())
  7557. {
  7558. /*!
  7559. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7560. */
  7561. case -1:
  7562. dcode__1(); break;
  7563. #ifdef DEBUG_DCODES
  7564. /*!
  7565. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7566. #### Usage
  7567. D0 [ B ]
  7568. #### Parameters
  7569. - `B` - Bootloader
  7570. */
  7571. case 0:
  7572. dcode_0(); break;
  7573. /*!
  7574. *
  7575. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7576. D1
  7577. *
  7578. */
  7579. case 1:
  7580. dcode_1(); break;
  7581. #endif
  7582. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7583. /*!
  7584. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7585. This command can be used without any additional parameters. It will read the entire RAM.
  7586. #### Usage
  7587. D2 [ A | C | X ]
  7588. #### Parameters
  7589. - `A` - Address (x0000-x1fff)
  7590. - `C` - Count (1-8192)
  7591. - `X` - Data
  7592. #### Notes
  7593. - The hex address needs to be lowercase without the 0 before the x
  7594. - Count is decimal
  7595. - The hex data needs to be lowercase
  7596. */
  7597. case 2:
  7598. dcode_2(); break;
  7599. #endif //DEBUG_DCODES
  7600. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7601. /*!
  7602. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7603. This command can be used without any additional parameters. It will read the entire eeprom.
  7604. #### Usage
  7605. D3 [ A | C | X ]
  7606. #### Parameters
  7607. - `A` - Address (x0000-x0fff)
  7608. - `C` - Count (1-4096)
  7609. - `X` - Data (hex)
  7610. #### Notes
  7611. - The hex address needs to be lowercase without the 0 before the x
  7612. - Count is decimal
  7613. - The hex data needs to be lowercase
  7614. */
  7615. case 3:
  7616. dcode_3(); break;
  7617. #endif //DEBUG_DCODE3
  7618. #ifdef DEBUG_DCODES
  7619. /*!
  7620. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7621. To read the digital value of a pin you need only to define the pin number.
  7622. #### Usage
  7623. D4 [ P | F | V ]
  7624. #### Parameters
  7625. - `P` - Pin (0-255)
  7626. - `F` - Function in/out (0/1)
  7627. - `V` - Value (0/1)
  7628. */
  7629. case 4:
  7630. dcode_4(); break;
  7631. #endif //DEBUG_DCODES
  7632. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7633. /*!
  7634. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7635. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7636. #### Usage
  7637. D5 [ A | C | X | E ]
  7638. #### Parameters
  7639. - `A` - Address (x00000-x3ffff)
  7640. - `C` - Count (1-8192)
  7641. - `X` - Data (hex)
  7642. - `E` - Erase
  7643. #### Notes
  7644. - The hex address needs to be lowercase without the 0 before the x
  7645. - Count is decimal
  7646. - The hex data needs to be lowercase
  7647. */
  7648. case 5:
  7649. dcode_5(); break;
  7650. #endif //DEBUG_DCODE5
  7651. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7652. /*!
  7653. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7654. Reserved
  7655. */
  7656. case 6:
  7657. dcode_6(); break;
  7658. #endif
  7659. #ifdef DEBUG_DCODES
  7660. /*!
  7661. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7662. Reserved
  7663. */
  7664. case 7:
  7665. dcode_7(); break;
  7666. /*!
  7667. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7668. #### Usage
  7669. D8 [ ? | ! | P | Z ]
  7670. #### Parameters
  7671. - `?` - Read PINDA temperature shift values
  7672. - `!` - Reset PINDA temperature shift values to default
  7673. - `P` - Pinda temperature [C]
  7674. - `Z` - Z Offset [mm]
  7675. */
  7676. case 8:
  7677. dcode_8(); break;
  7678. /*!
  7679. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7680. #### Usage
  7681. D9 [ I | V ]
  7682. #### Parameters
  7683. - `I` - ADC channel index
  7684. - `0` - Heater 0 temperature
  7685. - `1` - Heater 1 temperature
  7686. - `2` - Bed temperature
  7687. - `3` - PINDA temperature
  7688. - `4` - PWR voltage
  7689. - `5` - Ambient temperature
  7690. - `6` - BED voltage
  7691. - `V` Value to be written as simulated
  7692. */
  7693. case 9:
  7694. dcode_9(); break;
  7695. /*!
  7696. ### 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>
  7697. */
  7698. case 10:
  7699. dcode_10(); break;
  7700. /*!
  7701. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7702. Writes the current time in the log file.
  7703. */
  7704. #endif //DEBUG_DCODES
  7705. #ifdef XFLASH_DUMP
  7706. /*!
  7707. ### 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>
  7708. Generate a crash dump for later retrival.
  7709. #### Usage
  7710. D20 [E]
  7711. ### Parameters
  7712. - `E` - Perform an emergency crash dump (resets the printer).
  7713. ### Notes
  7714. - A crash dump can be later recovered with D21, or cleared with D22.
  7715. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7716. is completed.
  7717. */
  7718. case 20: {
  7719. dcode_20();
  7720. break;
  7721. };
  7722. /*!
  7723. ### 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>
  7724. Output the complete crash dump (if present) to the serial.
  7725. #### Usage
  7726. D21
  7727. ### Notes
  7728. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7729. */
  7730. case 21: {
  7731. dcode_21();
  7732. break;
  7733. };
  7734. /*!
  7735. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7736. Clear an existing internal crash dump.
  7737. #### Usage
  7738. D22
  7739. */
  7740. case 22: {
  7741. dcode_22();
  7742. break;
  7743. };
  7744. #endif //XFLASH_DUMP
  7745. #ifdef EMERGENCY_SERIAL_DUMP
  7746. /*!
  7747. ### 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>
  7748. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7749. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7750. #### Usage
  7751. D23 [E] [R]
  7752. #### Parameters
  7753. - `E` - Perform an emergency crash dump (resets the printer).
  7754. - `R` - Disable online dumps.
  7755. */
  7756. case 23: {
  7757. dcode_23();
  7758. break;
  7759. };
  7760. #endif
  7761. #ifdef TEMP_MODEL_DEBUG
  7762. /*!
  7763. ## D70 - Enable low-level temperature model logging for offline simulation
  7764. #### Usage
  7765. D70 [ S ]
  7766. #### Parameters
  7767. - `S` - Enable 0-1 (default 0)
  7768. */
  7769. case 70: {
  7770. if(code_seen('S'))
  7771. temp_model_log_enable(code_value_short());
  7772. break;
  7773. }
  7774. #endif
  7775. #ifdef HEATBED_ANALYSIS
  7776. /*!
  7777. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7778. This command will log data to SD card file "mesh.txt".
  7779. #### Usage
  7780. D80 [ E | F | G | H | I | J ]
  7781. #### Parameters
  7782. - `E` - Dimension X (default 40)
  7783. - `F` - Dimention Y (default 40)
  7784. - `G` - Points X (default 40)
  7785. - `H` - Points Y (default 40)
  7786. - `I` - Offset X (default 74)
  7787. - `J` - Offset Y (default 34)
  7788. */
  7789. case 80:
  7790. dcode_80(); break;
  7791. /*!
  7792. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7793. This command will log data to SD card file "wldsd.txt".
  7794. #### Usage
  7795. D81 [ E | F | G | H | I | J ]
  7796. #### Parameters
  7797. - `E` - Dimension X (default 40)
  7798. - `F` - Dimention Y (default 40)
  7799. - `G` - Points X (default 40)
  7800. - `H` - Points Y (default 40)
  7801. - `I` - Offset X (default 74)
  7802. - `J` - Offset Y (default 34)
  7803. */
  7804. case 81:
  7805. dcode_81(); break;
  7806. #endif //HEATBED_ANALYSIS
  7807. #ifdef DEBUG_DCODES
  7808. /*!
  7809. ### 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>
  7810. */
  7811. case 106:
  7812. dcode_106(); break;
  7813. #ifdef TMC2130
  7814. /*!
  7815. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7816. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7817. #### Usage
  7818. D2130 [ Axis | Command | Subcommand | Value ]
  7819. #### Parameters
  7820. - Axis
  7821. - `X` - X stepper driver
  7822. - `Y` - Y stepper driver
  7823. - `Z` - Z stepper driver
  7824. - `E` - Extruder stepper driver
  7825. - Commands
  7826. - `0` - Current off
  7827. - `1` - Current on
  7828. - `+` - Single step
  7829. - `-` - Single step oposite direction
  7830. - `NNN` - Value sereval steps
  7831. - `?` - Read register
  7832. - Subcommands for read register
  7833. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7834. - `step` - Step
  7835. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7836. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7837. - `wave` - Microstep linearity compensation curve
  7838. - `!` - Set register
  7839. - Subcommands for set register
  7840. - `mres` - Micro step resolution
  7841. - `step` - Step
  7842. - `wave` - Microstep linearity compensation curve
  7843. - Values for set register
  7844. - `0, 180 --> 250` - Off
  7845. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7846. - `@` - Home calibrate axis
  7847. Examples:
  7848. D2130E?wave
  7849. Print extruder microstep linearity compensation curve
  7850. D2130E!wave0
  7851. Disable extruder linearity compensation curve, (sine curve is used)
  7852. D2130E!wave220
  7853. (sin(x))^1.1 extruder microstep compensation curve used
  7854. Notes:
  7855. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7856. *
  7857. */
  7858. case 2130:
  7859. dcode_2130(); break;
  7860. #endif //TMC2130
  7861. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7862. /*!
  7863. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7864. #### Usage
  7865. D9125 [ ? | ! | R | X | Y | L ]
  7866. #### Parameters
  7867. - `?` - Print values
  7868. - `!` - Print values
  7869. - `R` - Resolution. Not active in code
  7870. - `X` - X values
  7871. - `Y` - Y values
  7872. - `L` - Activate filament sensor log
  7873. */
  7874. case 9125:
  7875. dcode_9125(); break;
  7876. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7877. #endif //DEBUG_DCODES
  7878. default:
  7879. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7880. }
  7881. }
  7882. else
  7883. {
  7884. SERIAL_ECHO_START;
  7885. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7886. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7887. SERIAL_ECHOLNPGM("\"(2)");
  7888. }
  7889. KEEPALIVE_STATE(NOT_BUSY);
  7890. ClearToSend();
  7891. }
  7892. /*!
  7893. #### End of D-Codes
  7894. */
  7895. /** @defgroup GCodes G-Code List
  7896. */
  7897. // ---------------------------------------------------
  7898. void FlushSerialRequestResend()
  7899. {
  7900. //char cmdbuffer[bufindr][100]="Resend:";
  7901. MYSERIAL.flush();
  7902. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7903. }
  7904. // Confirm the execution of a command, if sent from a serial line.
  7905. // Execution of a command from a SD card will not be confirmed.
  7906. void ClearToSend()
  7907. {
  7908. previous_millis_cmd.start();
  7909. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7910. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7911. }
  7912. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7913. void update_currents() {
  7914. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7915. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7916. float tmp_motor[3];
  7917. //SERIAL_ECHOLNPGM("Currents updated: ");
  7918. if (destination[Z_AXIS] < Z_SILENT) {
  7919. //SERIAL_ECHOLNPGM("LOW");
  7920. for (uint8_t i = 0; i < 3; i++) {
  7921. st_current_set(i, current_low[i]);
  7922. /*MYSERIAL.print(int(i));
  7923. SERIAL_ECHOPGM(": ");
  7924. MYSERIAL.println(current_low[i]);*/
  7925. }
  7926. }
  7927. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7928. //SERIAL_ECHOLNPGM("HIGH");
  7929. for (uint8_t i = 0; i < 3; i++) {
  7930. st_current_set(i, current_high[i]);
  7931. /*MYSERIAL.print(int(i));
  7932. SERIAL_ECHOPGM(": ");
  7933. MYSERIAL.println(current_high[i]);*/
  7934. }
  7935. }
  7936. else {
  7937. for (uint8_t i = 0; i < 3; i++) {
  7938. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7939. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7940. st_current_set(i, tmp_motor[i]);
  7941. /*MYSERIAL.print(int(i));
  7942. SERIAL_ECHOPGM(": ");
  7943. MYSERIAL.println(tmp_motor[i]);*/
  7944. }
  7945. }
  7946. }
  7947. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7948. void get_coordinates() {
  7949. bool seen[4]={false,false,false,false};
  7950. for(int8_t i=0; i < NUM_AXIS; i++) {
  7951. if(code_seen(axis_codes[i]))
  7952. {
  7953. bool relative = axis_relative_modes & (1 << i);
  7954. destination[i] = code_value();
  7955. if (i == E_AXIS) {
  7956. float emult = extruder_multiplier[active_extruder];
  7957. if (emult != 1.) {
  7958. if (! relative) {
  7959. destination[i] -= current_position[i];
  7960. relative = true;
  7961. }
  7962. destination[i] *= emult;
  7963. }
  7964. }
  7965. if (relative)
  7966. destination[i] += current_position[i];
  7967. seen[i]=true;
  7968. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7969. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7970. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7971. }
  7972. else destination[i] = current_position[i]; //Are these else lines really needed?
  7973. }
  7974. if(code_seen('F')) {
  7975. next_feedrate = code_value();
  7976. if(next_feedrate > 0.0) feedrate = next_feedrate;
  7977. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  7978. {
  7979. // float e_max_speed =
  7980. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  7981. }
  7982. }
  7983. }
  7984. void clamp_to_software_endstops(float target[3])
  7985. {
  7986. #ifdef DEBUG_DISABLE_SWLIMITS
  7987. return;
  7988. #endif //DEBUG_DISABLE_SWLIMITS
  7989. world2machine_clamp(target[0], target[1]);
  7990. // Clamp the Z coordinate.
  7991. if (min_software_endstops) {
  7992. float negative_z_offset = 0;
  7993. #ifdef ENABLE_AUTO_BED_LEVELING
  7994. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  7995. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  7996. #endif
  7997. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  7998. }
  7999. if (max_software_endstops) {
  8000. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8001. }
  8002. }
  8003. uint16_t restore_interrupted_gcode() {
  8004. // When recovering from a previous print move, restore the originally
  8005. // calculated start position on the first USB/SD command. This accounts
  8006. // properly for relative moves
  8007. if (
  8008. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  8009. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  8010. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  8011. )
  8012. ) {
  8013. memcpy(current_position, saved_start_position, sizeof(current_position));
  8014. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  8015. return saved_segment_idx;
  8016. }
  8017. else
  8018. return 1; //begin with the first segment
  8019. }
  8020. #ifdef MESH_BED_LEVELING
  8021. 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) {
  8022. float dx = x - current_position[X_AXIS];
  8023. float dy = y - current_position[Y_AXIS];
  8024. uint16_t n_segments = 0;
  8025. if (mbl.active) {
  8026. float len = fabs(dx) + fabs(dy);
  8027. if (len > 0)
  8028. // Split to 3cm segments or shorter.
  8029. n_segments = uint16_t(ceil(len / 30.f));
  8030. }
  8031. if (n_segments > 1 && start_segment_idx) {
  8032. float dz = z - current_position[Z_AXIS];
  8033. float de = e - current_position[E_AXIS];
  8034. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  8035. float t = float(i) / float(n_segments);
  8036. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8037. current_position[Y_AXIS] + t * dy,
  8038. current_position[Z_AXIS] + t * dz,
  8039. current_position[E_AXIS] + t * de,
  8040. feed_rate, extruder, current_position, i);
  8041. if (planner_aborted)
  8042. return;
  8043. }
  8044. }
  8045. // The rest of the path.
  8046. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  8047. }
  8048. #endif // MESH_BED_LEVELING
  8049. void prepare_move(uint16_t start_segment_idx)
  8050. {
  8051. clamp_to_software_endstops(destination);
  8052. previous_millis_cmd.start();
  8053. // Do not use feedmultiply for E or Z only moves
  8054. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8055. plan_buffer_line_destinationXYZE(feedrate/60);
  8056. }
  8057. else {
  8058. #ifdef MESH_BED_LEVELING
  8059. 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);
  8060. #else
  8061. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8062. #endif
  8063. }
  8064. set_current_to_destination();
  8065. }
  8066. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8067. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8068. // Trace the arc
  8069. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8070. // As far as the parser is concerned, the position is now == target. In reality the
  8071. // motion control system might still be processing the action and the real tool position
  8072. // in any intermediate location.
  8073. set_current_to_destination();
  8074. previous_millis_cmd.start();
  8075. }
  8076. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8077. #if defined(FAN_PIN)
  8078. #if CONTROLLERFAN_PIN == FAN_PIN
  8079. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8080. #endif
  8081. #endif
  8082. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8083. unsigned long lastMotorCheck = 0;
  8084. void controllerFan()
  8085. {
  8086. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8087. {
  8088. lastMotorCheck = _millis();
  8089. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8090. #if EXTRUDERS > 2
  8091. || !READ(E2_ENABLE_PIN)
  8092. #endif
  8093. #if EXTRUDER > 1
  8094. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8095. || !READ(X2_ENABLE_PIN)
  8096. #endif
  8097. || !READ(E1_ENABLE_PIN)
  8098. #endif
  8099. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8100. {
  8101. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8102. }
  8103. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8104. {
  8105. digitalWrite(CONTROLLERFAN_PIN, 0);
  8106. analogWrite(CONTROLLERFAN_PIN, 0);
  8107. }
  8108. else
  8109. {
  8110. // allows digital or PWM fan output to be used (see M42 handling)
  8111. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8112. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8113. }
  8114. }
  8115. }
  8116. #endif
  8117. #ifdef SAFETYTIMER
  8118. /**
  8119. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8120. *
  8121. * Full screen blocking notification message is shown after heater turning off.
  8122. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8123. * damage print.
  8124. *
  8125. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8126. */
  8127. static void handleSafetyTimer()
  8128. {
  8129. #if (EXTRUDERS > 1)
  8130. #error Implemented only for one extruder.
  8131. #endif //(EXTRUDERS > 1)
  8132. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8133. {
  8134. safetyTimer.stop();
  8135. }
  8136. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8137. {
  8138. safetyTimer.start();
  8139. }
  8140. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8141. {
  8142. setTargetBed(0);
  8143. setAllTargetHotends(0);
  8144. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8145. }
  8146. }
  8147. #endif //SAFETYTIMER
  8148. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8149. {
  8150. #ifdef FILAMENT_SENSOR
  8151. if (fsensor.update()) {
  8152. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8153. }
  8154. #endif
  8155. #ifdef SAFETYTIMER
  8156. handleSafetyTimer();
  8157. #endif //SAFETYTIMER
  8158. #if defined(KILL_PIN) && KILL_PIN > -1
  8159. static int killCount = 0; // make the inactivity button a bit less responsive
  8160. const int KILL_DELAY = 10000;
  8161. #endif
  8162. if(buflen < (BUFSIZE-1)){
  8163. get_command();
  8164. }
  8165. if(previous_millis_cmd.expired(max_inactive_time))
  8166. if(max_inactive_time)
  8167. kill(_n("Inactivity Shutdown"), 4);
  8168. if(stepper_inactive_time) {
  8169. if(previous_millis_cmd.expired(stepper_inactive_time))
  8170. {
  8171. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8172. disable_x();
  8173. disable_y();
  8174. disable_z();
  8175. disable_e0();
  8176. disable_e1();
  8177. disable_e2();
  8178. }
  8179. }
  8180. }
  8181. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8182. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8183. {
  8184. chdkActive = false;
  8185. WRITE(CHDK, LOW);
  8186. }
  8187. #endif
  8188. #if defined(KILL_PIN) && KILL_PIN > -1
  8189. // Check if the kill button was pressed and wait just in case it was an accidental
  8190. // key kill key press
  8191. // -------------------------------------------------------------------------------
  8192. if( 0 == READ(KILL_PIN) )
  8193. {
  8194. killCount++;
  8195. }
  8196. else if (killCount > 0)
  8197. {
  8198. killCount--;
  8199. }
  8200. // Exceeded threshold and we can confirm that it was not accidental
  8201. // KILL the machine
  8202. // ----------------------------------------------------------------
  8203. if ( killCount >= KILL_DELAY)
  8204. {
  8205. kill(NULL, 5);
  8206. }
  8207. #endif
  8208. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8209. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8210. #endif
  8211. #ifdef EXTRUDER_RUNOUT_PREVENT
  8212. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8213. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8214. {
  8215. bool oldstatus=READ(E0_ENABLE_PIN);
  8216. enable_e0();
  8217. float oldepos=current_position[E_AXIS];
  8218. float oldedes=destination[E_AXIS];
  8219. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8220. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8221. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8222. current_position[E_AXIS]=oldepos;
  8223. destination[E_AXIS]=oldedes;
  8224. plan_set_e_position(oldepos);
  8225. previous_millis_cmd.start();
  8226. st_synchronize();
  8227. WRITE(E0_ENABLE_PIN,oldstatus);
  8228. }
  8229. #endif
  8230. check_axes_activity();
  8231. MMU2::mmu2.mmu_loop();
  8232. // handle longpress
  8233. if(lcd_longpress_trigger)
  8234. {
  8235. // long press is not possible in modal mode, wait until ready
  8236. if (lcd_longpress_func && lcd_update_enabled)
  8237. {
  8238. lcd_longpress_func();
  8239. lcd_longpress_trigger = 0;
  8240. }
  8241. }
  8242. #if defined(AUTO_REPORT)
  8243. host_autoreport();
  8244. #endif //AUTO_REPORT
  8245. host_keepalive();
  8246. }
  8247. void kill(const char *full_screen_message, unsigned char id)
  8248. {
  8249. printf_P(_N("KILL: %d\n"), id);
  8250. //return;
  8251. cli(); // Stop interrupts
  8252. disable_heater();
  8253. disable_x();
  8254. // SERIAL_ECHOLNPGM("kill - disable Y");
  8255. disable_y();
  8256. poweroff_z();
  8257. disable_e0();
  8258. disable_e1();
  8259. disable_e2();
  8260. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8261. pinMode(PS_ON_PIN,INPUT);
  8262. #endif
  8263. SERIAL_ERROR_START;
  8264. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8265. if (full_screen_message != NULL) {
  8266. SERIAL_ERRORLNRPGM(full_screen_message);
  8267. lcd_display_message_fullscreen_P(full_screen_message);
  8268. } else {
  8269. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8270. }
  8271. // FMC small patch to update the LCD before ending
  8272. sei(); // enable interrupts
  8273. for ( int i=5; i--; lcd_update(0))
  8274. {
  8275. _delay(200);
  8276. }
  8277. cli(); // disable interrupts
  8278. suicide();
  8279. while(1)
  8280. {
  8281. #ifdef WATCHDOG
  8282. wdt_reset();
  8283. #endif //WATCHDOG
  8284. /* Intentionally left empty */
  8285. } // Wait for reset
  8286. }
  8287. void UnconditionalStop()
  8288. {
  8289. CRITICAL_SECTION_START;
  8290. // Disable all heaters and unroll the temperature wait loop stack
  8291. disable_heater();
  8292. cancel_heatup = true;
  8293. heating_status = HeatingStatus::NO_HEATING;
  8294. // Clear any saved printing state
  8295. cancel_saved_printing();
  8296. // Abort the planner
  8297. planner_abort_hard();
  8298. // Reset the queue
  8299. cmdqueue_reset();
  8300. cmdqueue_serial_disabled = false;
  8301. // Reset the sd status
  8302. card.sdprinting = false;
  8303. card.closefile();
  8304. st_reset_timer();
  8305. CRITICAL_SECTION_END;
  8306. }
  8307. // Emergency stop used by overtemp functions which allows recovery
  8308. // WARNING: This function is called *continuously* during a thermal failure.
  8309. //
  8310. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8311. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8312. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8313. // kept in busy state and *must* be recovered from the LCD.
  8314. void ThermalStop(bool allow_pause)
  8315. {
  8316. if(Stopped == false) {
  8317. Stopped = true;
  8318. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8319. if (!isPrintPaused) {
  8320. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8321. // we cannot make a distinction for the host here, the pause must be instantaneous
  8322. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8323. // disable heaters and save the original temperatures to saved_*, which will get
  8324. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8325. // original values after the pause handler is called.
  8326. float bed_temp = saved_bed_temperature;
  8327. float ext_temp = saved_extruder_temperature;
  8328. int fan_speed = saved_fan_speed;
  8329. lcd_pause_print();
  8330. saved_bed_temperature = bed_temp;
  8331. saved_extruder_temperature = ext_temp;
  8332. saved_fan_speed = fan_speed;
  8333. }
  8334. } else {
  8335. // We got a hard thermal error and/or there is no print going on. Just stop.
  8336. lcd_print_stop();
  8337. // Also prevent further menu entry
  8338. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8339. }
  8340. // Report the status on the serial, switch to a busy state
  8341. SERIAL_ERROR_START;
  8342. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8343. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8344. // higher-priority alert status message)
  8345. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8346. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8347. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8348. WRITE(BEEPER, HIGH);
  8349. }
  8350. // Return to the status screen to stop any pending menu action which could have been
  8351. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8352. // error is immediately shown.
  8353. if (menu_menu != lcd_status_screen)
  8354. lcd_return_to_status();
  8355. }
  8356. bool IsStopped() { return Stopped; };
  8357. void finishAndDisableSteppers()
  8358. {
  8359. st_synchronize();
  8360. disable_x();
  8361. disable_y();
  8362. disable_z();
  8363. disable_e0();
  8364. disable_e1();
  8365. disable_e2();
  8366. #ifndef LA_NOCOMPAT
  8367. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8368. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8369. // state for the next print.
  8370. la10c_reset();
  8371. #endif
  8372. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8373. print_time_remaining_init();
  8374. }
  8375. #ifdef FAST_PWM_FAN
  8376. void setPwmFrequency(uint8_t pin, int val)
  8377. {
  8378. val &= 0x07;
  8379. switch(digitalPinToTimer(pin))
  8380. {
  8381. #if defined(TCCR0A)
  8382. case TIMER0A:
  8383. case TIMER0B:
  8384. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8385. // TCCR0B |= val;
  8386. break;
  8387. #endif
  8388. #if defined(TCCR1A)
  8389. case TIMER1A:
  8390. case TIMER1B:
  8391. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8392. // TCCR1B |= val;
  8393. break;
  8394. #endif
  8395. #if defined(TCCR2)
  8396. case TIMER2:
  8397. case TIMER2:
  8398. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8399. TCCR2 |= val;
  8400. break;
  8401. #endif
  8402. #if defined(TCCR2A)
  8403. case TIMER2A:
  8404. case TIMER2B:
  8405. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8406. TCCR2B |= val;
  8407. break;
  8408. #endif
  8409. #if defined(TCCR3A)
  8410. case TIMER3A:
  8411. case TIMER3B:
  8412. case TIMER3C:
  8413. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8414. TCCR3B |= val;
  8415. break;
  8416. #endif
  8417. #if defined(TCCR4A)
  8418. case TIMER4A:
  8419. case TIMER4B:
  8420. case TIMER4C:
  8421. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8422. TCCR4B |= val;
  8423. break;
  8424. #endif
  8425. #if defined(TCCR5A)
  8426. case TIMER5A:
  8427. case TIMER5B:
  8428. case TIMER5C:
  8429. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8430. TCCR5B |= val;
  8431. break;
  8432. #endif
  8433. }
  8434. }
  8435. #endif //FAST_PWM_FAN
  8436. //! @brief Get and validate extruder number
  8437. //!
  8438. //! If it is not specified, active_extruder is returned in parameter extruder.
  8439. //! @param [in] code M code number
  8440. //! @param [out] extruder
  8441. //! @return error
  8442. //! @retval true Invalid extruder specified in T code
  8443. //! @retval false Valid extruder specified in T code, or not specifiead
  8444. bool setTargetedHotend(int code, uint8_t &extruder)
  8445. {
  8446. extruder = active_extruder;
  8447. if(code_seen('T')) {
  8448. extruder = code_value_uint8();
  8449. if(extruder >= EXTRUDERS) {
  8450. SERIAL_ECHO_START;
  8451. serialprintPGM(PSTR("M"));
  8452. SERIAL_ECHO(code);
  8453. SERIAL_ECHOPGM(" Invalid extruder ");
  8454. SERIAL_PROTOCOLLN((int)extruder);
  8455. return true;
  8456. }
  8457. }
  8458. return false;
  8459. }
  8460. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) { //_total_filament_used unit: mm/100; print time in s
  8461. uint32_t _previous_filament = eeprom_init_default_dword((uint32_t *)EEPROM_FILAMENTUSED, 0); //_previous_filament unit: cm
  8462. uint32_t _previous_time = eeprom_init_default_dword((uint32_t *)EEPROM_TOTALTIME, 0); //_previous_time unit: min
  8463. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time / 60)); // EEPROM_TOTALTIME unit: min
  8464. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8465. total_filament_used = 0;
  8466. if (MMU2::mmu2.Enabled()) {
  8467. eeprom_add_dword((uint32_t *)EEPROM_TOTAL_TOOLCHANGE_COUNT, MMU2::mmu2.ToolChangeCounter());
  8468. // @@TODO why were EEPROM_MMU_FAIL_TOT and EEPROM_MMU_LOAD_FAIL_TOT behaving differently - i.e. updated with every change?
  8469. MMU2::mmu2.ClearToolChangeCounter();
  8470. MMU2::mmu2.ClearTMCFailures(); // not stored into EEPROM
  8471. }
  8472. }
  8473. float calculate_extruder_multiplier(float diameter) {
  8474. float out = 1.f;
  8475. if (cs.volumetric_enabled && diameter > 0.f) {
  8476. float area = M_PI * diameter * diameter * 0.25;
  8477. out = 1.f / area;
  8478. }
  8479. if (extrudemultiply != 100)
  8480. out *= float(extrudemultiply) * 0.01f;
  8481. return out;
  8482. }
  8483. void calculate_extruder_multipliers() {
  8484. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8485. #if EXTRUDERS > 1
  8486. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8487. #if EXTRUDERS > 2
  8488. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8489. #endif
  8490. #endif
  8491. }
  8492. void delay_keep_alive(unsigned int ms)
  8493. {
  8494. for (;;) {
  8495. manage_heater();
  8496. // Manage inactivity, but don't disable steppers on timeout.
  8497. manage_inactivity(true);
  8498. lcd_update(0);
  8499. if (ms == 0)
  8500. break;
  8501. else if (ms >= 50) {
  8502. _delay(50);
  8503. ms -= 50;
  8504. } else {
  8505. _delay(ms);
  8506. ms = 0;
  8507. }
  8508. }
  8509. }
  8510. static void wait_for_heater(long codenum, uint8_t extruder) {
  8511. if (!degTargetHotend(extruder))
  8512. return;
  8513. #ifdef TEMP_RESIDENCY_TIME
  8514. long residencyStart;
  8515. residencyStart = -1;
  8516. /* continue to loop until we have reached the target temp
  8517. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8518. cancel_heatup = false;
  8519. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8520. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8521. #else
  8522. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8523. #endif //TEMP_RESIDENCY_TIME
  8524. if ((_millis() - codenum) > 1000UL)
  8525. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8526. if (!farm_mode) {
  8527. SERIAL_PROTOCOLPGM("T:");
  8528. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8529. SERIAL_PROTOCOLPGM(" E:");
  8530. SERIAL_PROTOCOL((int)extruder);
  8531. #ifdef TEMP_RESIDENCY_TIME
  8532. SERIAL_PROTOCOLPGM(" W:");
  8533. if (residencyStart > -1)
  8534. {
  8535. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8536. SERIAL_PROTOCOLLN(codenum);
  8537. }
  8538. else
  8539. {
  8540. SERIAL_PROTOCOLLN('?');
  8541. }
  8542. }
  8543. #else
  8544. SERIAL_PROTOCOLLN();
  8545. #endif
  8546. codenum = _millis();
  8547. }
  8548. manage_heater();
  8549. manage_inactivity(true); //do not disable steppers
  8550. lcd_update(0);
  8551. #ifdef TEMP_RESIDENCY_TIME
  8552. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8553. or when current temp falls outside the hysteresis after target temp was reached */
  8554. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8555. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8556. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8557. {
  8558. residencyStart = _millis();
  8559. }
  8560. #endif //TEMP_RESIDENCY_TIME
  8561. }
  8562. }
  8563. void check_babystep()
  8564. {
  8565. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8566. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8567. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8568. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8569. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8570. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8571. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8572. babystep_z);
  8573. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8574. lcd_update_enable(true);
  8575. }
  8576. }
  8577. #ifdef HEATBED_ANALYSIS
  8578. void d_setup()
  8579. {
  8580. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8581. pinMode(D_DATA, INPUT_PULLUP);
  8582. pinMode(D_REQUIRE, OUTPUT);
  8583. digitalWrite(D_REQUIRE, HIGH);
  8584. }
  8585. float d_ReadData()
  8586. {
  8587. int digit[13];
  8588. String mergeOutput;
  8589. float output;
  8590. digitalWrite(D_REQUIRE, HIGH);
  8591. for (int i = 0; i<13; i++)
  8592. {
  8593. for (int j = 0; j < 4; j++)
  8594. {
  8595. while (digitalRead(D_DATACLOCK) == LOW) {}
  8596. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8597. bitWrite(digit[i], j, digitalRead(D_DATA));
  8598. }
  8599. }
  8600. digitalWrite(D_REQUIRE, LOW);
  8601. mergeOutput = "";
  8602. output = 0;
  8603. for (int r = 5; r <= 10; r++) //Merge digits
  8604. {
  8605. mergeOutput += digit[r];
  8606. }
  8607. output = mergeOutput.toFloat();
  8608. if (digit[4] == 8) //Handle sign
  8609. {
  8610. output *= -1;
  8611. }
  8612. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8613. {
  8614. output /= 10;
  8615. }
  8616. return output;
  8617. }
  8618. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8619. int t1 = 0;
  8620. int t_delay = 0;
  8621. int digit[13];
  8622. int m;
  8623. char str[3];
  8624. //String mergeOutput;
  8625. char mergeOutput[15];
  8626. float output;
  8627. int mesh_point = 0; //index number of calibration point
  8628. 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
  8629. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8630. float mesh_home_z_search = 4;
  8631. float measure_z_height = 0.2f;
  8632. float row[x_points_num];
  8633. int ix = 0;
  8634. int iy = 0;
  8635. const char* filename_wldsd = "mesh.txt";
  8636. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8637. char numb_wldsd[8]; // (" -A.BCD" + null)
  8638. #ifdef MICROMETER_LOGGING
  8639. d_setup();
  8640. #endif //MICROMETER_LOGGING
  8641. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8642. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8643. unsigned int custom_message_type_old = custom_message_type;
  8644. unsigned int custom_message_state_old = custom_message_state;
  8645. custom_message_type = CustomMsg::MeshBedLeveling;
  8646. custom_message_state = (x_points_num * y_points_num) + 10;
  8647. lcd_update(1);
  8648. //mbl.reset();
  8649. babystep_undo();
  8650. card.openFile(filename_wldsd, false);
  8651. /*destination[Z_AXIS] = mesh_home_z_search;
  8652. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8653. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8654. for(int8_t i=0; i < NUM_AXIS; i++) {
  8655. current_position[i] = destination[i];
  8656. }
  8657. st_synchronize();
  8658. */
  8659. destination[Z_AXIS] = measure_z_height;
  8660. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8661. for(int8_t i=0; i < NUM_AXIS; i++) {
  8662. current_position[i] = destination[i];
  8663. }
  8664. st_synchronize();
  8665. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8666. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8667. SERIAL_PROTOCOL(x_points_num);
  8668. SERIAL_PROTOCOLPGM(",");
  8669. SERIAL_PROTOCOL(y_points_num);
  8670. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8671. SERIAL_PROTOCOL(mesh_home_z_search);
  8672. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8673. SERIAL_PROTOCOL(x_dimension);
  8674. SERIAL_PROTOCOLPGM(",");
  8675. SERIAL_PROTOCOL(y_dimension);
  8676. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8677. while (mesh_point != x_points_num * y_points_num) {
  8678. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8679. iy = mesh_point / x_points_num;
  8680. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8681. float z0 = 0.f;
  8682. /*destination[Z_AXIS] = mesh_home_z_search;
  8683. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8684. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8685. for(int8_t i=0; i < NUM_AXIS; i++) {
  8686. current_position[i] = destination[i];
  8687. }
  8688. st_synchronize();*/
  8689. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8690. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8691. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8692. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8693. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8694. set_current_to_destination();
  8695. st_synchronize();
  8696. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8697. delay_keep_alive(1000);
  8698. #ifdef MICROMETER_LOGGING
  8699. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8700. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8701. //strcat(data_wldsd, numb_wldsd);
  8702. //MYSERIAL.println(data_wldsd);
  8703. //delay(1000);
  8704. //delay(3000);
  8705. //t1 = millis();
  8706. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8707. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8708. memset(digit, 0, sizeof(digit));
  8709. //cli();
  8710. digitalWrite(D_REQUIRE, LOW);
  8711. for (int i = 0; i<13; i++)
  8712. {
  8713. //t1 = millis();
  8714. for (int j = 0; j < 4; j++)
  8715. {
  8716. while (digitalRead(D_DATACLOCK) == LOW) {}
  8717. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8718. //printf_P(PSTR("Done %d\n"), j);
  8719. bitWrite(digit[i], j, digitalRead(D_DATA));
  8720. }
  8721. //t_delay = (millis() - t1);
  8722. //SERIAL_PROTOCOLPGM(" ");
  8723. //SERIAL_PROTOCOL_F(t_delay, 5);
  8724. //SERIAL_PROTOCOLPGM(" ");
  8725. }
  8726. //sei();
  8727. digitalWrite(D_REQUIRE, HIGH);
  8728. mergeOutput[0] = '\0';
  8729. output = 0;
  8730. for (int r = 5; r <= 10; r++) //Merge digits
  8731. {
  8732. sprintf(str, "%d", digit[r]);
  8733. strcat(mergeOutput, str);
  8734. }
  8735. output = atof(mergeOutput);
  8736. if (digit[4] == 8) //Handle sign
  8737. {
  8738. output *= -1;
  8739. }
  8740. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8741. {
  8742. output *= 0.1;
  8743. }
  8744. //output = d_ReadData();
  8745. //row[ix] = current_position[Z_AXIS];
  8746. //row[ix] = d_ReadData();
  8747. row[ix] = output;
  8748. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8749. memset(data_wldsd, 0, sizeof(data_wldsd));
  8750. for (int i = 0; i < x_points_num; i++) {
  8751. SERIAL_PROTOCOLPGM(" ");
  8752. SERIAL_PROTOCOL_F(row[i], 5);
  8753. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8754. dtostrf(row[i], 7, 3, numb_wldsd);
  8755. strcat(data_wldsd, numb_wldsd);
  8756. }
  8757. card.write_command(data_wldsd);
  8758. SERIAL_PROTOCOLPGM("\n");
  8759. }
  8760. custom_message_state--;
  8761. mesh_point++;
  8762. lcd_update(1);
  8763. }
  8764. #endif //MICROMETER_LOGGING
  8765. card.closefile();
  8766. //clean_up_after_endstop_move(l_feedmultiply);
  8767. }
  8768. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8769. int t1 = 0;
  8770. int t_delay = 0;
  8771. int digit[13];
  8772. int m;
  8773. char str[3];
  8774. //String mergeOutput;
  8775. char mergeOutput[15];
  8776. float output;
  8777. int mesh_point = 0; //index number of calibration point
  8778. 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
  8779. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8780. float mesh_home_z_search = 4;
  8781. float row[x_points_num];
  8782. int ix = 0;
  8783. int iy = 0;
  8784. const char* filename_wldsd = "wldsd.txt";
  8785. char data_wldsd[70];
  8786. char numb_wldsd[10];
  8787. d_setup();
  8788. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8789. // We don't know where we are! HOME!
  8790. // Push the commands to the front of the message queue in the reverse order!
  8791. // There shall be always enough space reserved for these commands.
  8792. repeatcommand_front(); // repeat G80 with all its parameters
  8793. enquecommand_front_P(G28W0);
  8794. enquecommand_front_P((PSTR("G1 Z5")));
  8795. return;
  8796. }
  8797. unsigned int custom_message_type_old = custom_message_type;
  8798. unsigned int custom_message_state_old = custom_message_state;
  8799. custom_message_type = CustomMsg::MeshBedLeveling;
  8800. custom_message_state = (x_points_num * y_points_num) + 10;
  8801. lcd_update(1);
  8802. mbl.reset();
  8803. babystep_undo();
  8804. card.openFile(filename_wldsd, false);
  8805. current_position[Z_AXIS] = mesh_home_z_search;
  8806. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8807. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8808. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8809. int l_feedmultiply = setup_for_endstop_move(false);
  8810. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8811. SERIAL_PROTOCOL(x_points_num);
  8812. SERIAL_PROTOCOLPGM(",");
  8813. SERIAL_PROTOCOL(y_points_num);
  8814. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8815. SERIAL_PROTOCOL(mesh_home_z_search);
  8816. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8817. SERIAL_PROTOCOL(x_dimension);
  8818. SERIAL_PROTOCOLPGM(",");
  8819. SERIAL_PROTOCOL(y_dimension);
  8820. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8821. while (mesh_point != x_points_num * y_points_num) {
  8822. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8823. iy = mesh_point / x_points_num;
  8824. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8825. float z0 = 0.f;
  8826. current_position[Z_AXIS] = mesh_home_z_search;
  8827. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8828. st_synchronize();
  8829. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8830. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8831. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8832. st_synchronize();
  8833. 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
  8834. break;
  8835. card.closefile();
  8836. }
  8837. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8838. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8839. //strcat(data_wldsd, numb_wldsd);
  8840. //MYSERIAL.println(data_wldsd);
  8841. //_delay(1000);
  8842. //_delay(3000);
  8843. //t1 = _millis();
  8844. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8845. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8846. memset(digit, 0, sizeof(digit));
  8847. //cli();
  8848. digitalWrite(D_REQUIRE, LOW);
  8849. for (int i = 0; i<13; i++)
  8850. {
  8851. //t1 = _millis();
  8852. for (int j = 0; j < 4; j++)
  8853. {
  8854. while (digitalRead(D_DATACLOCK) == LOW) {}
  8855. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8856. bitWrite(digit[i], j, digitalRead(D_DATA));
  8857. }
  8858. //t_delay = (_millis() - t1);
  8859. //SERIAL_PROTOCOLPGM(" ");
  8860. //SERIAL_PROTOCOL_F(t_delay, 5);
  8861. //SERIAL_PROTOCOLPGM(" ");
  8862. }
  8863. //sei();
  8864. digitalWrite(D_REQUIRE, HIGH);
  8865. mergeOutput[0] = '\0';
  8866. output = 0;
  8867. for (int r = 5; r <= 10; r++) //Merge digits
  8868. {
  8869. sprintf(str, "%d", digit[r]);
  8870. strcat(mergeOutput, str);
  8871. }
  8872. output = atof(mergeOutput);
  8873. if (digit[4] == 8) //Handle sign
  8874. {
  8875. output *= -1;
  8876. }
  8877. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8878. {
  8879. output *= 0.1;
  8880. }
  8881. //output = d_ReadData();
  8882. //row[ix] = current_position[Z_AXIS];
  8883. memset(data_wldsd, 0, sizeof(data_wldsd));
  8884. for (int i = 0; i <3; i++) {
  8885. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8886. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8887. strcat(data_wldsd, numb_wldsd);
  8888. strcat(data_wldsd, ";");
  8889. }
  8890. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8891. dtostrf(output, 8, 5, numb_wldsd);
  8892. strcat(data_wldsd, numb_wldsd);
  8893. //strcat(data_wldsd, ";");
  8894. card.write_command(data_wldsd);
  8895. //row[ix] = d_ReadData();
  8896. row[ix] = output; // current_position[Z_AXIS];
  8897. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8898. for (int i = 0; i < x_points_num; i++) {
  8899. SERIAL_PROTOCOLPGM(" ");
  8900. SERIAL_PROTOCOL_F(row[i], 5);
  8901. }
  8902. SERIAL_PROTOCOLPGM("\n");
  8903. }
  8904. custom_message_state--;
  8905. mesh_point++;
  8906. lcd_update(1);
  8907. }
  8908. card.closefile();
  8909. clean_up_after_endstop_move(l_feedmultiply);
  8910. }
  8911. #endif //HEATBED_ANALYSIS
  8912. #ifndef PINDA_THERMISTOR
  8913. static void temp_compensation_start() {
  8914. custom_message_type = CustomMsg::TempCompPreheat;
  8915. custom_message_state = PINDA_HEAT_T + 1;
  8916. lcd_update(2);
  8917. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8918. current_position[E_AXIS] -= default_retraction;
  8919. }
  8920. plan_buffer_line_curposXYZE(400, active_extruder);
  8921. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8922. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8923. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8924. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8925. st_synchronize();
  8926. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8927. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8928. delay_keep_alive(1000);
  8929. custom_message_state = PINDA_HEAT_T - i;
  8930. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8931. else lcd_update(1);
  8932. }
  8933. custom_message_type = CustomMsg::Status;
  8934. custom_message_state = 0;
  8935. }
  8936. static void temp_compensation_apply() {
  8937. int i_add;
  8938. int z_shift = 0;
  8939. float z_shift_mm;
  8940. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8941. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8942. i_add = (target_temperature_bed - 60) / 10;
  8943. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  8944. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8945. }else {
  8946. //interpolation
  8947. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8948. }
  8949. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8950. 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);
  8951. st_synchronize();
  8952. plan_set_z_position(current_position[Z_AXIS]);
  8953. }
  8954. else {
  8955. //we have no temp compensation data
  8956. }
  8957. }
  8958. #endif //ndef PINDA_THERMISTOR
  8959. float temp_comp_interpolation(float inp_temperature) {
  8960. //cubic spline interpolation
  8961. int n, i, j;
  8962. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8963. int shift[10];
  8964. int temp_C[10];
  8965. n = 6; //number of measured points
  8966. shift[0] = 0;
  8967. for (i = 0; i < n; i++) {
  8968. if (i > 0) {
  8969. //read shift in steps from EEPROM
  8970. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  8971. }
  8972. temp_C[i] = 50 + i * 10; //temperature in C
  8973. #ifdef PINDA_THERMISTOR
  8974. constexpr int start_compensating_temp = 35;
  8975. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  8976. #ifdef SUPERPINDA_SUPPORT
  8977. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  8978. #endif //SUPERPINDA_SUPPORT
  8979. #else
  8980. temp_C[i] = 50 + i * 10; //temperature in C
  8981. #endif
  8982. x[i] = (float)temp_C[i];
  8983. f[i] = (float)shift[i];
  8984. }
  8985. if (inp_temperature < x[0]) return 0;
  8986. for (i = n - 1; i>0; i--) {
  8987. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  8988. h[i - 1] = x[i] - x[i - 1];
  8989. }
  8990. //*********** formation of h, s , f matrix **************
  8991. for (i = 1; i<n - 1; i++) {
  8992. m[i][i] = 2 * (h[i - 1] + h[i]);
  8993. if (i != 1) {
  8994. m[i][i - 1] = h[i - 1];
  8995. m[i - 1][i] = h[i - 1];
  8996. }
  8997. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  8998. }
  8999. //*********** forward elimination **************
  9000. for (i = 1; i<n - 2; i++) {
  9001. temp = (m[i + 1][i] / m[i][i]);
  9002. for (j = 1; j <= n - 1; j++)
  9003. m[i + 1][j] -= temp*m[i][j];
  9004. }
  9005. //*********** backward substitution *********
  9006. for (i = n - 2; i>0; i--) {
  9007. sum = 0;
  9008. for (j = i; j <= n - 2; j++)
  9009. sum += m[i][j] * s[j];
  9010. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9011. }
  9012. for (i = 0; i<n - 1; i++)
  9013. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9014. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9015. b = s[i] / 2;
  9016. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9017. d = f[i];
  9018. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9019. }
  9020. return sum;
  9021. }
  9022. #ifdef PINDA_THERMISTOR
  9023. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9024. {
  9025. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9026. if (!calibration_status_pinda()) return 0;
  9027. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9028. }
  9029. #endif //PINDA_THERMISTOR
  9030. void long_pause() //long pause print
  9031. {
  9032. st_synchronize();
  9033. start_pause_print = _millis();
  9034. // Stop heaters
  9035. heating_status = HeatingStatus::NO_HEATING;
  9036. setAllTargetHotends(0);
  9037. // Lift z
  9038. raise_z(Z_PAUSE_LIFT);
  9039. // Move XY to side
  9040. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9041. current_position[X_AXIS] = X_PAUSE_POS;
  9042. current_position[Y_AXIS] = Y_PAUSE_POS;
  9043. plan_buffer_line_curposXYZE(50);
  9044. }
  9045. // did we come here from a thermal error?
  9046. if(get_temp_error()) {
  9047. // time to stop the error beep
  9048. WRITE(BEEPER, LOW);
  9049. } else {
  9050. // Turn off the print fan
  9051. fanSpeed = 0;
  9052. }
  9053. }
  9054. void serialecho_temperatures() {
  9055. float tt = degHotend(active_extruder);
  9056. SERIAL_PROTOCOLPGM("T:");
  9057. SERIAL_PROTOCOL(tt);
  9058. SERIAL_PROTOCOLPGM(" E:");
  9059. SERIAL_PROTOCOL((int)active_extruder);
  9060. SERIAL_PROTOCOLPGM(" B:");
  9061. SERIAL_PROTOCOL_F(degBed(), 1);
  9062. SERIAL_PROTOCOLLN();
  9063. }
  9064. #ifdef UVLO_SUPPORT
  9065. void uvlo_drain_reset()
  9066. {
  9067. // burn all that residual power
  9068. wdt_enable(WDTO_1S);
  9069. WRITE(BEEPER,HIGH);
  9070. lcd_clear();
  9071. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9072. while(1);
  9073. }
  9074. void uvlo_()
  9075. {
  9076. unsigned long time_start = _millis();
  9077. bool sd_print = card.sdprinting;
  9078. // Conserve power as soon as possible.
  9079. #ifdef LCD_BL_PIN
  9080. backlightMode = BACKLIGHT_MODE_DIM;
  9081. backlightLevel_LOW = 0;
  9082. backlight_update();
  9083. #endif //LCD_BL_PIN
  9084. disable_x();
  9085. disable_y();
  9086. #ifdef TMC2130
  9087. tmc2130_set_current_h(Z_AXIS, 20);
  9088. tmc2130_set_current_r(Z_AXIS, 20);
  9089. tmc2130_set_current_h(E_AXIS, 20);
  9090. tmc2130_set_current_r(E_AXIS, 20);
  9091. #endif //TMC2130
  9092. // Stop all heaters
  9093. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9094. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9095. setAllTargetHotends(0);
  9096. setTargetBed(0);
  9097. // Calculate the file position, from which to resume this print.
  9098. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9099. {
  9100. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9101. sd_position -= sdlen_planner;
  9102. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9103. sd_position -= sdlen_cmdqueue;
  9104. if (sd_position < 0) sd_position = 0;
  9105. }
  9106. // save the global state at planning time
  9107. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9108. uint16_t feedrate_bckp;
  9109. if (current_block && !pos_invalid)
  9110. {
  9111. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9112. feedrate_bckp = current_block->gcode_feedrate;
  9113. saved_segment_idx = current_block->segment_idx;
  9114. }
  9115. else
  9116. {
  9117. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9118. feedrate_bckp = feedrate;
  9119. saved_segment_idx = 0;
  9120. }
  9121. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9122. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9123. // get the physical Z for further manipulation.
  9124. bool mbl_was_active = mbl.active;
  9125. mbl.active = false;
  9126. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9127. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9128. // are in action.
  9129. planner_abort_hard();
  9130. // Store the print logical Z position, which we need to recover (a slight error here would be
  9131. // recovered on the next Gcode instruction, while a physical location error would not)
  9132. float logical_z = current_position[Z_AXIS];
  9133. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9134. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9135. // Store the print E position before we lose track
  9136. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9137. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9138. // Clean the input command queue, inhibit serial processing using saved_printing
  9139. cmdqueue_reset();
  9140. card.sdprinting = false;
  9141. saved_printing = true;
  9142. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9143. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9144. planner_aborted = false;
  9145. sei();
  9146. // Retract
  9147. current_position[E_AXIS] -= default_retraction;
  9148. plan_buffer_line_curposXYZE(95);
  9149. st_synchronize();
  9150. disable_e0();
  9151. // Read out the current Z motor microstep counter to move the axis up towards
  9152. // a full step before powering off. NOTE: we need to ensure to schedule more
  9153. // than "dropsegments" steps in order to move (this is always the case here
  9154. // due to UVLO_Z_AXIS_SHIFT being used)
  9155. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9156. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9157. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9158. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9159. + UVLO_Z_AXIS_SHIFT;
  9160. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9161. st_synchronize();
  9162. poweroff_z();
  9163. // Write the file position.
  9164. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9165. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9166. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9167. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9168. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9169. // Scale the z value to 1u resolution.
  9170. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9171. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9172. }
  9173. // Write the _final_ Z position and motor microstep counter (unused).
  9174. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9175. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9176. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9177. // Store the current position.
  9178. if (pos_invalid)
  9179. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9180. else
  9181. {
  9182. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9183. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9184. }
  9185. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9186. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9187. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9188. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9189. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9190. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9191. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9192. #if EXTRUDERS > 1
  9193. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9194. #if EXTRUDERS > 2
  9195. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9196. #endif
  9197. #endif
  9198. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9199. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9200. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9201. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9202. // Store the saved target
  9203. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9204. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9205. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9206. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9207. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9208. #ifdef LIN_ADVANCE
  9209. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9210. #endif
  9211. // Finaly store the "power outage" flag.
  9212. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9213. // Increment power failure counter
  9214. eeprom_increment_byte((uint8_t*)EEPROM_POWER_COUNT);
  9215. eeprom_increment_word((uint16_t*)EEPROM_POWER_COUNT_TOT);
  9216. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9217. WRITE(BEEPER,HIGH);
  9218. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9219. poweron_z();
  9220. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9221. plan_buffer_line_curposXYZE(500);
  9222. st_synchronize();
  9223. wdt_enable(WDTO_1S);
  9224. while(1);
  9225. }
  9226. void uvlo_tiny()
  9227. {
  9228. unsigned long time_start = _millis();
  9229. // Conserve power as soon as possible.
  9230. disable_x();
  9231. disable_y();
  9232. disable_e0();
  9233. #ifdef TMC2130
  9234. tmc2130_set_current_h(Z_AXIS, 20);
  9235. tmc2130_set_current_r(Z_AXIS, 20);
  9236. #endif //TMC2130
  9237. // Stop all heaters
  9238. setAllTargetHotends(0);
  9239. setTargetBed(0);
  9240. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9241. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9242. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9243. // Disable MBL (if not already) to work with physical coordinates.
  9244. mbl.active = false;
  9245. planner_abort_hard();
  9246. // Allow for small roundoffs to be ignored
  9247. 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])
  9248. {
  9249. // Clean the input command queue, inhibit serial processing using saved_printing
  9250. cmdqueue_reset();
  9251. card.sdprinting = false;
  9252. saved_printing = true;
  9253. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9254. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9255. planner_aborted = false;
  9256. sei();
  9257. // The axis was moved: adjust Z as done on a regular UVLO.
  9258. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9259. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9260. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9261. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9262. + UVLO_TINY_Z_AXIS_SHIFT;
  9263. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9264. st_synchronize();
  9265. poweroff_z();
  9266. // Update Z position
  9267. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9268. // Update the _final_ Z motor microstep counter (unused).
  9269. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9270. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9271. }
  9272. // Update the the "power outage" flag.
  9273. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9274. // Increment power failure counter
  9275. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9276. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9277. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9278. uvlo_drain_reset();
  9279. }
  9280. #endif //UVLO_SUPPORT
  9281. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9282. void setup_fan_interrupt() {
  9283. //INT7
  9284. DDRE &= ~(1 << 7); //input pin
  9285. PORTE &= ~(1 << 7); //no internal pull-up
  9286. //start with sensing rising edge
  9287. EICRB &= ~(1 << 6);
  9288. EICRB |= (1 << 7);
  9289. //enable INT7 interrupt
  9290. EIMSK |= (1 << 7);
  9291. }
  9292. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9293. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9294. ISR(INT7_vect) {
  9295. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9296. #ifdef FAN_SOFT_PWM
  9297. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9298. #else //FAN_SOFT_PWM
  9299. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9300. #endif //FAN_SOFT_PWM
  9301. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9302. t_fan_rising_edge = millis_nc();
  9303. }
  9304. else { //interrupt was triggered by falling edge
  9305. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9306. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9307. }
  9308. }
  9309. EICRB ^= (1 << 6); //change edge
  9310. }
  9311. #endif
  9312. #ifdef UVLO_SUPPORT
  9313. void setup_uvlo_interrupt() {
  9314. DDRE &= ~(1 << 4); //input pin
  9315. PORTE &= ~(1 << 4); //no internal pull-up
  9316. // sensing falling edge
  9317. EICRB |= (1 << 0);
  9318. EICRB &= ~(1 << 1);
  9319. // enable INT4 interrupt
  9320. EIMSK |= (1 << 4);
  9321. // check if power was lost before we armed the interrupt
  9322. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9323. {
  9324. SERIAL_ECHOLNPGM("INT4");
  9325. uvlo_drain_reset();
  9326. }
  9327. }
  9328. ISR(INT4_vect) {
  9329. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9330. SERIAL_ECHOLNPGM("INT4");
  9331. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9332. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9333. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9334. }
  9335. void recover_print(uint8_t automatic) {
  9336. char cmd[30];
  9337. lcd_update_enable(true);
  9338. lcd_update(2);
  9339. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9340. // Recover position, temperatures and extrude_multipliers
  9341. bool mbl_was_active = recover_machine_state_after_power_panic();
  9342. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9343. // and second also so one may remove the excess priming material.
  9344. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9345. {
  9346. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9347. enquecommand(cmd);
  9348. }
  9349. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9350. // transformation status. G28 will not touch Z when MBL is off.
  9351. enquecommand_P(PSTR("G28 X Y"));
  9352. // Set the target bed and nozzle temperatures and wait.
  9353. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9354. enquecommand(cmd);
  9355. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9356. enquecommand(cmd);
  9357. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9358. enquecommand(cmd);
  9359. enquecommand_P(PSTR("M83")); //E axis relative mode
  9360. // If not automatically recoreverd (long power loss)
  9361. if(automatic == 0){
  9362. //Extrude some filament to stabilize the pressure
  9363. enquecommand_P(PSTR("G1 E5 F120"));
  9364. // Retract to be consistent with a short pause
  9365. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9366. enquecommand(cmd);
  9367. }
  9368. 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]);
  9369. // Restart the print.
  9370. restore_print_from_eeprom(mbl_was_active);
  9371. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9372. }
  9373. bool recover_machine_state_after_power_panic()
  9374. {
  9375. // 1) Preset some dummy values for the XY axes
  9376. current_position[X_AXIS] = 0;
  9377. current_position[Y_AXIS] = 0;
  9378. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9379. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9380. bool mbl_was_active = false;
  9381. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9382. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9383. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9384. // Scale the z value to 10u resolution.
  9385. int16_t v;
  9386. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9387. if (v != 0)
  9388. mbl_was_active = true;
  9389. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9390. }
  9391. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9392. // The current position after power panic is moved to the next closest 0th full step.
  9393. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9394. // Recover last E axis position
  9395. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9396. // 3) Initialize the logical to physical coordinate system transformation.
  9397. world2machine_initialize();
  9398. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9399. // print_mesh_bed_leveling_table();
  9400. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9401. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9402. babystep_load();
  9403. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9404. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9405. clamp_to_software_endstops(current_position);
  9406. set_destination_to_current();
  9407. plan_set_position_curposXYZE();
  9408. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9409. print_world_coordinates();
  9410. // 6) Power up the Z motors, mark their positions as known.
  9411. axis_known_position[Z_AXIS] = true;
  9412. enable_z();
  9413. // 7) Recover the target temperatures.
  9414. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9415. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9416. // 8) Recover extruder multipilers
  9417. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9418. #if EXTRUDERS > 1
  9419. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9420. #if EXTRUDERS > 2
  9421. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9422. #endif
  9423. #endif
  9424. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9425. // 9) Recover the saved target
  9426. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9427. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9428. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9429. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9430. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9431. #ifdef LIN_ADVANCE
  9432. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9433. #endif
  9434. return mbl_was_active;
  9435. }
  9436. void restore_print_from_eeprom(bool mbl_was_active) {
  9437. int feedrate_rec;
  9438. int feedmultiply_rec;
  9439. uint8_t fan_speed_rec;
  9440. char cmd[48];
  9441. char filename[FILENAME_LENGTH];
  9442. uint8_t depth = 0;
  9443. char dir_name[9];
  9444. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9445. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9446. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9447. SERIAL_ECHOPGM("Feedrate:");
  9448. MYSERIAL.print(feedrate_rec);
  9449. SERIAL_ECHOPGM(", feedmultiply:");
  9450. MYSERIAL.println(feedmultiply_rec);
  9451. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9452. MYSERIAL.println(int(depth));
  9453. for (uint8_t i = 0; i < depth; i++) {
  9454. for (uint8_t j = 0; j < 8; j++) {
  9455. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9456. }
  9457. dir_name[8] = '\0';
  9458. MYSERIAL.println(dir_name);
  9459. // strcpy(card.dir_names[i], dir_name);
  9460. card.chdir(dir_name, false);
  9461. }
  9462. for (uint8_t i = 0; i < 8; i++) {
  9463. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9464. }
  9465. filename[8] = '\0';
  9466. MYSERIAL.print(filename);
  9467. strcat_P(filename, PSTR(".gco"));
  9468. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9469. enquecommand(cmd);
  9470. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9471. SERIAL_ECHOPGM("Position read from eeprom:");
  9472. MYSERIAL.println(position);
  9473. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9474. // without shifting Z along the way. This requires performing the move without mbl.
  9475. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9476. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9477. if (pos_x != X_COORD_INVALID)
  9478. {
  9479. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9480. enquecommand(cmd);
  9481. }
  9482. // Enable MBL and switch to logical positioning
  9483. if (mbl_was_active)
  9484. enquecommand_P(PSTR("PRUSA MBL V1"));
  9485. // Move the Z axis down to the print, in logical coordinates.
  9486. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9487. enquecommand(cmd);
  9488. // Restore acceleration settings
  9489. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9490. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9491. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9492. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9493. enquecommand(cmd);
  9494. // Unretract.
  9495. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9496. enquecommand(cmd);
  9497. // Recover final E axis position and mode
  9498. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9499. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9500. enquecommand(cmd);
  9501. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9502. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9503. // Set the feedrates saved at the power panic.
  9504. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9505. enquecommand(cmd);
  9506. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9507. enquecommand(cmd);
  9508. // Set the fan speed saved at the power panic.
  9509. strcpy_P(cmd, PSTR("M106 S"));
  9510. strcat(cmd, itostr3(int(fan_speed_rec)));
  9511. enquecommand(cmd);
  9512. // Set a position in the file.
  9513. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9514. enquecommand(cmd);
  9515. enquecommand_P(PSTR("G4 S0"));
  9516. enquecommand_P(PSTR("PRUSA uvlo"));
  9517. }
  9518. #endif //UVLO_SUPPORT
  9519. //! @brief Immediately stop print moves
  9520. //!
  9521. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9522. //! If printing from sd card, position in file is saved.
  9523. //! If printing from USB, line number is saved.
  9524. //!
  9525. //! @param z_move
  9526. //! @param e_move
  9527. void stop_and_save_print_to_ram(float z_move, float e_move)
  9528. {
  9529. if (saved_printing) return;
  9530. #if 0
  9531. unsigned char nplanner_blocks;
  9532. #endif
  9533. unsigned char nlines;
  9534. uint16_t sdlen_planner;
  9535. uint16_t sdlen_cmdqueue;
  9536. cli();
  9537. if (card.sdprinting) {
  9538. #if 0
  9539. nplanner_blocks = number_of_blocks();
  9540. #endif
  9541. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9542. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9543. saved_sdpos -= sdlen_planner;
  9544. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9545. saved_sdpos -= sdlen_cmdqueue;
  9546. saved_printing_type = PRINTING_TYPE_SD;
  9547. }
  9548. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9549. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9550. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9551. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9552. saved_sdpos -= nlines;
  9553. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9554. saved_printing_type = PRINTING_TYPE_USB;
  9555. }
  9556. else {
  9557. saved_printing_type = PRINTING_TYPE_NONE;
  9558. //not sd printing nor usb printing
  9559. }
  9560. #if 0
  9561. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9562. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9563. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9564. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9565. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9566. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9567. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9568. {
  9569. card.setIndex(saved_sdpos);
  9570. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9571. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9572. MYSERIAL.print(char(card.get()));
  9573. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9574. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9575. MYSERIAL.print(char(card.get()));
  9576. SERIAL_ECHOLNPGM("End of command buffer");
  9577. }
  9578. {
  9579. // Print the content of the planner buffer, line by line:
  9580. card.setIndex(saved_sdpos);
  9581. int8_t iline = 0;
  9582. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9583. SERIAL_ECHOPGM("Planner line (from file): ");
  9584. MYSERIAL.print(int(iline), DEC);
  9585. SERIAL_ECHOPGM(", length: ");
  9586. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9587. SERIAL_ECHOPGM(", steps: (");
  9588. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9589. SERIAL_ECHOPGM(",");
  9590. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9591. SERIAL_ECHOPGM(",");
  9592. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9593. SERIAL_ECHOPGM(",");
  9594. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9595. SERIAL_ECHOPGM("), events: ");
  9596. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9597. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9598. MYSERIAL.print(char(card.get()));
  9599. }
  9600. }
  9601. {
  9602. // Print the content of the command buffer, line by line:
  9603. int8_t iline = 0;
  9604. union {
  9605. struct {
  9606. char lo;
  9607. char hi;
  9608. } lohi;
  9609. uint16_t value;
  9610. } sdlen_single;
  9611. int _bufindr = bufindr;
  9612. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9613. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9614. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9615. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9616. }
  9617. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9618. MYSERIAL.print(int(iline), DEC);
  9619. SERIAL_ECHOPGM(", type: ");
  9620. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9621. SERIAL_ECHOPGM(", len: ");
  9622. MYSERIAL.println(sdlen_single.value, DEC);
  9623. // Print the content of the buffer line.
  9624. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9625. SERIAL_ECHOPGM("Buffer line (from file): ");
  9626. MYSERIAL.println(int(iline), DEC);
  9627. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9628. MYSERIAL.print(char(card.get()));
  9629. if (-- _buflen == 0)
  9630. break;
  9631. // First skip the current command ID and iterate up to the end of the string.
  9632. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9633. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9634. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9635. // If the end of the buffer was empty,
  9636. if (_bufindr == sizeof(cmdbuffer)) {
  9637. // skip to the start and find the nonzero command.
  9638. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9639. }
  9640. }
  9641. }
  9642. #endif
  9643. // save the global state at planning time
  9644. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9645. if (current_block && !pos_invalid)
  9646. {
  9647. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9648. saved_feedrate2 = current_block->gcode_feedrate;
  9649. saved_segment_idx = current_block->segment_idx;
  9650. // 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);
  9651. }
  9652. else
  9653. {
  9654. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9655. saved_feedrate2 = feedrate;
  9656. saved_segment_idx = 0;
  9657. }
  9658. planner_abort_hard(); //abort printing
  9659. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9660. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9661. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9662. saved_extruder_temperature = degTargetHotend(active_extruder);
  9663. saved_bed_temperature = degTargetBed();
  9664. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9665. saved_fan_speed = fanSpeed;
  9666. cmdqueue_reset(); //empty cmdqueue
  9667. card.sdprinting = false;
  9668. // card.closefile();
  9669. saved_printing = true;
  9670. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9671. st_reset_timer();
  9672. sei();
  9673. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9674. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9675. // the caller can continue processing. This is used during powerpanic to save the state as we
  9676. // move away from the print.
  9677. char buf[48];
  9678. if(e_move)
  9679. {
  9680. // First unretract (relative extrusion)
  9681. if(!saved_extruder_relative_mode){
  9682. enquecommand(PSTR("M83"), true);
  9683. }
  9684. //retract 45mm/s
  9685. // A single sprintf may not be faster, but is definitely 20B shorter
  9686. // than a sequence of commands building the string piece by piece
  9687. // A snprintf would have been a safer call, but since it is not used
  9688. // in the whole program, its implementation would bring more bytes to the total size
  9689. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9690. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9691. enquecommand(buf, false);
  9692. }
  9693. if(z_move)
  9694. {
  9695. // Then lift Z axis
  9696. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9697. enquecommand(buf, false);
  9698. }
  9699. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9700. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9701. repeatcommand_front();
  9702. }
  9703. }
  9704. void restore_extruder_temperature_from_ram() {
  9705. if (degTargetHotend(active_extruder) != saved_extruder_temperature)
  9706. {
  9707. setTargetHotendSafe(saved_extruder_temperature, active_extruder);
  9708. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9709. wait_for_heater(_millis(), active_extruder);
  9710. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9711. }
  9712. }
  9713. //! @brief Restore print from ram
  9714. //!
  9715. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9716. //! print fan speed, waits for extruder temperature restore, then restores
  9717. //! position and continues print moves.
  9718. //!
  9719. //! Internally lcd_update() is called by wait_for_heater().
  9720. //!
  9721. //! @param e_move
  9722. void restore_print_from_ram_and_continue(float e_move)
  9723. {
  9724. if (!saved_printing) return;
  9725. #ifdef FANCHECK
  9726. // Do not allow resume printing if fans are still not ok
  9727. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9728. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9729. #endif
  9730. // Make sure fan is turned off
  9731. fanSpeed = 0;
  9732. // restore bed temperature (bed can be disabled during a thermal warning)
  9733. if (degBed() != saved_bed_temperature)
  9734. setTargetBed(saved_bed_temperature);
  9735. restore_extruder_temperature_from_ram();
  9736. // Restore saved fan speed
  9737. fanSpeed = saved_fan_speed;
  9738. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9739. float e = saved_pos[E_AXIS] - e_move;
  9740. plan_set_e_position(e);
  9741. #ifdef FANCHECK
  9742. fans_check_enabled = false;
  9743. #endif
  9744. // do not restore XY for commands that do not require that
  9745. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9746. {
  9747. saved_pos[X_AXIS] = current_position[X_AXIS];
  9748. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9749. }
  9750. //first move print head in XY to the saved position:
  9751. 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);
  9752. //then move Z
  9753. 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);
  9754. //and finaly unretract (35mm/s)
  9755. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9756. st_synchronize();
  9757. #ifdef FANCHECK
  9758. fans_check_enabled = true;
  9759. #endif
  9760. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9761. feedrate = saved_feedrate2;
  9762. feedmultiply = saved_feedmultiply2;
  9763. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9764. set_destination_to_current();
  9765. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9766. card.setIndex(saved_sdpos);
  9767. sdpos_atomic = saved_sdpos;
  9768. card.sdprinting = true;
  9769. }
  9770. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9771. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9772. serial_count = 0;
  9773. FlushSerialRequestResend();
  9774. }
  9775. else {
  9776. //not sd printing nor usb printing
  9777. }
  9778. lcd_setstatuspgm(MSG_WELCOME);
  9779. saved_printing_type = PRINTING_TYPE_NONE;
  9780. saved_printing = false;
  9781. planner_aborted = true; // unroll the stack
  9782. }
  9783. // Cancel the state related to a currently saved print
  9784. void cancel_saved_printing()
  9785. {
  9786. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9787. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9788. saved_printing_type = PRINTING_TYPE_NONE;
  9789. saved_printing = false;
  9790. }
  9791. void print_world_coordinates()
  9792. {
  9793. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9794. }
  9795. void print_physical_coordinates()
  9796. {
  9797. 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));
  9798. }
  9799. void print_mesh_bed_leveling_table()
  9800. {
  9801. SERIAL_ECHOPGM("mesh bed leveling: ");
  9802. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9803. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9804. MYSERIAL.print(mbl.z_values[y][x], 3);
  9805. SERIAL_ECHO(' ');
  9806. }
  9807. SERIAL_ECHOLN();
  9808. }
  9809. uint8_t calc_percent_done()
  9810. {
  9811. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9812. uint8_t percent_done = 0;
  9813. #ifdef TMC2130
  9814. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9815. {
  9816. percent_done = print_percent_done_normal;
  9817. }
  9818. else if (print_percent_done_silent <= 100)
  9819. {
  9820. percent_done = print_percent_done_silent;
  9821. }
  9822. #else
  9823. if (print_percent_done_normal <= 100)
  9824. {
  9825. percent_done = print_percent_done_normal;
  9826. }
  9827. #endif //TMC2130
  9828. else
  9829. {
  9830. percent_done = card.percentDone();
  9831. }
  9832. return percent_done;
  9833. }
  9834. static void print_time_remaining_init()
  9835. {
  9836. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9837. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9838. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9839. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9840. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9841. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9842. }
  9843. void load_filament_final_feed()
  9844. {
  9845. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9846. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9847. }
  9848. //! @brief Wait for user to check the state
  9849. //! @par nozzle_temp nozzle temperature to load filament
  9850. void M600_check_state(float nozzle_temp)
  9851. {
  9852. uint8_t lcd_change_filament_state = 0;
  9853. while (lcd_change_filament_state != 1)
  9854. {
  9855. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9856. lcd_change_filament_state = lcd_alright();
  9857. KEEPALIVE_STATE(IN_HANDLER);
  9858. switch(lcd_change_filament_state)
  9859. {
  9860. // Filament failed to load so load it again
  9861. case 2:
  9862. if (MMU2::mmu2.Enabled()){
  9863. // Unload filament
  9864. mmu_M600_unload_filament();
  9865. // Ask to remove any old filament and load new
  9866. mmu_M600_wait_and_beep();
  9867. // After user clicks knob, MMU will load the filament
  9868. mmu_M600_load_filament(false, nozzle_temp);
  9869. } else {
  9870. M600_load_filament_movements();
  9871. }
  9872. break;
  9873. // Filament loaded properly but color is not clear
  9874. case 3:
  9875. st_synchronize();
  9876. load_filament_final_feed();
  9877. lcd_loading_color();
  9878. st_synchronize();
  9879. break;
  9880. // Everything good
  9881. default:
  9882. lcd_change_success();
  9883. break;
  9884. }
  9885. }
  9886. }
  9887. //! @brief Wait for user action
  9888. //!
  9889. //! Beep, manage nozzle heater and wait for user to start unload filament
  9890. //! If times out, active extruder temperature is set to 0.
  9891. //!
  9892. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9893. void M600_wait_for_user(float HotendTempBckp) {
  9894. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9895. int counterBeep = 0;
  9896. unsigned long waiting_start_time = _millis();
  9897. uint8_t wait_for_user_state = 0;
  9898. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9899. bool bFirst=true;
  9900. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9901. manage_heater();
  9902. manage_inactivity(true);
  9903. #if BEEPER > 0
  9904. if (counterBeep == 500) {
  9905. counterBeep = 0;
  9906. }
  9907. SET_OUTPUT(BEEPER);
  9908. if (counterBeep == 0) {
  9909. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9910. {
  9911. bFirst=false;
  9912. WRITE(BEEPER, HIGH);
  9913. }
  9914. }
  9915. if (counterBeep == 20) {
  9916. WRITE(BEEPER, LOW);
  9917. }
  9918. counterBeep++;
  9919. #endif //BEEPER > 0
  9920. switch (wait_for_user_state) {
  9921. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9922. delay_keep_alive(4);
  9923. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9924. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9925. wait_for_user_state = 1;
  9926. setAllTargetHotends(0);
  9927. st_synchronize();
  9928. disable_e0();
  9929. disable_e1();
  9930. disable_e2();
  9931. }
  9932. break;
  9933. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9934. delay_keep_alive(4);
  9935. if (lcd_clicked()) {
  9936. setTargetHotend(HotendTempBckp, active_extruder);
  9937. lcd_wait_for_heater();
  9938. wait_for_user_state = 2;
  9939. }
  9940. break;
  9941. case 2: //waiting for nozzle to reach target temperature
  9942. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9943. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9944. waiting_start_time = _millis();
  9945. wait_for_user_state = 0;
  9946. }
  9947. else {
  9948. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9949. lcd_set_cursor(1, 4);
  9950. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  9951. }
  9952. break;
  9953. }
  9954. }
  9955. WRITE(BEEPER, LOW);
  9956. }
  9957. void M600_load_filament_movements()
  9958. {
  9959. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  9960. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  9961. load_filament_final_feed();
  9962. lcd_loading_filament();
  9963. st_synchronize();
  9964. }
  9965. void M600_load_filament() {
  9966. //load filament for single material and MMU
  9967. lcd_wait_interact();
  9968. //load_filament_time = _millis();
  9969. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9970. while(!lcd_clicked())
  9971. {
  9972. manage_heater();
  9973. manage_inactivity(true);
  9974. #ifdef FILAMENT_SENSOR
  9975. if (fsensor.getFilamentLoadEvent()) {
  9976. Sound_MakeCustom(50,1000,false);
  9977. break;
  9978. }
  9979. #endif //FILAMENT_SENSOR
  9980. }
  9981. KEEPALIVE_STATE(IN_HANDLER);
  9982. M600_load_filament_movements();
  9983. Sound_MakeCustom(50,1000,false);
  9984. lcd_update_enable(false);
  9985. }
  9986. //! @brief Wait for click
  9987. //!
  9988. //! Set
  9989. void marlin_wait_for_click()
  9990. {
  9991. int8_t busy_state_backup = busy_state;
  9992. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9993. lcd_consume_click();
  9994. while(!lcd_clicked())
  9995. {
  9996. manage_heater();
  9997. manage_inactivity(true);
  9998. lcd_update(0);
  9999. }
  10000. KEEPALIVE_STATE(busy_state_backup);
  10001. }
  10002. #ifdef PSU_Delta
  10003. bool bEnableForce_z;
  10004. void init_force_z()
  10005. {
  10006. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10007. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10008. disable_force_z();
  10009. }
  10010. void check_force_z()
  10011. {
  10012. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10013. init_force_z(); // causes enforced switching into disable-state
  10014. }
  10015. void disable_force_z()
  10016. {
  10017. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10018. bEnableForce_z=false;
  10019. // switching to silent mode
  10020. #ifdef TMC2130
  10021. tmc2130_mode=TMC2130_MODE_SILENT;
  10022. update_mode_profile();
  10023. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10024. #endif // TMC2130
  10025. }
  10026. void enable_force_z()
  10027. {
  10028. if(bEnableForce_z)
  10029. return; // motor already enabled (may be ;-p )
  10030. bEnableForce_z=true;
  10031. // mode recovering
  10032. #ifdef TMC2130
  10033. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10034. update_mode_profile();
  10035. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10036. #endif // TMC2130
  10037. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10038. }
  10039. #endif // PSU_Delta