Marlin_main.cpp 390 KB

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