Marlin_main.cpp 389 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642
  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 "Dcodes.h"
  80. #include "AutoDeplete.h"
  81. #ifndef LA_NOCOMPAT
  82. #include "la10compat.h"
  83. #endif
  84. #include "spi.h"
  85. #include "Filament_sensor.h"
  86. #ifdef TMC2130
  87. #include "tmc2130.h"
  88. #endif //TMC2130
  89. #ifdef XFLASH
  90. #include "xflash.h"
  91. #include "optiboot_xflash.h"
  92. #endif //XFLASH
  93. #include "xflash_dump.h"
  94. #ifdef BLINKM
  95. #include "BlinkM.h"
  96. #include "Wire.h"
  97. #endif
  98. #ifdef ULTRALCD
  99. #include "ultralcd.h"
  100. #endif
  101. #if NUM_SERVOS > 0
  102. #include "Servo.h"
  103. #endif
  104. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  105. #include <SPI.h>
  106. #endif
  107. #include "mmu.h"
  108. #define VERSION_STRING "1.0.2"
  109. #include "ultralcd.h"
  110. #include "sound.h"
  111. #include "cmdqueue.h"
  112. //Macro for print fan speed
  113. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  114. //filament types
  115. #define FILAMENT_DEFAULT 0
  116. #define FILAMENT_FLEX 1
  117. #define FILAMENT_PVA 2
  118. #define FILAMENT_UNDEFINED 255
  119. //Stepper Movement Variables
  120. //===========================================================================
  121. //=============================imported variables============================
  122. //===========================================================================
  123. //===========================================================================
  124. //=============================public variables=============================
  125. //===========================================================================
  126. #ifdef SDSUPPORT
  127. CardReader card;
  128. #endif
  129. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  130. //used for PINDA temp calibration and pause print
  131. #define DEFAULT_RETRACTION 1
  132. #define DEFAULT_RETRACTION_MM 4 //MM
  133. float default_retraction = DEFAULT_RETRACTION;
  134. float homing_feedrate[] = HOMING_FEEDRATE;
  135. //Although this flag and many others like this could be represented with a struct/bitfield for each axis (more readable and efficient code), the implementation
  136. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  137. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  138. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  139. uint8_t axis_relative_modes = 0;
  140. int feedmultiply=100; //100->1 200->2
  141. int extrudemultiply=100; //100->1 200->2
  142. int extruder_multiply[EXTRUDERS] = {100
  143. #if EXTRUDERS > 1
  144. , 100
  145. #if EXTRUDERS > 2
  146. , 100
  147. #endif
  148. #endif
  149. };
  150. bool homing_flag = false;
  151. int8_t lcd_change_fil_state = 0;
  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. uint8_t active_extruder = 0;
  194. int fanSpeed=0;
  195. uint8_t newFanSpeed = 0;
  196. #ifdef FWRETRACT
  197. bool retracted[EXTRUDERS]={false
  198. #if EXTRUDERS > 1
  199. , false
  200. #if EXTRUDERS > 2
  201. , false
  202. #endif
  203. #endif
  204. };
  205. bool retracted_swap[EXTRUDERS]={false
  206. #if EXTRUDERS > 1
  207. , false
  208. #if EXTRUDERS > 2
  209. , false
  210. #endif
  211. #endif
  212. };
  213. float retract_length_swap = RETRACT_LENGTH_SWAP;
  214. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  215. #endif
  216. #ifdef PS_DEFAULT_OFF
  217. bool powersupply = false;
  218. #else
  219. bool powersupply = true;
  220. #endif
  221. bool cancel_heatup = false;
  222. int8_t busy_state = NOT_BUSY;
  223. static long prev_busy_signal_ms = -1;
  224. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  225. const char errormagic[] PROGMEM = "Error:";
  226. const char echomagic[] PROGMEM = "echo:";
  227. const char G28W0[] PROGMEM = "G28 W0";
  228. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  229. // that they can be used later for various logical checks
  230. #define X_COORD_INVALID (X_MIN_POS-1)
  231. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  232. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  233. uint16_t saved_segment_idx = 0;
  234. // save/restore printing in case that mmu was not responding
  235. bool mmu_print_saved = false;
  236. // storing estimated time to end of print counted by slicer
  237. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  238. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  239. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  240. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  241. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  242. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  243. uint32_t IP_address = 0;
  244. //===========================================================================
  245. //=============================Private Variables=============================
  246. //===========================================================================
  247. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  248. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  249. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  250. // For tracing an arc
  251. static float offset[3] = {0.0, 0.0, 0.0};
  252. // Current feedrate
  253. float feedrate = 1500.0;
  254. // Feedrate for the next move
  255. static float next_feedrate;
  256. // Original feedrate saved during homing moves
  257. static float saved_feedrate;
  258. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  259. //static float tt = 0;
  260. //static float bt = 0;
  261. //Inactivity shutdown variables
  262. static LongTimer previous_millis_cmd;
  263. unsigned long max_inactive_time = 0;
  264. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  265. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  266. unsigned long starttime=0;
  267. unsigned long stoptime=0;
  268. ShortTimer usb_timer;
  269. bool Stopped=false;
  270. #if NUM_SERVOS > 0
  271. Servo servos[NUM_SERVOS];
  272. #endif
  273. bool target_direction;
  274. //Insert variables if CHDK is defined
  275. #ifdef CHDK
  276. unsigned long chdkHigh = 0;
  277. bool chdkActive = false;
  278. #endif
  279. //! @name RAM save/restore printing
  280. //! @{
  281. bool saved_printing = false; //!< Print is paused and saved in RAM
  282. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  283. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  284. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  285. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  286. static int saved_feedmultiply2 = 0;
  287. static uint8_t saved_active_extruder = 0;
  288. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  289. float saved_bed_temperature = 0.0; //!< Bed temperature
  290. static bool saved_extruder_relative_mode = false;
  291. int saved_fan_speed = 0; //!< Print fan speed
  292. //! @}
  293. static int saved_feedmultiply_mm = 100;
  294. class AutoReportFeatures {
  295. union {
  296. struct {
  297. uint8_t temp : 1; //Temperature flag
  298. uint8_t fans : 1; //Fans flag
  299. uint8_t pos: 1; //Position flag
  300. uint8_t ar4 : 1; //Unused
  301. uint8_t ar5 : 1; //Unused
  302. uint8_t ar6 : 1; //Unused
  303. uint8_t ar7 : 1; //Unused
  304. } __attribute__((packed)) bits;
  305. uint8_t byte;
  306. } arFunctionsActive;
  307. uint8_t auto_report_period;
  308. public:
  309. LongTimer auto_report_timer;
  310. AutoReportFeatures():auto_report_period(0){
  311. #if defined(AUTO_REPORT)
  312. arFunctionsActive.byte = 0xff;
  313. #else
  314. arFunctionsActive.byte = 0;
  315. #endif //AUTO_REPORT
  316. }
  317. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  318. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  319. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  320. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  321. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  322. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  323. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  324. /// sets the autoreporting timer's period
  325. /// setting it to zero stops the timer
  326. void SetPeriod(uint8_t p){
  327. auto_report_period = p;
  328. if (auto_report_period != 0){
  329. auto_report_timer.start();
  330. } else{
  331. auto_report_timer.stop();
  332. }
  333. }
  334. inline void TimerStart() { auto_report_timer.start(); }
  335. inline bool TimerRunning()const { return auto_report_timer.running(); }
  336. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  337. };
  338. AutoReportFeatures autoReportFeatures;
  339. //===========================================================================
  340. //=============================Routines======================================
  341. //===========================================================================
  342. static bool setTargetedHotend(int code, uint8_t &extruder);
  343. static void print_time_remaining_init();
  344. static void wait_for_heater(long codenum, uint8_t extruder);
  345. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  346. static void gcode_M105(uint8_t extruder);
  347. #ifndef PINDA_THERMISTOR
  348. static void temp_compensation_start();
  349. static void temp_compensation_apply();
  350. #endif
  351. #ifdef PRUSA_SN_SUPPORT
  352. static uint8_t get_PRUSA_SN(char* SN);
  353. #endif //PRUSA_SN_SUPPORT
  354. uint16_t gcode_in_progress = 0;
  355. uint16_t mcode_in_progress = 0;
  356. void serial_echopair_P(const char *s_P, float v)
  357. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  358. void serial_echopair_P(const char *s_P, double v)
  359. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  360. void serial_echopair_P(const char *s_P, unsigned long v)
  361. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  362. void serialprintPGM(const char *str) {
  363. while(uint8_t ch = pgm_read_byte(str)) {
  364. MYSERIAL.write((char)ch);
  365. ++str;
  366. }
  367. }
  368. void serialprintlnPGM(const char *str) {
  369. serialprintPGM(str);
  370. MYSERIAL.println();
  371. }
  372. #ifdef SDSUPPORT
  373. #include "SdFatUtil.h"
  374. int freeMemory() { return SdFatUtil::FreeRam(); }
  375. #else
  376. extern "C" {
  377. extern unsigned int __bss_end;
  378. extern unsigned int __heap_start;
  379. extern void *__brkval;
  380. int freeMemory() {
  381. int free_memory;
  382. if ((int)__brkval == 0)
  383. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  384. else
  385. free_memory = ((int)&free_memory) - ((int)__brkval);
  386. return free_memory;
  387. }
  388. }
  389. #endif //!SDSUPPORT
  390. void setup_killpin()
  391. {
  392. #if defined(KILL_PIN) && KILL_PIN > -1
  393. SET_INPUT(KILL_PIN);
  394. WRITE(KILL_PIN,HIGH);
  395. #endif
  396. }
  397. // Set home pin
  398. void setup_homepin(void)
  399. {
  400. #if defined(HOME_PIN) && HOME_PIN > -1
  401. SET_INPUT(HOME_PIN);
  402. WRITE(HOME_PIN,HIGH);
  403. #endif
  404. }
  405. void setup_photpin()
  406. {
  407. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  408. SET_OUTPUT(PHOTOGRAPH_PIN);
  409. WRITE(PHOTOGRAPH_PIN, LOW);
  410. #endif
  411. }
  412. void setup_powerhold()
  413. {
  414. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  415. SET_OUTPUT(SUICIDE_PIN);
  416. WRITE(SUICIDE_PIN, HIGH);
  417. #endif
  418. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  419. SET_OUTPUT(PS_ON_PIN);
  420. #if defined(PS_DEFAULT_OFF)
  421. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  422. #else
  423. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  424. #endif
  425. #endif
  426. }
  427. void suicide()
  428. {
  429. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  430. SET_OUTPUT(SUICIDE_PIN);
  431. WRITE(SUICIDE_PIN, LOW);
  432. #endif
  433. }
  434. void servo_init()
  435. {
  436. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  437. servos[0].attach(SERVO0_PIN);
  438. #endif
  439. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  440. servos[1].attach(SERVO1_PIN);
  441. #endif
  442. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  443. servos[2].attach(SERVO2_PIN);
  444. #endif
  445. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  446. servos[3].attach(SERVO3_PIN);
  447. #endif
  448. #if (NUM_SERVOS >= 5)
  449. #error "TODO: enter initalisation code for more servos"
  450. #endif
  451. }
  452. bool __attribute__((noinline)) printer_active() {
  453. return IS_SD_PRINTING
  454. || usb_timer.running()
  455. || isPrintPaused
  456. || (custom_message_type == CustomMsg::TempCal)
  457. || saved_printing
  458. || (lcd_commands_type == LcdCommands::Layer1Cal)
  459. || mmu_print_saved
  460. || homing_flag
  461. || mesh_bed_leveling_flag;
  462. }
  463. bool fans_check_enabled = true;
  464. #ifdef TMC2130
  465. void crashdet_stop_and_save_print()
  466. {
  467. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  468. }
  469. void crashdet_restore_print_and_continue()
  470. {
  471. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  472. // babystep_apply();
  473. }
  474. void crashdet_fmt_error(char* buf, uint8_t mask)
  475. {
  476. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  477. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  478. *buf++ = ' ';
  479. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  480. }
  481. void crashdet_detected(uint8_t mask)
  482. {
  483. st_synchronize();
  484. static uint8_t crashDet_counter = 0;
  485. static uint8_t crashDet_axes = 0;
  486. bool automatic_recovery_after_crash = true;
  487. char msg[LCD_WIDTH+1] = "";
  488. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  489. crashDet_counter = 0;
  490. }
  491. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  492. automatic_recovery_after_crash = false;
  493. }
  494. crashDetTimer.start();
  495. crashDet_axes |= mask;
  496. lcd_update_enable(true);
  497. lcd_clear();
  498. lcd_update(2);
  499. if (mask & X_AXIS_MASK)
  500. {
  501. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  502. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  503. }
  504. if (mask & Y_AXIS_MASK)
  505. {
  506. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  507. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  508. }
  509. lcd_update_enable(true);
  510. lcd_update(2);
  511. // prepare the status message with the _current_ axes status
  512. crashdet_fmt_error(msg, mask);
  513. lcd_setstatus(msg);
  514. gcode_G28(true, true, false); //home X and Y
  515. if (automatic_recovery_after_crash) {
  516. enquecommand_P(PSTR("CRASH_RECOVER"));
  517. }else{
  518. setTargetHotend(0, active_extruder);
  519. // notify the user of *all* the axes previously affected, not just the last one
  520. lcd_update_enable(false);
  521. lcd_clear();
  522. crashdet_fmt_error(msg, crashDet_axes);
  523. crashDet_axes = 0;
  524. lcd_print(msg);
  525. // ask whether to resume printing
  526. lcd_set_cursor(0, 1);
  527. lcd_puts_P(_T(MSG_RESUME_PRINT));
  528. lcd_putc('?');
  529. bool yesno = lcd_show_yes_no_and_wait(false);
  530. lcd_update_enable(true);
  531. if (yesno)
  532. {
  533. enquecommand_P(PSTR("CRASH_RECOVER"));
  534. }
  535. else
  536. {
  537. enquecommand_P(PSTR("CRASH_CANCEL"));
  538. }
  539. }
  540. }
  541. void crashdet_recover()
  542. {
  543. crashdet_restore_print_and_continue();
  544. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  545. }
  546. void crashdet_cancel()
  547. {
  548. saved_printing = false;
  549. tmc2130_sg_stop_on_crash = true;
  550. if (saved_printing_type == PRINTING_TYPE_SD) {
  551. lcd_print_stop();
  552. }else if(saved_printing_type == PRINTING_TYPE_USB){
  553. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  554. cmdqueue_reset();
  555. }
  556. }
  557. #endif //TMC2130
  558. void failstats_reset_print()
  559. {
  560. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  561. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  562. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  563. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  564. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  565. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  566. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  567. fsensor_softfail = 0;
  568. #endif
  569. }
  570. void softReset()
  571. {
  572. cli();
  573. wdt_enable(WDTO_15MS);
  574. while(1);
  575. }
  576. #ifdef MESH_BED_LEVELING
  577. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  578. #endif
  579. static void factory_reset_stats(){
  580. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  581. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  582. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  583. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  584. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  585. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  586. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  587. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  588. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  589. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  590. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  591. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  592. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  593. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  594. }
  595. // Factory reset function
  596. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  597. // Level input parameter sets depth of reset
  598. static void factory_reset(char level)
  599. {
  600. lcd_clear();
  601. Sound_MakeCustom(100,0,false);
  602. switch (level) {
  603. case 0: // Level 0: Language reset
  604. lang_reset();
  605. break;
  606. case 1: //Level 1: Reset statistics
  607. factory_reset_stats();
  608. lcd_menu_statistics();
  609. break;
  610. case 2: // Level 2: Prepare for shipping
  611. factory_reset_stats();
  612. // FALLTHRU
  613. case 3: // Level 3: Preparation after being serviced
  614. // Force language selection at the next boot up.
  615. lang_reset();
  616. // Force the "Follow calibration flow" message at the next boot up.
  617. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  618. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  619. farm_disable();
  620. #ifdef FILAMENT_SENSOR
  621. fsensor.setEnabled(true);
  622. fsensor.setAutoLoadEnabled(true, true);
  623. fsensor.setRunoutEnabled(true, true);
  624. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  625. fsensor.setJamDetectionEnabled(true, true);
  626. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  627. #endif //FILAMENT_SENSOR
  628. break;
  629. case 4:
  630. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  631. // Erase EEPROM
  632. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  633. eeprom_update_byte((uint8_t*)i, 0xFF);
  634. menu_progressbar_update(i);
  635. }
  636. menu_progressbar_finish();
  637. softReset();
  638. break;
  639. default:
  640. break;
  641. }
  642. }
  643. extern "C" {
  644. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  645. }
  646. int uart_putchar(char c, FILE *)
  647. {
  648. MYSERIAL.write(c);
  649. return 0;
  650. }
  651. void lcd_splash()
  652. {
  653. lcd_clear(); // clears display and homes screen
  654. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  655. }
  656. void factory_reset()
  657. {
  658. KEEPALIVE_STATE(PAUSED_FOR_USER);
  659. if (!READ(BTN_ENC))
  660. {
  661. _delay_ms(1000);
  662. if (!READ(BTN_ENC))
  663. {
  664. lcd_clear();
  665. lcd_puts_P(PSTR("Factory RESET"));
  666. SET_OUTPUT(BEEPER);
  667. if(eSoundMode!=e_SOUND_MODE_SILENT)
  668. WRITE(BEEPER, HIGH);
  669. while (!READ(BTN_ENC));
  670. WRITE(BEEPER, LOW);
  671. _delay_ms(2000);
  672. char level = reset_menu();
  673. factory_reset(level);
  674. switch (level) {
  675. case 0:
  676. case 1:
  677. case 2:
  678. case 3:
  679. case 4: _delay_ms(0); break;
  680. }
  681. }
  682. }
  683. KEEPALIVE_STATE(IN_HANDLER);
  684. }
  685. void show_fw_version_warnings() {
  686. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  687. switch (FW_DEV_VERSION) {
  688. case(FW_VERSION_ALPHA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware alpha version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_ALPHA c=20 r=8
  689. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware beta version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_BETA c=20 r=8
  690. case(FW_VERSION_DEVEL):
  691. case(FW_VERSION_DEBUG):
  692. lcd_update_enable(false);
  693. lcd_clear();
  694. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  695. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  696. #else
  697. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  698. #endif
  699. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  700. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  701. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  702. lcd_wait_for_click();
  703. break;
  704. // 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
  705. }
  706. lcd_update_enable(true);
  707. }
  708. //! @brief try to check if firmware is on right type of printer
  709. static void check_if_fw_is_on_right_printer(){
  710. #ifdef FILAMENT_SENSOR
  711. if((PRINTER_TYPE == PRINTER_MK3) || (PRINTER_TYPE == PRINTER_MK3S)){
  712. #ifdef IR_SENSOR
  713. if (pat9125_probe()){
  714. lcd_show_fullscreen_message_and_wait_P(_i("MK3S firmware detected on MK3 printer"));}////MSG_MK3S_FIRMWARE_ON_MK3 c=20 r=4
  715. #endif //IR_SENSOR
  716. #ifdef PAT9125
  717. //will return 1 only if IR can detect filament in bondtech extruder so this may fail even when we have IR sensor
  718. const uint8_t ir_detected = fsensor.getFilamentPresent();
  719. if (ir_detected){
  720. lcd_show_fullscreen_message_and_wait_P(_i("MK3 firmware detected on MK3S printer"));}////MSG_MK3_FIRMWARE_ON_MK3S c=20 r=4
  721. #endif //PAT9125
  722. }
  723. #endif //FILAMENT_SENSOR
  724. }
  725. uint8_t check_printer_version()
  726. {
  727. uint8_t version_changed = 0;
  728. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  729. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  730. if (printer_type != PRINTER_TYPE) {
  731. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  732. else version_changed |= 0b10;
  733. }
  734. if (motherboard != MOTHERBOARD) {
  735. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  736. else version_changed |= 0b01;
  737. }
  738. return version_changed;
  739. }
  740. #ifdef BOOTAPP
  741. #include "bootapp.h" //bootloader support
  742. #endif //BOOTAPP
  743. #if (LANG_MODE != 0) //secondary language support
  744. #ifdef XFLASH
  745. // language update from external flash
  746. #define LANGBOOT_BLOCKSIZE 0x1000u
  747. #define LANGBOOT_RAMBUFFER 0x0800
  748. void update_sec_lang_from_external_flash()
  749. {
  750. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  751. {
  752. uint8_t lang = boot_reserved >> 3;
  753. uint8_t state = boot_reserved & 0x07;
  754. lang_table_header_t header;
  755. uint32_t src_addr;
  756. if (lang_get_header(lang, &header, &src_addr))
  757. {
  758. lcd_puts_at_P(1,3,PSTR("Language update."));
  759. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  760. _delay(100);
  761. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  762. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  763. {
  764. cli();
  765. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  766. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  767. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  768. if (state == 0)
  769. {
  770. //TODO - check header integrity
  771. }
  772. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  773. }
  774. else
  775. {
  776. //TODO - check sec lang data integrity
  777. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  778. }
  779. }
  780. }
  781. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  782. }
  783. #ifdef DEBUG_XFLASH
  784. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  785. {
  786. lang_table_header_t header;
  787. uint8_t count = 0;
  788. uint32_t addr = 0x00000;
  789. while (1)
  790. {
  791. printf_P(_n("LANGTABLE%d:"), count);
  792. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  793. if (header.magic != LANG_MAGIC)
  794. {
  795. puts_P(_n("NG!"));
  796. break;
  797. }
  798. puts_P(_n("OK"));
  799. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  800. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  801. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  802. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  803. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  804. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  805. addr += header.size;
  806. codes[count] = header.code;
  807. count ++;
  808. }
  809. return count;
  810. }
  811. void list_sec_lang_from_external_flash()
  812. {
  813. uint16_t codes[8];
  814. uint8_t count = lang_xflash_enum_codes(codes);
  815. printf_P(_n("XFlash lang count = %hhd\n"), count);
  816. }
  817. #endif //DEBUG_XFLASH
  818. #endif //XFLASH
  819. #endif //(LANG_MODE != 0)
  820. static void fw_crash_init()
  821. {
  822. #ifdef XFLASH_DUMP
  823. dump_crash_reason crash_reason;
  824. if(xfdump_check_state(&crash_reason))
  825. {
  826. // always signal to the host that a dump is available for retrieval
  827. puts_P(_N("// action:dump_available"));
  828. #ifdef EMERGENCY_DUMP
  829. if(crash_reason != dump_crash_reason::manual &&
  830. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  831. {
  832. lcd_show_fullscreen_message_and_wait_P(
  833. _n("FW crash detected! "
  834. "You can continue printing. "
  835. "Debug data available for analysis. "
  836. "Contact support to submit details."));
  837. }
  838. #endif
  839. }
  840. #else //XFLASH_DUMP
  841. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  842. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  843. {
  844. lcd_beeper_quick_feedback();
  845. lcd_clear();
  846. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  847. switch(crash_reason)
  848. {
  849. case dump_crash_reason::stack_error:
  850. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  851. break;
  852. case dump_crash_reason::watchdog:
  853. lcd_puts_P(_n("Watchdog timeout"));
  854. break;
  855. case dump_crash_reason::bad_isr:
  856. lcd_puts_P(_n("Bad interrupt"));
  857. break;
  858. default:
  859. lcd_print((uint8_t)crash_reason);
  860. break;
  861. }
  862. lcd_wait_for_click();
  863. }
  864. #endif //XFLASH_DUMP
  865. // prevent crash prompts to reappear once acknowledged
  866. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  867. }
  868. static void xflash_err_msg()
  869. {
  870. puts_P(_n("XFLASH not responding."));
  871. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  872. }
  873. // "Setup" function is called by the Arduino framework on startup.
  874. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  875. // are initialized by the main() routine provided by the Arduino framework.
  876. void setup()
  877. {
  878. timer2_init(); // enables functional millis
  879. mmu_init();
  880. ultralcd_init();
  881. spi_init();
  882. lcd_splash();
  883. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  884. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  885. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  886. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  887. MYSERIAL.begin(BAUDRATE);
  888. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  889. stdout = uartout;
  890. #ifdef XFLASH
  891. bool xflash_success = xflash_init();
  892. uint8_t optiboot_status = 1;
  893. if (xflash_success)
  894. {
  895. optiboot_status = optiboot_xflash_enter();
  896. #if (LANG_MODE != 0) //secondary language support
  897. update_sec_lang_from_external_flash();
  898. #endif //(LANG_MODE != 0)
  899. }
  900. #else
  901. const bool xflash_success = true;
  902. #endif //XFLASH
  903. setup_killpin();
  904. setup_powerhold();
  905. farm_mode_init();
  906. #ifdef TMC2130
  907. if( FarmOrUserECool() ){
  908. //increased extruder current (PFW363)
  909. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  910. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  911. }
  912. #endif //TMC2130
  913. #ifdef PRUSA_SN_SUPPORT
  914. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  915. //SN is valid only if it is NULL terminated and starts with "CZPX".
  916. {
  917. char SN[20];
  918. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  919. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  920. {
  921. if (!get_PRUSA_SN(SN))
  922. {
  923. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  924. puts_P(PSTR("SN updated"));
  925. }
  926. else
  927. puts_P(PSTR("SN update failed"));
  928. }
  929. }
  930. #endif //PRUSA_SN_SUPPORT
  931. #ifndef XFLASH
  932. SERIAL_PROTOCOLLNPGM("start");
  933. #else
  934. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  935. SERIAL_PROTOCOLLNPGM("start");
  936. #endif
  937. SERIAL_ECHO_START;
  938. puts_P(PSTR(" " FW_VERSION_FULL));
  939. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  940. #ifdef DEBUG_SEC_LANG
  941. lang_table_header_t header;
  942. uint32_t src_addr = 0x00000;
  943. if (lang_get_header(1, &header, &src_addr))
  944. {
  945. printf_P(
  946. _n(
  947. " _src_addr = 0x%08lx\n"
  948. " _lt_magic = 0x%08lx %S\n"
  949. " _lt_size = 0x%04x (%d)\n"
  950. " _lt_count = 0x%04x (%d)\n"
  951. " _lt_chsum = 0x%04x\n"
  952. " _lt_code = 0x%04x (%c%c)\n"
  953. " _lt_resv1 = 0x%08lx\n"
  954. ),
  955. src_addr,
  956. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  957. header.size, header.size,
  958. header.count, header.count,
  959. header.checksum,
  960. header.code, header.code >> 8, header.code & 0xff,
  961. header.signature
  962. );
  963. #if 0
  964. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  965. for (uint16_t i = 0; i < 1024; i++)
  966. {
  967. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  968. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  969. if ((i % 16) == 15) putchar('\n');
  970. }
  971. #endif
  972. uint16_t sum = 0;
  973. for (uint16_t i = 0; i < header.size; i++)
  974. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  975. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  976. sum -= header.checksum; //subtract checksum
  977. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  978. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  979. if (sum == header.checksum)
  980. puts_P(_n("Checksum OK"));
  981. else
  982. puts_P(_n("Checksum NG"));
  983. }
  984. else
  985. puts_P(_n("lang_get_header failed!"));
  986. #if 0
  987. for (uint16_t i = 0; i < 1024*10; i++)
  988. {
  989. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  990. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  991. if ((i % 16) == 15) putchar('\n');
  992. }
  993. #endif
  994. #if 0
  995. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  996. for (int i = 0; i < 4096; ++i) {
  997. int b = eeprom_read_byte((unsigned char*)i);
  998. if (b != 255) {
  999. SERIAL_ECHO(i);
  1000. SERIAL_ECHO(":");
  1001. SERIAL_ECHO(b);
  1002. SERIAL_ECHOLN("");
  1003. }
  1004. }
  1005. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  1006. #endif
  1007. #endif //DEBUG_SEC_LANG
  1008. // Check startup - does nothing if bootloader sets MCUSR to 0
  1009. byte mcu = MCUSR;
  1010. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  1011. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  1012. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  1013. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1014. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1015. if (mcu & 1) puts_P(MSG_POWERUP);
  1016. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1017. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1018. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1019. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1020. MCUSR = 0;
  1021. //SERIAL_ECHORPGM(MSG_MARLIN);
  1022. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1023. #ifdef STRING_VERSION_CONFIG_H
  1024. #ifdef STRING_CONFIG_H_AUTHOR
  1025. SERIAL_ECHO_START;
  1026. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1027. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1028. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1029. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1030. SERIAL_ECHOPGM("Compiled: ");
  1031. SERIAL_ECHOLNPGM(__DATE__);
  1032. #endif
  1033. #endif
  1034. SERIAL_ECHO_START;
  1035. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1036. SERIAL_ECHO(freeMemory());
  1037. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1038. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1039. //lcd_update_enable(false); // why do we need this?? - andre
  1040. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1041. bool previous_settings_retrieved = false;
  1042. uint8_t hw_changed = check_printer_version();
  1043. 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
  1044. previous_settings_retrieved = Config_RetrieveSettings();
  1045. }
  1046. else { //printer version was changed so use default settings
  1047. Config_ResetDefault();
  1048. }
  1049. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1050. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1051. // performed inside the soft_pwm_isr)
  1052. SdFatUtil::set_stack_guard();
  1053. // Initialize pwm/temperature loops
  1054. soft_pwm_init();
  1055. temp_mgr_init();
  1056. #ifdef EXTRUDER_ALTFAN_DETECT
  1057. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1058. if (extruder_altfan_detect())
  1059. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1060. else
  1061. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1062. #endif //EXTRUDER_ALTFAN_DETECT
  1063. plan_init(); // Initialize planner;
  1064. factory_reset();
  1065. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1066. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1067. {
  1068. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1069. // where all the EEPROM entries are set to 0x0ff.
  1070. // Once a firmware boots up, it forces at least a language selection, which changes
  1071. // EEPROM_LANG to number lower than 0x0ff.
  1072. // 1) Set a high power mode.
  1073. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1074. #ifdef TMC2130
  1075. tmc2130_mode = TMC2130_MODE_NORMAL;
  1076. #endif //TMC2130
  1077. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1078. }
  1079. lcd_encoder_diff=0;
  1080. #ifdef TMC2130
  1081. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1082. if (silentMode == 0xff) silentMode = 0;
  1083. tmc2130_mode = TMC2130_MODE_NORMAL;
  1084. if (lcd_crash_detect_enabled() && !farm_mode)
  1085. {
  1086. lcd_crash_detect_enable();
  1087. puts_P(_N("CrashDetect ENABLED!"));
  1088. }
  1089. else
  1090. {
  1091. lcd_crash_detect_disable();
  1092. puts_P(_N("CrashDetect DISABLED"));
  1093. }
  1094. #ifdef TMC2130_LINEARITY_CORRECTION
  1095. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1096. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1097. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1098. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1099. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1100. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1101. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1102. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1103. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1104. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1105. #endif //TMC2130_LINEARITY_CORRECTION
  1106. #ifdef TMC2130_VARIABLE_RESOLUTION
  1107. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1108. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1109. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1110. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1111. #else //TMC2130_VARIABLE_RESOLUTION
  1112. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1113. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1114. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1115. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1116. #endif //TMC2130_VARIABLE_RESOLUTION
  1117. #endif //TMC2130
  1118. st_init(); // Initialize stepper, this enables interrupts!
  1119. #ifdef TMC2130
  1120. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1121. update_mode_profile();
  1122. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1123. #endif //TMC2130
  1124. #ifdef PSU_Delta
  1125. init_force_z(); // ! important for correct Z-axis initialization
  1126. #endif // PSU_Delta
  1127. setup_photpin();
  1128. #if 0
  1129. servo_init();
  1130. #endif
  1131. // Reset the machine correction matrix.
  1132. // It does not make sense to load the correction matrix until the machine is homed.
  1133. world2machine_reset();
  1134. // Initialize current_position accounting for software endstops to
  1135. // avoid unexpected initial shifts on the first move
  1136. clamp_to_software_endstops(current_position);
  1137. plan_set_position_curposXYZE();
  1138. // Show the xflash error message now that serial, lcd and encoder are available
  1139. if (!xflash_success)
  1140. xflash_err_msg();
  1141. #ifdef FILAMENT_SENSOR
  1142. fsensor.init();
  1143. #endif //FILAMENT_SENSOR
  1144. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1145. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1146. #endif
  1147. setup_homepin();
  1148. #if defined(Z_AXIS_ALWAYS_ON)
  1149. enable_z();
  1150. #endif
  1151. // The farm monitoring SW may accidentally expect
  1152. // 2 messages of "printer started" to consider a printer working.
  1153. prusa_statistics(8);
  1154. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1155. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1156. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1157. // but this times out if a blocking dialog is shown in setup().
  1158. card.initsd();
  1159. #ifdef DEBUG_SD_SPEED_TEST
  1160. if (card.cardOK)
  1161. {
  1162. uint8_t* buff = (uint8_t*)block_buffer;
  1163. uint32_t block = 0;
  1164. uint32_t sumr = 0;
  1165. uint32_t sumw = 0;
  1166. for (int i = 0; i < 1024; i++)
  1167. {
  1168. uint32_t u = _micros();
  1169. bool res = card.card.readBlock(i, buff);
  1170. u = _micros() - u;
  1171. if (res)
  1172. {
  1173. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1174. sumr += u;
  1175. u = _micros();
  1176. res = card.card.writeBlock(i, buff);
  1177. u = _micros() - u;
  1178. if (res)
  1179. {
  1180. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1181. sumw += u;
  1182. }
  1183. else
  1184. {
  1185. printf_P(PSTR("writeBlock %4d error\n"), i);
  1186. break;
  1187. }
  1188. }
  1189. else
  1190. {
  1191. printf_P(PSTR("readBlock %4d error\n"), i);
  1192. break;
  1193. }
  1194. }
  1195. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1196. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1197. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1198. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1199. }
  1200. else
  1201. printf_P(PSTR("Card NG!\n"));
  1202. #endif //DEBUG_SD_SPEED_TEST
  1203. eeprom_init();
  1204. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1205. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1206. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1207. #if (LANG_MODE != 0) //secondary language support
  1208. #ifdef DEBUG_XFLASH
  1209. XFLASH_SPI_ENTER();
  1210. uint8_t uid[8]; // 64bit unique id
  1211. xflash_rd_uid(uid);
  1212. puts_P(_n("XFLASH UID="));
  1213. for (uint8_t i = 0; i < 8; i ++)
  1214. printf_P(PSTR("%02x"), uid[i]);
  1215. putchar('\n');
  1216. list_sec_lang_from_external_flash();
  1217. #endif //DEBUG_XFLASH
  1218. // lang_reset();
  1219. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1220. lcd_language();
  1221. #ifdef DEBUG_SEC_LANG
  1222. uint16_t sec_lang_code = lang_get_code(1);
  1223. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1224. 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);
  1225. lang_print_sec_lang(uartout);
  1226. #endif //DEBUG_SEC_LANG
  1227. #endif //(LANG_MODE != 0)
  1228. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1229. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1230. }
  1231. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1232. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1233. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1234. int16_t z_shift = 0;
  1235. for (uint8_t i = 0; i < 5; i++) {
  1236. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1237. }
  1238. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1239. }
  1240. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1241. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1242. }
  1243. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1244. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1245. }
  1246. //mbl_mode_init();
  1247. mbl_settings_init();
  1248. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1249. if (SilentModeMenu_MMU == 255) {
  1250. SilentModeMenu_MMU = 1;
  1251. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1252. }
  1253. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1254. setup_fan_interrupt();
  1255. #endif //DEBUG_DISABLE_FANCHECK
  1256. #ifndef DEBUG_DISABLE_STARTMSGS
  1257. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1258. if (!farm_mode) {
  1259. check_if_fw_is_on_right_printer();
  1260. show_fw_version_warnings();
  1261. }
  1262. switch (hw_changed) {
  1263. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1264. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1265. case(0b01):
  1266. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1267. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1268. break;
  1269. case(0b10):
  1270. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1271. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1272. break;
  1273. case(0b11):
  1274. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1275. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1276. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1277. break;
  1278. default: break; //no change, show no message
  1279. }
  1280. if (!previous_settings_retrieved) {
  1281. 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
  1282. Config_StoreSettings();
  1283. }
  1284. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1285. lcd_wizard(WizState::Run);
  1286. }
  1287. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1288. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1289. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1290. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1291. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1292. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1293. // Show the message.
  1294. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1295. }
  1296. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1297. // Show the message.
  1298. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1299. lcd_update_enable(true);
  1300. }
  1301. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1302. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1303. lcd_update_enable(true);
  1304. }
  1305. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1306. // Show the message.
  1307. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1308. }
  1309. }
  1310. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1311. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1312. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1313. update_current_firmware_version_to_eeprom();
  1314. lcd_selftest();
  1315. }
  1316. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1317. KEEPALIVE_STATE(IN_PROCESS);
  1318. #endif //DEBUG_DISABLE_STARTMSGS
  1319. lcd_update_enable(true);
  1320. lcd_clear();
  1321. lcd_update(2);
  1322. // Store the currently running firmware into an eeprom,
  1323. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1324. update_current_firmware_version_to_eeprom();
  1325. #ifdef TMC2130
  1326. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1327. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1328. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1329. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1330. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1331. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1332. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1333. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1334. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1335. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1336. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1337. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1338. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1339. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1340. #endif //TMC2130
  1341. // report crash failures
  1342. fw_crash_init();
  1343. #ifdef UVLO_SUPPORT
  1344. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1345. /*
  1346. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1347. else {
  1348. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1349. lcd_update_enable(true);
  1350. lcd_update(2);
  1351. lcd_setstatuspgm(MSG_WELCOME);
  1352. }
  1353. */
  1354. manage_heater(); // Update temperatures
  1355. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1356. 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));
  1357. #endif
  1358. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1359. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1360. puts_P(_N("Automatic recovery!"));
  1361. #endif
  1362. recover_print(1);
  1363. }
  1364. else{
  1365. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1366. puts_P(_N("Normal recovery!"));
  1367. #endif
  1368. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1369. else {
  1370. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1371. lcd_update_enable(true);
  1372. lcd_update(2);
  1373. lcd_setstatuspgm(MSG_WELCOME);
  1374. }
  1375. }
  1376. }
  1377. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1378. // the entire state machine initialized.
  1379. setup_uvlo_interrupt();
  1380. #endif //UVLO_SUPPORT
  1381. fCheckModeInit();
  1382. fSetMmuMode(mmu_enabled);
  1383. KEEPALIVE_STATE(NOT_BUSY);
  1384. #ifdef WATCHDOG
  1385. wdt_enable(WDTO_4S);
  1386. #ifdef EMERGENCY_HANDLERS
  1387. WDTCSR |= (1 << WDIE);
  1388. #endif //EMERGENCY_HANDLERS
  1389. #endif //WATCHDOG
  1390. }
  1391. static inline void crash_and_burn(dump_crash_reason reason)
  1392. {
  1393. WRITE(BEEPER, HIGH);
  1394. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1395. #ifdef EMERGENCY_DUMP
  1396. xfdump_full_dump_and_reset(reason);
  1397. #elif defined(EMERGENCY_SERIAL_DUMP)
  1398. if(emergency_serial_dump)
  1399. serial_dump_and_reset(reason);
  1400. #endif
  1401. softReset();
  1402. }
  1403. #ifdef EMERGENCY_HANDLERS
  1404. #ifdef WATCHDOG
  1405. ISR(WDT_vect)
  1406. {
  1407. crash_and_burn(dump_crash_reason::watchdog);
  1408. }
  1409. #endif
  1410. ISR(BADISR_vect)
  1411. {
  1412. crash_and_burn(dump_crash_reason::bad_isr);
  1413. }
  1414. #endif //EMERGENCY_HANDLERS
  1415. void stack_error() {
  1416. crash_and_burn(dump_crash_reason::stack_error);
  1417. }
  1418. /**
  1419. * Output autoreport values according to features requested in M155
  1420. */
  1421. #if defined(AUTO_REPORT)
  1422. void host_autoreport()
  1423. {
  1424. if (autoReportFeatures.TimerExpired())
  1425. {
  1426. if(autoReportFeatures.Temp()){
  1427. gcode_M105(active_extruder);
  1428. }
  1429. if(autoReportFeatures.Pos()){
  1430. gcode_M114();
  1431. }
  1432. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1433. if(autoReportFeatures.Fans()){
  1434. gcode_M123();
  1435. }
  1436. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1437. autoReportFeatures.TimerStart();
  1438. }
  1439. }
  1440. #endif //AUTO_REPORT
  1441. /**
  1442. * Output a "busy" message at regular intervals
  1443. * while the machine is not accepting commands.
  1444. */
  1445. void host_keepalive() {
  1446. #ifndef HOST_KEEPALIVE_FEATURE
  1447. return;
  1448. #endif //HOST_KEEPALIVE_FEATURE
  1449. if (farm_mode) return;
  1450. long ms = _millis();
  1451. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1452. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1453. switch (busy_state) {
  1454. case IN_HANDLER:
  1455. case IN_PROCESS:
  1456. SERIAL_ECHO_START;
  1457. SERIAL_ECHOLNPGM("busy: processing");
  1458. break;
  1459. case PAUSED_FOR_USER:
  1460. SERIAL_ECHO_START;
  1461. SERIAL_ECHOLNPGM("busy: paused for user");
  1462. break;
  1463. case PAUSED_FOR_INPUT:
  1464. SERIAL_ECHO_START;
  1465. SERIAL_ECHOLNPGM("busy: paused for input");
  1466. break;
  1467. default:
  1468. break;
  1469. }
  1470. }
  1471. prev_busy_signal_ms = ms;
  1472. }
  1473. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1474. // Before loop(), the setup() function is called by the main() routine.
  1475. void loop()
  1476. {
  1477. // Reset a previously aborted command, we can now start processing motion again
  1478. planner_aborted = false;
  1479. if(Stopped) {
  1480. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1481. // Signal to the host that we're currently busy waiting for supervision.
  1482. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1483. } else {
  1484. // Printer is available for processing, reset state
  1485. KEEPALIVE_STATE(NOT_BUSY);
  1486. }
  1487. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1488. usb_timer.start();
  1489. }
  1490. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1491. ;
  1492. }
  1493. #ifdef PRUSA_M28
  1494. if (prusa_sd_card_upload)
  1495. {
  1496. //we read byte-by byte
  1497. serial_read_stream();
  1498. }
  1499. else
  1500. #endif
  1501. {
  1502. get_command();
  1503. #ifdef SDSUPPORT
  1504. card.checkautostart(false);
  1505. #endif
  1506. if(buflen)
  1507. {
  1508. cmdbuffer_front_already_processed = false;
  1509. #ifdef SDSUPPORT
  1510. if(card.saving)
  1511. {
  1512. // Saving a G-code file onto an SD-card is in progress.
  1513. // Saving starts with M28, saving until M29 is seen.
  1514. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1515. card.write_command(CMDBUFFER_CURRENT_STRING);
  1516. if(card.logging)
  1517. process_commands();
  1518. else
  1519. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1520. } else {
  1521. card.closefile();
  1522. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1523. }
  1524. } else {
  1525. process_commands();
  1526. }
  1527. #else
  1528. process_commands();
  1529. #endif //SDSUPPORT
  1530. if (! cmdbuffer_front_already_processed && buflen)
  1531. {
  1532. // ptr points to the start of the block currently being processed.
  1533. // The first character in the block is the block type.
  1534. char *ptr = cmdbuffer + bufindr;
  1535. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1536. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1537. union {
  1538. struct {
  1539. char lo;
  1540. char hi;
  1541. } lohi;
  1542. uint16_t value;
  1543. } sdlen;
  1544. sdlen.value = 0;
  1545. {
  1546. // This block locks the interrupts globally for 3.25 us,
  1547. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1548. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1549. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1550. cli();
  1551. // Reset the command to something, which will be ignored by the power panic routine,
  1552. // so this buffer length will not be counted twice.
  1553. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1554. // Extract the current buffer length.
  1555. sdlen.lohi.lo = *ptr ++;
  1556. sdlen.lohi.hi = *ptr;
  1557. // and pass it to the planner queue.
  1558. planner_add_sd_length(sdlen.value);
  1559. sei();
  1560. }
  1561. }
  1562. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1563. cli();
  1564. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1565. // and one for each command to previous block in the planner queue.
  1566. planner_add_sd_length(1);
  1567. sei();
  1568. }
  1569. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1570. // this block's SD card length will not be counted twice as its command type has been replaced
  1571. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1572. cmdqueue_pop_front();
  1573. }
  1574. host_keepalive();
  1575. }
  1576. }
  1577. //check heater every n milliseconds
  1578. manage_heater();
  1579. manage_inactivity(isPrintPaused);
  1580. checkHitEndstops();
  1581. lcd_update(0);
  1582. #ifdef TMC2130
  1583. tmc2130_check_overtemp();
  1584. if (tmc2130_sg_crash)
  1585. {
  1586. uint8_t crash = tmc2130_sg_crash;
  1587. tmc2130_sg_crash = 0;
  1588. // crashdet_stop_and_save_print();
  1589. switch (crash)
  1590. {
  1591. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1592. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1593. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1594. }
  1595. }
  1596. #endif //TMC2130
  1597. mmu_loop();
  1598. }
  1599. #define DEFINE_PGM_READ_ANY(type, reader) \
  1600. static inline type pgm_read_any(const type *p) \
  1601. { return pgm_read_##reader##_near(p); }
  1602. DEFINE_PGM_READ_ANY(float, float);
  1603. DEFINE_PGM_READ_ANY(signed char, byte);
  1604. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1605. static const PROGMEM type array##_P[3] = \
  1606. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1607. static inline type array(uint8_t axis) \
  1608. { return pgm_read_any(&array##_P[axis]); } \
  1609. type array##_ext(uint8_t axis) \
  1610. { return pgm_read_any(&array##_P[axis]); }
  1611. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1612. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1613. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1614. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1615. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1616. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1617. static void axis_is_at_home(uint8_t axis) {
  1618. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1619. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1620. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1621. }
  1622. //! @return original feedmultiply
  1623. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1624. saved_feedrate = feedrate;
  1625. int l_feedmultiply = feedmultiply;
  1626. feedmultiply = 100;
  1627. previous_millis_cmd.start();
  1628. enable_endstops(enable_endstops_now);
  1629. return l_feedmultiply;
  1630. }
  1631. //! @param original_feedmultiply feedmultiply to restore
  1632. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1633. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1634. enable_endstops(false);
  1635. #endif
  1636. feedrate = saved_feedrate;
  1637. feedmultiply = original_feedmultiply;
  1638. previous_millis_cmd.start();
  1639. }
  1640. #ifdef ENABLE_AUTO_BED_LEVELING
  1641. #ifdef AUTO_BED_LEVELING_GRID
  1642. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1643. {
  1644. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1645. planeNormal.debug("planeNormal");
  1646. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1647. //bedLevel.debug("bedLevel");
  1648. //plan_bed_level_matrix.debug("bed level before");
  1649. //vector_3 uncorrected_position = plan_get_position_mm();
  1650. //uncorrected_position.debug("position before");
  1651. vector_3 corrected_position = plan_get_position();
  1652. // corrected_position.debug("position after");
  1653. current_position[X_AXIS] = corrected_position.x;
  1654. current_position[Y_AXIS] = corrected_position.y;
  1655. current_position[Z_AXIS] = corrected_position.z;
  1656. // put the bed at 0 so we don't go below it.
  1657. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1658. plan_set_position_curposXYZE();
  1659. }
  1660. #else // not AUTO_BED_LEVELING_GRID
  1661. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1662. plan_bed_level_matrix.set_to_identity();
  1663. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1664. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1665. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1666. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1667. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1668. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1669. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1670. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1671. vector_3 corrected_position = plan_get_position();
  1672. current_position[X_AXIS] = corrected_position.x;
  1673. current_position[Y_AXIS] = corrected_position.y;
  1674. current_position[Z_AXIS] = corrected_position.z;
  1675. // put the bed at 0 so we don't go below it.
  1676. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1677. plan_set_position_curposXYZE();
  1678. }
  1679. #endif // AUTO_BED_LEVELING_GRID
  1680. static void run_z_probe() {
  1681. plan_bed_level_matrix.set_to_identity();
  1682. feedrate = homing_feedrate[Z_AXIS];
  1683. // move down until you find the bed
  1684. float zPosition = -10;
  1685. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1686. st_synchronize();
  1687. // we have to let the planner know where we are right now as it is not where we said to go.
  1688. zPosition = st_get_position_mm(Z_AXIS);
  1689. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1690. // move up the retract distance
  1691. zPosition += home_retract_mm(Z_AXIS);
  1692. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1693. st_synchronize();
  1694. // move back down slowly to find bed
  1695. feedrate = homing_feedrate[Z_AXIS]/4;
  1696. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1697. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1698. st_synchronize();
  1699. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1700. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1701. plan_set_position_curposXYZE();
  1702. }
  1703. static void do_blocking_move_to(float x, float y, float z) {
  1704. float oldFeedRate = feedrate;
  1705. feedrate = homing_feedrate[Z_AXIS];
  1706. current_position[Z_AXIS] = z;
  1707. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1708. st_synchronize();
  1709. feedrate = XY_TRAVEL_SPEED;
  1710. current_position[X_AXIS] = x;
  1711. current_position[Y_AXIS] = y;
  1712. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1713. st_synchronize();
  1714. feedrate = oldFeedRate;
  1715. }
  1716. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1717. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1718. }
  1719. /// Probe bed height at position (x,y), returns the measured z value
  1720. static float probe_pt(float x, float y, float z_before) {
  1721. // move to right place
  1722. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1723. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1724. run_z_probe();
  1725. float measured_z = current_position[Z_AXIS];
  1726. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1727. SERIAL_PROTOCOLPGM(" x: ");
  1728. SERIAL_PROTOCOL(x);
  1729. SERIAL_PROTOCOLPGM(" y: ");
  1730. SERIAL_PROTOCOL(y);
  1731. SERIAL_PROTOCOLPGM(" z: ");
  1732. SERIAL_PROTOCOL(measured_z);
  1733. SERIAL_PROTOCOLPGM("\n");
  1734. return measured_z;
  1735. }
  1736. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1737. #ifdef LIN_ADVANCE
  1738. /**
  1739. * M900: Set and/or Get advance K factor
  1740. *
  1741. * K<factor> Set advance K factor
  1742. */
  1743. inline void gcode_M900() {
  1744. float newK = code_seen('K') ? code_value_float() : -2;
  1745. #ifdef LA_NOCOMPAT
  1746. if (newK >= 0 && newK < LA_K_MAX)
  1747. extruder_advance_K = newK;
  1748. else
  1749. SERIAL_ECHOLNPGM("K out of allowed range!");
  1750. #else
  1751. if (newK == 0)
  1752. {
  1753. extruder_advance_K = 0;
  1754. la10c_reset();
  1755. }
  1756. else
  1757. {
  1758. newK = la10c_value(newK);
  1759. if (newK < 0)
  1760. SERIAL_ECHOLNPGM("K out of allowed range!");
  1761. else
  1762. extruder_advance_K = newK;
  1763. }
  1764. #endif
  1765. SERIAL_ECHO_START;
  1766. SERIAL_ECHOPGM("Advance K=");
  1767. SERIAL_ECHOLN(extruder_advance_K);
  1768. }
  1769. #endif // LIN_ADVANCE
  1770. bool check_commands() {
  1771. bool end_command_found = false;
  1772. while (buflen)
  1773. {
  1774. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1775. if (!cmdbuffer_front_already_processed)
  1776. cmdqueue_pop_front();
  1777. cmdbuffer_front_already_processed = false;
  1778. }
  1779. return end_command_found;
  1780. }
  1781. // raise_z_above: slowly raise Z to the requested height
  1782. //
  1783. // contrarily to a simple move, this function will carefully plan a move
  1784. // when the current Z position is unknown. In such cases, stallguard is
  1785. // enabled and will prevent prolonged pushing against the Z tops
  1786. void raise_z_above(float target, bool plan)
  1787. {
  1788. if (current_position[Z_AXIS] >= target)
  1789. return;
  1790. // Z needs raising
  1791. current_position[Z_AXIS] = target;
  1792. clamp_to_software_endstops(current_position);
  1793. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1794. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1795. #else
  1796. bool z_min_endstop = false;
  1797. #endif
  1798. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1799. {
  1800. // current position is known or very low, it's safe to raise Z
  1801. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1802. return;
  1803. }
  1804. // ensure Z is powered in normal mode to overcome initial load
  1805. enable_z();
  1806. st_synchronize();
  1807. // rely on crashguard to limit damage
  1808. bool z_endstop_enabled = enable_z_endstop(true);
  1809. #ifdef TMC2130
  1810. tmc2130_home_enter(Z_AXIS_MASK);
  1811. #endif //TMC2130
  1812. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1813. st_synchronize();
  1814. #ifdef TMC2130
  1815. if (endstop_z_hit_on_purpose())
  1816. {
  1817. // not necessarily exact, but will avoid further vertical moves
  1818. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1819. plan_set_position_curposXYZE();
  1820. }
  1821. tmc2130_home_exit();
  1822. #endif //TMC2130
  1823. enable_z_endstop(z_endstop_enabled);
  1824. }
  1825. #ifdef TMC2130
  1826. bool calibrate_z_auto()
  1827. {
  1828. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1829. lcd_clear();
  1830. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1831. bool endstops_enabled = enable_endstops(true);
  1832. int axis_up_dir = -home_dir(Z_AXIS);
  1833. tmc2130_home_enter(Z_AXIS_MASK);
  1834. current_position[Z_AXIS] = 0;
  1835. plan_set_position_curposXYZE();
  1836. set_destination_to_current();
  1837. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1838. feedrate = homing_feedrate[Z_AXIS];
  1839. plan_buffer_line_destinationXYZE(feedrate / 60);
  1840. st_synchronize();
  1841. // current_position[axis] = 0;
  1842. // plan_set_position_curposXYZE();
  1843. tmc2130_home_exit();
  1844. enable_endstops(false);
  1845. current_position[Z_AXIS] = 0;
  1846. plan_set_position_curposXYZE();
  1847. set_destination_to_current();
  1848. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1849. feedrate = homing_feedrate[Z_AXIS] / 2;
  1850. plan_buffer_line_destinationXYZE(feedrate / 60);
  1851. st_synchronize();
  1852. enable_endstops(endstops_enabled);
  1853. if (PRINTER_TYPE == PRINTER_MK3) {
  1854. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1855. }
  1856. else {
  1857. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1858. }
  1859. plan_set_position_curposXYZE();
  1860. return true;
  1861. }
  1862. #endif //TMC2130
  1863. #ifdef TMC2130
  1864. static void check_Z_crash(void)
  1865. {
  1866. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1867. FORCE_HIGH_POWER_END;
  1868. current_position[Z_AXIS] = 0;
  1869. plan_set_position_curposXYZE();
  1870. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1871. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1872. st_synchronize();
  1873. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1874. }
  1875. }
  1876. #endif //TMC2130
  1877. #ifdef TMC2130
  1878. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1879. #else
  1880. void homeaxis(uint8_t axis, uint8_t cnt)
  1881. #endif //TMC2130
  1882. {
  1883. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1884. #define HOMEAXIS_DO(LETTER) \
  1885. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1886. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1887. {
  1888. int axis_home_dir = home_dir(axis);
  1889. feedrate = homing_feedrate[axis];
  1890. #ifdef TMC2130
  1891. tmc2130_home_enter(X_AXIS_MASK << axis);
  1892. #endif //TMC2130
  1893. // Move away a bit, so that the print head does not touch the end position,
  1894. // and the following movement to endstop has a chance to achieve the required velocity
  1895. // for the stall guard to work.
  1896. current_position[axis] = 0;
  1897. plan_set_position_curposXYZE();
  1898. set_destination_to_current();
  1899. // destination[axis] = 11.f;
  1900. destination[axis] = -3.f * axis_home_dir;
  1901. plan_buffer_line_destinationXYZE(feedrate/60);
  1902. st_synchronize();
  1903. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1904. endstops_hit_on_purpose();
  1905. enable_endstops(false);
  1906. current_position[axis] = 0;
  1907. plan_set_position_curposXYZE();
  1908. destination[axis] = 1. * axis_home_dir;
  1909. plan_buffer_line_destinationXYZE(feedrate/60);
  1910. st_synchronize();
  1911. // Now continue to move up to the left end stop with the collision detection enabled.
  1912. enable_endstops(true);
  1913. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1914. plan_buffer_line_destinationXYZE(feedrate/60);
  1915. st_synchronize();
  1916. for (uint8_t i = 0; i < cnt; i++)
  1917. {
  1918. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1919. endstops_hit_on_purpose();
  1920. enable_endstops(false);
  1921. current_position[axis] = 0;
  1922. plan_set_position_curposXYZE();
  1923. destination[axis] = -10.f * axis_home_dir;
  1924. plan_buffer_line_destinationXYZE(feedrate/60);
  1925. st_synchronize();
  1926. endstops_hit_on_purpose();
  1927. // Now move left up to the collision, this time with a repeatable velocity.
  1928. enable_endstops(true);
  1929. destination[axis] = 11.f * axis_home_dir;
  1930. #ifdef TMC2130
  1931. feedrate = homing_feedrate[axis];
  1932. #else //TMC2130
  1933. feedrate = homing_feedrate[axis] / 2;
  1934. #endif //TMC2130
  1935. plan_buffer_line_destinationXYZE(feedrate/60);
  1936. st_synchronize();
  1937. #ifdef TMC2130
  1938. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1939. if (pstep) pstep[i] = mscnt >> 4;
  1940. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1941. #endif //TMC2130
  1942. }
  1943. endstops_hit_on_purpose();
  1944. enable_endstops(false);
  1945. #ifdef TMC2130
  1946. uint8_t orig = tmc2130_home_origin[axis];
  1947. uint8_t back = tmc2130_home_bsteps[axis];
  1948. if (tmc2130_home_enabled && (orig <= 63))
  1949. {
  1950. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1951. if (back > 0)
  1952. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1953. }
  1954. else
  1955. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1956. tmc2130_home_exit();
  1957. #endif //TMC2130
  1958. axis_is_at_home(axis);
  1959. axis_known_position[axis] = true;
  1960. // Move from minimum
  1961. #ifdef TMC2130
  1962. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1963. #else //TMC2130
  1964. float dist = - axis_home_dir * 0.01f * 64;
  1965. #endif //TMC2130
  1966. current_position[axis] -= dist;
  1967. plan_set_position_curposXYZE();
  1968. current_position[axis] += dist;
  1969. destination[axis] = current_position[axis];
  1970. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1971. st_synchronize();
  1972. feedrate = 0.0;
  1973. }
  1974. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1975. {
  1976. #ifdef TMC2130
  1977. FORCE_HIGH_POWER_START;
  1978. #endif
  1979. int axis_home_dir = home_dir(axis);
  1980. current_position[axis] = 0;
  1981. plan_set_position_curposXYZE();
  1982. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1983. feedrate = homing_feedrate[axis];
  1984. plan_buffer_line_destinationXYZE(feedrate/60);
  1985. st_synchronize();
  1986. #ifdef TMC2130
  1987. check_Z_crash();
  1988. #endif //TMC2130
  1989. current_position[axis] = 0;
  1990. plan_set_position_curposXYZE();
  1991. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1992. plan_buffer_line_destinationXYZE(feedrate/60);
  1993. st_synchronize();
  1994. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1995. feedrate = homing_feedrate[axis]/2 ;
  1996. plan_buffer_line_destinationXYZE(feedrate/60);
  1997. st_synchronize();
  1998. #ifdef TMC2130
  1999. check_Z_crash();
  2000. #endif //TMC2130
  2001. axis_is_at_home(axis);
  2002. destination[axis] = current_position[axis];
  2003. feedrate = 0.0;
  2004. endstops_hit_on_purpose();
  2005. axis_known_position[axis] = true;
  2006. #ifdef TMC2130
  2007. FORCE_HIGH_POWER_END;
  2008. #endif
  2009. }
  2010. enable_endstops(endstops_enabled);
  2011. }
  2012. /**/
  2013. void home_xy()
  2014. {
  2015. set_destination_to_current();
  2016. homeaxis(X_AXIS);
  2017. homeaxis(Y_AXIS);
  2018. plan_set_position_curposXYZE();
  2019. endstops_hit_on_purpose();
  2020. }
  2021. void refresh_cmd_timeout(void)
  2022. {
  2023. previous_millis_cmd.start();
  2024. }
  2025. #ifdef FWRETRACT
  2026. void retract(bool retracting, bool swapretract = false) {
  2027. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2028. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2029. // position, which requires a sync
  2030. if(retracting && !retracted[active_extruder]) {
  2031. st_synchronize();
  2032. set_destination_to_current();
  2033. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2034. plan_set_e_position(current_position[E_AXIS]);
  2035. float oldFeedrate = feedrate;
  2036. feedrate=cs.retract_feedrate*60;
  2037. retracted[active_extruder]=true;
  2038. prepare_move();
  2039. if(cs.retract_zlift) {
  2040. st_synchronize();
  2041. current_position[Z_AXIS]-=cs.retract_zlift;
  2042. plan_set_position_curposXYZE();
  2043. prepare_move();
  2044. }
  2045. feedrate = oldFeedrate;
  2046. } else if(!retracting && retracted[active_extruder]) {
  2047. st_synchronize();
  2048. set_destination_to_current();
  2049. float oldFeedrate = feedrate;
  2050. feedrate=cs.retract_recover_feedrate*60;
  2051. if(cs.retract_zlift) {
  2052. current_position[Z_AXIS]+=cs.retract_zlift;
  2053. plan_set_position_curposXYZE();
  2054. prepare_move();
  2055. st_synchronize();
  2056. }
  2057. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2058. plan_set_e_position(current_position[E_AXIS]);
  2059. retracted[active_extruder]=false;
  2060. prepare_move();
  2061. feedrate = oldFeedrate;
  2062. }
  2063. } //retract
  2064. #endif //FWRETRACT
  2065. #ifdef TMC2130
  2066. void force_high_power_mode(bool start_high_power_section) {
  2067. #ifdef PSU_Delta
  2068. if (start_high_power_section == true) enable_force_z();
  2069. #endif //PSU_Delta
  2070. uint8_t silent;
  2071. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2072. if (silent == 1) {
  2073. //we are in silent mode, set to normal mode to enable crash detection
  2074. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2075. st_synchronize();
  2076. cli();
  2077. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2078. update_mode_profile();
  2079. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2080. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2081. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2082. st_reset_timer();
  2083. sei();
  2084. }
  2085. }
  2086. #endif //TMC2130
  2087. void gcode_M105(uint8_t extruder)
  2088. {
  2089. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2090. SERIAL_PROTOCOLPGM("T:");
  2091. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2092. SERIAL_PROTOCOLPGM(" /");
  2093. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2094. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2095. SERIAL_PROTOCOLPGM(" B:");
  2096. SERIAL_PROTOCOL_F(degBed(),1);
  2097. SERIAL_PROTOCOLPGM(" /");
  2098. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2099. #endif //TEMP_BED_PIN
  2100. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2101. SERIAL_PROTOCOLPGM(" T");
  2102. SERIAL_PROTOCOL(cur_extruder);
  2103. SERIAL_PROTOCOL(':');
  2104. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2105. SERIAL_PROTOCOLPGM(" /");
  2106. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2107. }
  2108. #else
  2109. SERIAL_ERROR_START;
  2110. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2111. #endif
  2112. SERIAL_PROTOCOLPGM(" @:");
  2113. #ifdef EXTRUDER_WATTS
  2114. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2115. SERIAL_PROTOCOLPGM("W");
  2116. #else
  2117. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2118. #endif
  2119. SERIAL_PROTOCOLPGM(" B@:");
  2120. #ifdef BED_WATTS
  2121. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2122. SERIAL_PROTOCOLPGM("W");
  2123. #else
  2124. SERIAL_PROTOCOL(getHeaterPower(-1));
  2125. #endif
  2126. #ifdef PINDA_THERMISTOR
  2127. SERIAL_PROTOCOLPGM(" P:");
  2128. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2129. #endif //PINDA_THERMISTOR
  2130. #ifdef AMBIENT_THERMISTOR
  2131. SERIAL_PROTOCOLPGM(" A:");
  2132. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2133. #endif //AMBIENT_THERMISTOR
  2134. #ifdef SHOW_TEMP_ADC_VALUES
  2135. {
  2136. float raw = 0.0;
  2137. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2138. SERIAL_PROTOCOLPGM(" ADC B:");
  2139. SERIAL_PROTOCOL_F(degBed(),1);
  2140. SERIAL_PROTOCOLPGM("C->");
  2141. raw = rawBedTemp();
  2142. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2143. SERIAL_PROTOCOLPGM(" Rb->");
  2144. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2145. SERIAL_PROTOCOLPGM(" Rxb->");
  2146. SERIAL_PROTOCOL_F(raw, 5);
  2147. #endif
  2148. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2149. SERIAL_PROTOCOLPGM(" T");
  2150. SERIAL_PROTOCOL(cur_extruder);
  2151. SERIAL_PROTOCOLPGM(":");
  2152. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2153. SERIAL_PROTOCOLPGM("C->");
  2154. raw = rawHotendTemp(cur_extruder);
  2155. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2156. SERIAL_PROTOCOLPGM(" Rt");
  2157. SERIAL_PROTOCOL(cur_extruder);
  2158. SERIAL_PROTOCOLPGM("->");
  2159. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2160. SERIAL_PROTOCOLPGM(" Rx");
  2161. SERIAL_PROTOCOL(cur_extruder);
  2162. SERIAL_PROTOCOLPGM("->");
  2163. SERIAL_PROTOCOL_F(raw, 5);
  2164. }
  2165. }
  2166. #endif
  2167. SERIAL_PROTOCOLLN();
  2168. }
  2169. #ifdef TMC2130
  2170. 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)
  2171. #else
  2172. 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)
  2173. #endif //TMC2130
  2174. {
  2175. // Flag for the display update routine and to disable the print cancelation during homing.
  2176. st_synchronize();
  2177. homing_flag = true;
  2178. #if 0
  2179. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2180. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2181. #endif
  2182. // Which axes should be homed?
  2183. bool home_x = home_x_axis;
  2184. bool home_y = home_y_axis;
  2185. bool home_z = home_z_axis;
  2186. // Either all X,Y,Z codes are present, or none of them.
  2187. bool home_all_axes = home_x == home_y && home_x == home_z;
  2188. if (home_all_axes)
  2189. // No X/Y/Z code provided means to home all axes.
  2190. home_x = home_y = home_z = true;
  2191. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2192. if (home_all_axes) {
  2193. raise_z_above(MESH_HOME_Z_SEARCH);
  2194. st_synchronize();
  2195. }
  2196. #ifdef ENABLE_AUTO_BED_LEVELING
  2197. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2198. #endif //ENABLE_AUTO_BED_LEVELING
  2199. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2200. // the planner will not perform any adjustments in the XY plane.
  2201. // Wait for the motors to stop and update the current position with the absolute values.
  2202. world2machine_revert_to_uncorrected();
  2203. // For mesh bed leveling deactivate the matrix temporarily.
  2204. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2205. // in a single axis only.
  2206. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2207. #ifdef MESH_BED_LEVELING
  2208. uint8_t mbl_was_active = mbl.active;
  2209. mbl.active = 0;
  2210. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2211. #endif
  2212. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2213. if (home_z)
  2214. babystep_undo();
  2215. int l_feedmultiply = setup_for_endstop_move();
  2216. set_destination_to_current();
  2217. feedrate = 0.0;
  2218. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2219. if(home_z)
  2220. homeaxis(Z_AXIS);
  2221. #endif
  2222. #ifdef QUICK_HOME
  2223. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2224. if(home_x && home_y) //first diagonal move
  2225. {
  2226. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2227. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2228. plan_set_position_curposXYZE();
  2229. 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);
  2230. feedrate = homing_feedrate[X_AXIS];
  2231. if(homing_feedrate[Y_AXIS]<feedrate)
  2232. feedrate = homing_feedrate[Y_AXIS];
  2233. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2234. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2235. } else {
  2236. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2237. }
  2238. plan_buffer_line_destinationXYZE(feedrate/60);
  2239. st_synchronize();
  2240. axis_is_at_home(X_AXIS);
  2241. axis_is_at_home(Y_AXIS);
  2242. plan_set_position_curposXYZE();
  2243. destination[X_AXIS] = current_position[X_AXIS];
  2244. destination[Y_AXIS] = current_position[Y_AXIS];
  2245. plan_buffer_line_destinationXYZE(feedrate/60);
  2246. feedrate = 0.0;
  2247. st_synchronize();
  2248. endstops_hit_on_purpose();
  2249. current_position[X_AXIS] = destination[X_AXIS];
  2250. current_position[Y_AXIS] = destination[Y_AXIS];
  2251. current_position[Z_AXIS] = destination[Z_AXIS];
  2252. }
  2253. #endif /* QUICK_HOME */
  2254. #ifdef TMC2130
  2255. if(home_x)
  2256. {
  2257. if (!calib)
  2258. homeaxis(X_AXIS);
  2259. else
  2260. tmc2130_home_calibrate(X_AXIS);
  2261. }
  2262. if(home_y)
  2263. {
  2264. if (!calib)
  2265. homeaxis(Y_AXIS);
  2266. else
  2267. tmc2130_home_calibrate(Y_AXIS);
  2268. }
  2269. #else //TMC2130
  2270. if(home_x) homeaxis(X_AXIS);
  2271. if(home_y) homeaxis(Y_AXIS);
  2272. #endif //TMC2130
  2273. if(home_x_axis && home_x_value != 0)
  2274. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2275. if(home_y_axis && home_y_value != 0)
  2276. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2277. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2278. #ifndef Z_SAFE_HOMING
  2279. if(home_z) {
  2280. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2281. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2282. st_synchronize();
  2283. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2284. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2285. raise_z_above(MESH_HOME_Z_SEARCH);
  2286. st_synchronize();
  2287. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2288. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2289. // 1st mesh bed leveling measurement point, corrected.
  2290. world2machine_initialize();
  2291. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2292. world2machine_reset();
  2293. if (destination[Y_AXIS] < Y_MIN_POS)
  2294. destination[Y_AXIS] = Y_MIN_POS;
  2295. feedrate = homing_feedrate[X_AXIS] / 20;
  2296. enable_endstops(false);
  2297. #ifdef DEBUG_BUILD
  2298. SERIAL_ECHOLNPGM("plan_set_position()");
  2299. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2300. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2301. #endif
  2302. plan_set_position_curposXYZE();
  2303. #ifdef DEBUG_BUILD
  2304. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2305. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2306. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2307. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2308. #endif
  2309. plan_buffer_line_destinationXYZE(feedrate);
  2310. st_synchronize();
  2311. current_position[X_AXIS] = destination[X_AXIS];
  2312. current_position[Y_AXIS] = destination[Y_AXIS];
  2313. enable_endstops(true);
  2314. endstops_hit_on_purpose();
  2315. homeaxis(Z_AXIS);
  2316. #else // MESH_BED_LEVELING
  2317. homeaxis(Z_AXIS);
  2318. #endif // MESH_BED_LEVELING
  2319. }
  2320. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2321. if(home_all_axes) {
  2322. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2323. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2324. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2325. feedrate = XY_TRAVEL_SPEED/60;
  2326. current_position[Z_AXIS] = 0;
  2327. plan_set_position_curposXYZE();
  2328. plan_buffer_line_destinationXYZE(feedrate);
  2329. st_synchronize();
  2330. current_position[X_AXIS] = destination[X_AXIS];
  2331. current_position[Y_AXIS] = destination[Y_AXIS];
  2332. homeaxis(Z_AXIS);
  2333. }
  2334. // Let's see if X and Y are homed and probe is inside bed area.
  2335. if(home_z) {
  2336. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2337. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2338. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2339. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2340. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2341. current_position[Z_AXIS] = 0;
  2342. plan_set_position_curposXYZE();
  2343. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2344. feedrate = max_feedrate[Z_AXIS];
  2345. plan_buffer_line_destinationXYZE(feedrate);
  2346. st_synchronize();
  2347. homeaxis(Z_AXIS);
  2348. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2349. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2350. SERIAL_ECHO_START;
  2351. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2352. } else {
  2353. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2354. SERIAL_ECHO_START;
  2355. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2356. }
  2357. }
  2358. #endif // Z_SAFE_HOMING
  2359. #endif // Z_HOME_DIR < 0
  2360. if(home_z_axis && home_z_value != 0)
  2361. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2362. #ifdef ENABLE_AUTO_BED_LEVELING
  2363. if(home_z)
  2364. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2365. #endif
  2366. // Set the planner and stepper routine positions.
  2367. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2368. // contains the machine coordinates.
  2369. plan_set_position_curposXYZE();
  2370. clean_up_after_endstop_move(l_feedmultiply);
  2371. endstops_hit_on_purpose();
  2372. #ifndef MESH_BED_LEVELING
  2373. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2374. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2375. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2376. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2377. lcd_adjust_z();
  2378. #endif
  2379. // Load the machine correction matrix
  2380. world2machine_initialize();
  2381. // and correct the current_position XY axes to match the transformed coordinate system.
  2382. world2machine_update_current();
  2383. #ifdef MESH_BED_LEVELING
  2384. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2385. {
  2386. if (! home_z && mbl_was_active) {
  2387. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2388. mbl.active = true;
  2389. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2390. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2391. }
  2392. }
  2393. #endif
  2394. prusa_statistics(20);
  2395. st_synchronize();
  2396. homing_flag = false;
  2397. #if 0
  2398. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2399. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2400. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2401. #endif
  2402. }
  2403. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2404. {
  2405. #ifdef TMC2130
  2406. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2407. #else
  2408. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2409. #endif //TMC2130
  2410. }
  2411. // G80 - Automatic mesh bed leveling
  2412. static void gcode_G80()
  2413. {
  2414. st_synchronize();
  2415. if (planner_aborted)
  2416. return;
  2417. mesh_bed_leveling_flag = true;
  2418. #ifndef PINDA_THERMISTOR
  2419. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2420. #endif // ndef PINDA_THERMISTOR
  2421. #ifdef SUPPORT_VERBOSITY
  2422. int8_t verbosity_level = 0;
  2423. if (code_seen('V')) {
  2424. // Just 'V' without a number counts as V1.
  2425. char c = strchr_pointer[1];
  2426. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2427. }
  2428. #endif //SUPPORT_VERBOSITY
  2429. // Firstly check if we know where we are
  2430. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2431. // We don't know where we are! HOME!
  2432. // Push the commands to the front of the message queue in the reverse order!
  2433. // There shall be always enough space reserved for these commands.
  2434. repeatcommand_front(); // repeat G80 with all its parameters
  2435. enquecommand_front_P(G28W0);
  2436. return;
  2437. }
  2438. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2439. if (code_seen('N')) {
  2440. nMeasPoints = code_value_uint8();
  2441. if (nMeasPoints != 7) {
  2442. nMeasPoints = 3;
  2443. }
  2444. }
  2445. else {
  2446. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2447. }
  2448. uint8_t nProbeRetry = 3;
  2449. if (code_seen('R')) {
  2450. nProbeRetry = code_value_uint8();
  2451. if (nProbeRetry > 10) {
  2452. nProbeRetry = 10;
  2453. }
  2454. }
  2455. else {
  2456. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2457. }
  2458. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2459. #ifndef PINDA_THERMISTOR
  2460. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2461. {
  2462. temp_compensation_start();
  2463. run = true;
  2464. repeatcommand_front(); // repeat G80 with all its parameters
  2465. enquecommand_front_P(G28W0);
  2466. break;
  2467. }
  2468. run = false;
  2469. #endif //PINDA_THERMISTOR
  2470. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2471. CustomMsg custom_message_type_old = custom_message_type;
  2472. uint8_t custom_message_state_old = custom_message_state;
  2473. custom_message_type = CustomMsg::MeshBedLeveling;
  2474. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2475. lcd_update(1);
  2476. mbl.reset(); //reset mesh bed leveling
  2477. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2478. babystep_undo();
  2479. // Cycle through all points and probe them
  2480. // First move up. During this first movement, the babystepping will be reverted.
  2481. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2482. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2483. // The move to the first calibration point.
  2484. current_position[X_AXIS] = BED_X0;
  2485. current_position[Y_AXIS] = BED_Y0;
  2486. #ifdef SUPPORT_VERBOSITY
  2487. if (verbosity_level >= 1)
  2488. {
  2489. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2490. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2491. }
  2492. #else //SUPPORT_VERBOSITY
  2493. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2494. #endif //SUPPORT_VERBOSITY
  2495. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2496. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2497. // Wait until the move is finished.
  2498. st_synchronize();
  2499. if (planner_aborted)
  2500. {
  2501. custom_message_type = custom_message_type_old;
  2502. custom_message_state = custom_message_state_old;
  2503. return;
  2504. }
  2505. uint8_t mesh_point = 0; //index number of calibration point
  2506. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2507. bool has_z = is_bed_z_jitter_data_valid(); //checks if we have data from Z calibration (offsets of the Z heiths of the 8 calibration points from the first point)
  2508. #ifdef SUPPORT_VERBOSITY
  2509. if (verbosity_level >= 1) {
  2510. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2511. }
  2512. #endif // SUPPORT_VERBOSITY
  2513. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2514. while (mesh_point != nMeasPoints * nMeasPoints) {
  2515. // Get coords of a measuring point.
  2516. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2517. uint8_t iy = mesh_point / nMeasPoints;
  2518. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2519. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2520. custom_message_state--;
  2521. mesh_point++;
  2522. continue; //skip
  2523. }*/
  2524. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2525. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2526. {
  2527. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2528. }
  2529. float z0 = 0.f;
  2530. if (has_z && (mesh_point > 0)) {
  2531. uint16_t z_offset_u = 0;
  2532. if (nMeasPoints == 7) {
  2533. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2534. }
  2535. else {
  2536. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2537. }
  2538. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2539. #ifdef SUPPORT_VERBOSITY
  2540. if (verbosity_level >= 1) {
  2541. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2542. }
  2543. #endif // SUPPORT_VERBOSITY
  2544. }
  2545. // Move Z up to MESH_HOME_Z_SEARCH.
  2546. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2547. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2548. float init_z_bckp = current_position[Z_AXIS];
  2549. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2550. st_synchronize();
  2551. // Move to XY position of the sensor point.
  2552. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2553. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2554. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2555. #ifdef SUPPORT_VERBOSITY
  2556. if (verbosity_level >= 1) {
  2557. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2558. SERIAL_PROTOCOL(mesh_point);
  2559. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2560. }
  2561. #else //SUPPORT_VERBOSITY
  2562. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2563. #endif // SUPPORT_VERBOSITY
  2564. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2565. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2566. st_synchronize();
  2567. if (planner_aborted)
  2568. {
  2569. custom_message_type = custom_message_type_old;
  2570. custom_message_state = custom_message_state_old;
  2571. return;
  2572. }
  2573. // Go down until endstop is hit
  2574. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2575. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  2576. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2577. break;
  2578. }
  2579. if (init_z_bckp - current_position[Z_AXIS] < 0.1f) { //broken cable or initial Z coordinate too low. Go to MESH_HOME_Z_SEARCH and repeat last step (z-probe) again to distinguish between these two cases.
  2580. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2581. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2582. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2583. st_synchronize();
  2584. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  2585. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2586. break;
  2587. }
  2588. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2589. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2590. break;
  2591. }
  2592. }
  2593. if (has_z && fabs(z0 - current_position[Z_AXIS]) > Z_CALIBRATION_THRESHOLD) { //if we have data from z calibration, max. allowed difference is 1mm for each point
  2594. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2595. break;
  2596. }
  2597. #ifdef SUPPORT_VERBOSITY
  2598. if (verbosity_level >= 10) {
  2599. SERIAL_ECHOPGM("X: ");
  2600. MYSERIAL.print(current_position[X_AXIS], 5);
  2601. SERIAL_ECHOLNPGM("");
  2602. SERIAL_ECHOPGM("Y: ");
  2603. MYSERIAL.print(current_position[Y_AXIS], 5);
  2604. SERIAL_PROTOCOLPGM("\n");
  2605. }
  2606. #endif // SUPPORT_VERBOSITY
  2607. float offset_z = 0;
  2608. #ifdef PINDA_THERMISTOR
  2609. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2610. #endif //PINDA_THERMISTOR
  2611. // #ifdef SUPPORT_VERBOSITY
  2612. /* if (verbosity_level >= 1)
  2613. {
  2614. SERIAL_ECHOPGM("mesh bed leveling: ");
  2615. MYSERIAL.print(current_position[Z_AXIS], 5);
  2616. SERIAL_ECHOPGM(" offset: ");
  2617. MYSERIAL.print(offset_z, 5);
  2618. SERIAL_ECHOLNPGM("");
  2619. }*/
  2620. // #endif // SUPPORT_VERBOSITY
  2621. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2622. custom_message_state--;
  2623. mesh_point++;
  2624. lcd_update(1);
  2625. }
  2626. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2627. #ifdef SUPPORT_VERBOSITY
  2628. if (verbosity_level >= 20) {
  2629. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2630. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2631. MYSERIAL.print(current_position[Z_AXIS], 5);
  2632. }
  2633. #endif // SUPPORT_VERBOSITY
  2634. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2635. st_synchronize();
  2636. if (mesh_point != nMeasPoints * nMeasPoints) {
  2637. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2638. bool bState;
  2639. do { // repeat until Z-leveling o.k.
  2640. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2641. #ifdef TMC2130
  2642. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2643. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2644. #else // TMC2130
  2645. lcd_wait_for_click_delay(0); // ~ no timeout
  2646. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2647. #endif // TMC2130
  2648. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2649. bState=enable_z_endstop(false);
  2650. current_position[Z_AXIS] -= 1;
  2651. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2652. st_synchronize();
  2653. enable_z_endstop(true);
  2654. #ifdef TMC2130
  2655. tmc2130_home_enter(Z_AXIS_MASK);
  2656. #endif // TMC2130
  2657. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2658. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2659. st_synchronize();
  2660. #ifdef TMC2130
  2661. tmc2130_home_exit();
  2662. #endif // TMC2130
  2663. enable_z_endstop(bState);
  2664. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2665. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2666. custom_message_type = custom_message_type_old;
  2667. custom_message_state = custom_message_state_old;
  2668. lcd_update_enable(true); // display / status-line recovery
  2669. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2670. repeatcommand_front(); // re-run (i.e. of "G80")
  2671. return;
  2672. }
  2673. clean_up_after_endstop_move(l_feedmultiply);
  2674. // SERIAL_ECHOLNPGM("clean up finished ");
  2675. #ifndef PINDA_THERMISTOR
  2676. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2677. #endif
  2678. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2679. // SERIAL_ECHOLNPGM("babystep applied");
  2680. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2681. #ifdef SUPPORT_VERBOSITY
  2682. if (verbosity_level >= 1) {
  2683. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2684. }
  2685. #endif // SUPPORT_VERBOSITY
  2686. for (uint8_t i = 0; i < 4; ++i) {
  2687. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2688. long correction = 0;
  2689. if (code_seen(codes[i]))
  2690. correction = code_value_long();
  2691. else if (eeprom_bed_correction_valid) {
  2692. unsigned char *addr = (i < 2) ?
  2693. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2694. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2695. correction = eeprom_read_int8(addr);
  2696. }
  2697. if (correction == 0)
  2698. continue;
  2699. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2700. SERIAL_ERROR_START;
  2701. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2702. SERIAL_ECHO(correction);
  2703. SERIAL_ECHOLNPGM(" microns");
  2704. }
  2705. else {
  2706. float offset = float(correction) * 0.001f;
  2707. switch (i) {
  2708. case 0:
  2709. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2710. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2711. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2712. }
  2713. }
  2714. break;
  2715. case 1:
  2716. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2717. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2718. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2719. }
  2720. }
  2721. break;
  2722. case 2:
  2723. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2724. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2725. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2726. }
  2727. }
  2728. break;
  2729. case 3:
  2730. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2731. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2732. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2733. }
  2734. }
  2735. break;
  2736. }
  2737. }
  2738. }
  2739. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2740. if (nMeasPoints == 3) {
  2741. mbl.upsample_3x3(); //interpolation from 3x3 to 7x7 points using largrangian polynomials while using the same array z_values[iy][ix] for storing (just coppying measured data to new destination and interpolating between them)
  2742. }
  2743. /*
  2744. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2745. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2746. SERIAL_PROTOCOLPGM(",");
  2747. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2748. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2749. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2750. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2751. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2752. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2753. SERIAL_PROTOCOLPGM(" ");
  2754. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2755. }
  2756. SERIAL_PROTOCOLPGM("\n");
  2757. }
  2758. */
  2759. if (nMeasPoints == 7 && magnet_elimination) {
  2760. mbl_interpolation(nMeasPoints);
  2761. }
  2762. /*
  2763. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2764. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2765. SERIAL_PROTOCOLPGM(",");
  2766. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2767. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2768. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2769. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2770. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2771. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2772. SERIAL_PROTOCOLPGM(" ");
  2773. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2774. }
  2775. SERIAL_PROTOCOLPGM("\n");
  2776. }
  2777. */
  2778. // SERIAL_ECHOLNPGM("Upsample finished");
  2779. mbl.active = 1; //activate mesh bed leveling
  2780. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2781. go_home_with_z_lift();
  2782. // SERIAL_ECHOLNPGM("Go home finished");
  2783. //unretract (after PINDA preheat retraction)
  2784. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2785. current_position[E_AXIS] += default_retraction;
  2786. plan_buffer_line_curposXYZE(400);
  2787. }
  2788. KEEPALIVE_STATE(NOT_BUSY);
  2789. // Restore custom message state
  2790. lcd_setstatuspgm(MSG_WELCOME);
  2791. custom_message_type = custom_message_type_old;
  2792. custom_message_state = custom_message_state_old;
  2793. lcd_update(2);
  2794. st_synchronize();
  2795. mesh_bed_leveling_flag = false;
  2796. }
  2797. void adjust_bed_reset()
  2798. {
  2799. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2800. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2801. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2802. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2803. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2804. }
  2805. //! @brief Calibrate XYZ
  2806. //! @param onlyZ if true, calibrate only Z axis
  2807. //! @param verbosity_level
  2808. //! @retval true Succeeded
  2809. //! @retval false Failed
  2810. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2811. {
  2812. bool final_result = false;
  2813. #ifdef TMC2130
  2814. FORCE_HIGH_POWER_START;
  2815. #endif // TMC2130
  2816. FORCE_BL_ON_START;
  2817. // Only Z calibration?
  2818. if (!onlyZ)
  2819. {
  2820. setTargetBed(0);
  2821. setAllTargetHotends(0);
  2822. adjust_bed_reset(); //reset bed level correction
  2823. }
  2824. // Disable the default update procedure of the display. We will do a modal dialog.
  2825. lcd_update_enable(false);
  2826. // Let the planner use the uncorrected coordinates.
  2827. mbl.reset();
  2828. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2829. // the planner will not perform any adjustments in the XY plane.
  2830. // Wait for the motors to stop and update the current position with the absolute values.
  2831. world2machine_revert_to_uncorrected();
  2832. // Reset the baby step value applied without moving the axes.
  2833. babystep_reset();
  2834. // Mark all axes as in a need for homing.
  2835. memset(axis_known_position, 0, sizeof(axis_known_position));
  2836. // Home in the XY plane.
  2837. //set_destination_to_current();
  2838. int l_feedmultiply = setup_for_endstop_move();
  2839. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2840. raise_z_above(MESH_HOME_Z_SEARCH);
  2841. st_synchronize();
  2842. home_xy();
  2843. enable_endstops(false);
  2844. current_position[X_AXIS] += 5;
  2845. current_position[Y_AXIS] += 5;
  2846. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2847. st_synchronize();
  2848. // Let the user move the Z axes up to the end stoppers.
  2849. #ifdef TMC2130
  2850. if (calibrate_z_auto())
  2851. {
  2852. #else //TMC2130
  2853. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2854. {
  2855. #endif //TMC2130
  2856. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2857. if(onlyZ){
  2858. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2859. lcd_puts_at_P(0,3,_n("1/9"));
  2860. }else{
  2861. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2862. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2863. lcd_puts_at_P(0,3,_n("1/4"));
  2864. }
  2865. refresh_cmd_timeout();
  2866. #ifndef STEEL_SHEET
  2867. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2868. {
  2869. lcd_wait_for_cool_down();
  2870. }
  2871. #endif //STEEL_SHEET
  2872. if(!onlyZ)
  2873. {
  2874. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2875. #ifdef STEEL_SHEET
  2876. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2877. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  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. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2886. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2887. st_synchronize();
  2888. // Move the print head close to the bed.
  2889. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2890. enable_endstops(true);
  2891. #ifdef TMC2130
  2892. tmc2130_home_enter(Z_AXIS_MASK);
  2893. #endif //TMC2130
  2894. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2895. st_synchronize();
  2896. #ifdef TMC2130
  2897. tmc2130_home_exit();
  2898. #endif //TMC2130
  2899. enable_endstops(endstops_enabled);
  2900. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2901. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2902. {
  2903. if (onlyZ)
  2904. {
  2905. clean_up_after_endstop_move(l_feedmultiply);
  2906. // Z only calibration.
  2907. // Load the machine correction matrix
  2908. world2machine_initialize();
  2909. // and correct the current_position to match the transformed coordinate system.
  2910. world2machine_update_current();
  2911. //FIXME
  2912. bool result = sample_mesh_and_store_reference();
  2913. if (result)
  2914. {
  2915. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2916. {
  2917. // Shipped, the nozzle height has been set already. The user can start printing now.
  2918. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2919. }
  2920. final_result = true;
  2921. // babystep_apply();
  2922. }
  2923. }
  2924. else
  2925. {
  2926. // Reset the baby step value and the baby step applied flag.
  2927. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2928. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2929. // Complete XYZ calibration.
  2930. uint8_t point_too_far_mask = 0;
  2931. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2932. clean_up_after_endstop_move(l_feedmultiply);
  2933. // Print head up.
  2934. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2935. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2936. st_synchronize();
  2937. //#ifndef NEW_XYZCAL
  2938. if (result >= 0)
  2939. {
  2940. #ifdef HEATBED_V2
  2941. sample_z();
  2942. #else //HEATBED_V2
  2943. point_too_far_mask = 0;
  2944. // Second half: The fine adjustment.
  2945. // Let the planner use the uncorrected coordinates.
  2946. mbl.reset();
  2947. world2machine_reset();
  2948. // Home in the XY plane.
  2949. int l_feedmultiply = setup_for_endstop_move();
  2950. home_xy();
  2951. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2952. clean_up_after_endstop_move(l_feedmultiply);
  2953. // Print head up.
  2954. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2955. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2956. st_synchronize();
  2957. // if (result >= 0) babystep_apply();
  2958. #endif //HEATBED_V2
  2959. }
  2960. //#endif //NEW_XYZCAL
  2961. lcd_update_enable(true);
  2962. lcd_update(2);
  2963. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2964. if (result >= 0)
  2965. {
  2966. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2967. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2968. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2969. final_result = true;
  2970. }
  2971. }
  2972. #ifdef TMC2130
  2973. tmc2130_home_exit();
  2974. #endif
  2975. }
  2976. else
  2977. {
  2978. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2979. final_result = false;
  2980. }
  2981. }
  2982. else
  2983. {
  2984. // Timeouted.
  2985. }
  2986. lcd_update_enable(true);
  2987. #ifdef TMC2130
  2988. FORCE_HIGH_POWER_END;
  2989. #endif // TMC2130
  2990. FORCE_BL_ON_END;
  2991. return final_result;
  2992. }
  2993. void gcode_M114()
  2994. {
  2995. SERIAL_PROTOCOLPGM("X:");
  2996. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2997. SERIAL_PROTOCOLPGM(" Y:");
  2998. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2999. SERIAL_PROTOCOLPGM(" Z:");
  3000. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3001. SERIAL_PROTOCOLPGM(" E:");
  3002. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3003. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  3004. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  3005. SERIAL_PROTOCOLPGM(" Y:");
  3006. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  3007. SERIAL_PROTOCOLPGM(" Z:");
  3008. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  3009. SERIAL_PROTOCOLPGM(" E:");
  3010. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3011. }
  3012. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3013. void gcode_M123()
  3014. {
  3015. 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);
  3016. }
  3017. #endif //FANCHECK and TACH_0 or TACH_1
  3018. //! extracted code to compute z_shift for M600 in case of filament change operation
  3019. //! requested from fsensors.
  3020. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  3021. //! unlike the previous implementation, which was adding 25mm even when the head was
  3022. //! printing at e.g. 24mm height.
  3023. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  3024. //! the printout.
  3025. //! This function is templated to enable fast change of computation data type.
  3026. //! @return new z_shift value
  3027. template<typename T>
  3028. static T gcode_M600_filament_change_z_shift()
  3029. {
  3030. #ifdef FILAMENTCHANGE_ZADD
  3031. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  3032. // avoid floating point arithmetics when not necessary - results in shorter code
  3033. T z_shift = T(FILAMENTCHANGE_ZADD); // always move above printout
  3034. T ztmp = T( current_position[Z_AXIS] );
  3035. if((ztmp + z_shift) < T(MIN_Z_FOR_SWAP)){
  3036. z_shift = T(MIN_Z_FOR_SWAP) - ztmp; // make sure to be at least 25mm above the heat bed
  3037. }
  3038. return z_shift;
  3039. #else
  3040. return T(0);
  3041. #endif
  3042. }
  3043. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  3044. {
  3045. st_synchronize();
  3046. float lastpos[4];
  3047. prusa_statistics(22);
  3048. //First backup current position and settings
  3049. int feedmultiplyBckp = feedmultiply;
  3050. float HotendTempBckp = degTargetHotend(active_extruder);
  3051. int fanSpeedBckp = fanSpeed;
  3052. lastpos[X_AXIS] = current_position[X_AXIS];
  3053. lastpos[Y_AXIS] = current_position[Y_AXIS];
  3054. lastpos[Z_AXIS] = current_position[Z_AXIS];
  3055. lastpos[E_AXIS] = current_position[E_AXIS];
  3056. //Retract E
  3057. current_position[E_AXIS] += e_shift;
  3058. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3059. st_synchronize();
  3060. //Lift Z
  3061. current_position[Z_AXIS] += z_shift;
  3062. clamp_to_software_endstops(current_position);
  3063. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED);
  3064. st_synchronize();
  3065. //Move XY to side
  3066. current_position[X_AXIS] = x_position;
  3067. current_position[Y_AXIS] = y_position;
  3068. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3069. st_synchronize();
  3070. //Beep, manage nozzle heater and wait for user to start unload filament
  3071. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  3072. lcd_change_fil_state = 0;
  3073. // Unload filament
  3074. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  3075. else unload_filament(true); //unload filament for single material (used also in M702)
  3076. //finish moves
  3077. st_synchronize();
  3078. #ifdef FILAMENT_SENSOR
  3079. fsensor.setRunoutEnabled(false); //suppress filament runouts while loading filament.
  3080. fsensor.setAutoLoadEnabled(false); //suppress filament autoloads while loading filament.
  3081. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3082. fsensor.setJamDetectionEnabled(false); //suppress filament jam detection while loading filament.
  3083. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3084. #endif
  3085. if (!mmu_enabled)
  3086. {
  3087. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3088. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(
  3089. _i("Was filament unload successful?"), ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3090. false, true);
  3091. if (lcd_change_fil_state == 0)
  3092. {
  3093. lcd_clear();
  3094. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3095. current_position[X_AXIS] -= 100;
  3096. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3097. st_synchronize();
  3098. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=5
  3099. }
  3100. }
  3101. if (mmu_enabled)
  3102. {
  3103. if (!automatic) {
  3104. if (saved_printing) mmu_eject_filament(mmu_extruder, false); //if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3105. mmu_M600_wait_and_beep();
  3106. if (saved_printing) {
  3107. lcd_clear();
  3108. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3109. mmu_command(MmuCmd::R0);
  3110. manage_response(false, false);
  3111. }
  3112. }
  3113. mmu_M600_load_filament(automatic, HotendTempBckp);
  3114. }
  3115. else
  3116. M600_load_filament();
  3117. if (!automatic) M600_check_state(HotendTempBckp);
  3118. lcd_update_enable(true);
  3119. //Not let's go back to print
  3120. fanSpeed = fanSpeedBckp;
  3121. //Feed a little of filament to stabilize pressure
  3122. if (!automatic)
  3123. {
  3124. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3125. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3126. }
  3127. //Move XY back
  3128. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  3129. FILAMENTCHANGE_XYFEED, active_extruder);
  3130. st_synchronize();
  3131. //Move Z back
  3132. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  3133. FILAMENTCHANGE_ZFEED, active_extruder);
  3134. st_synchronize();
  3135. //Set E position to original
  3136. plan_set_e_position(lastpos[E_AXIS]);
  3137. memcpy(current_position, lastpos, sizeof(lastpos));
  3138. set_destination_to_current();
  3139. //Recover feed rate
  3140. feedmultiply = feedmultiplyBckp;
  3141. char cmd[9];
  3142. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3143. enquecommand(cmd);
  3144. #ifdef FILAMENT_SENSOR
  3145. fsensor.settings_init();
  3146. #endif
  3147. lcd_setstatuspgm(MSG_WELCOME);
  3148. custom_message_type = CustomMsg::Status;
  3149. }
  3150. void gcode_M701()
  3151. {
  3152. printf_P(PSTR("gcode_M701 begin\n"));
  3153. #ifdef FILAMENT_SENSOR
  3154. fsensor.setRunoutEnabled(false); //suppress filament runouts while loading filament.
  3155. fsensor.setAutoLoadEnabled(false); //suppress filament autoloads while loading filament.
  3156. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3157. fsensor.setJamDetectionEnabled(false); //suppress filament jam detection while loading filament.
  3158. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3159. #endif
  3160. prusa_statistics(22);
  3161. if (mmu_enabled)
  3162. {
  3163. extr_adj(tmp_extruder);//loads current extruder
  3164. mmu_extruder = tmp_extruder;
  3165. }
  3166. else
  3167. {
  3168. enable_z();
  3169. custom_message_type = CustomMsg::FilamentLoading;
  3170. #ifdef FSENSOR_QUALITY
  3171. fsensor_oq_meassure_start(40);
  3172. #endif //FSENSOR_QUALITY
  3173. const int feed_mm_before_raising = 30;
  3174. static_assert(feed_mm_before_raising <= FILAMENTCHANGE_FIRSTFEED);
  3175. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3176. current_position[E_AXIS] += FILAMENTCHANGE_FIRSTFEED - feed_mm_before_raising;
  3177. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3178. st_synchronize();
  3179. raise_z_above(MIN_Z_FOR_LOAD, false);
  3180. current_position[E_AXIS] += feed_mm_before_raising;
  3181. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3182. load_filament_final_feed(); //slow sequence
  3183. st_synchronize();
  3184. Sound_MakeCustom(50,500,false);
  3185. if (!farm_mode && loading_flag) {
  3186. lcd_load_filament_color_check();
  3187. }
  3188. lcd_update_enable(true);
  3189. lcd_update(2);
  3190. lcd_setstatuspgm(MSG_WELCOME);
  3191. disable_z();
  3192. loading_flag = false;
  3193. custom_message_type = CustomMsg::Status;
  3194. #ifdef FSENSOR_QUALITY
  3195. fsensor_oq_meassure_stop();
  3196. if (!fsensor_oq_result())
  3197. {
  3198. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_n("Fil. sensor response is poor, disable it?"), false, true);
  3199. lcd_update_enable(true);
  3200. lcd_update(2);
  3201. if (disable)
  3202. fsensor_disable();
  3203. }
  3204. eFilamentAction = FilamentAction::None;
  3205. #ifdef FILAMENT_SENSOR
  3206. fsensor.settings_init(); //restore filament runout state.
  3207. #endif
  3208. }
  3209. /**
  3210. * @brief Get serial number from 32U2 processor
  3211. *
  3212. * Typical format of S/N is:CZPX0917X003XC13518
  3213. *
  3214. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3215. * reply is stored in *SN.
  3216. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3217. * and returns a general failure flag.
  3218. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3219. * In that case the value that is stored in the EEPROM should be used instead.
  3220. *
  3221. * @return 0 on success
  3222. * @return 1 on general failure
  3223. */
  3224. #ifdef PRUSA_SN_SUPPORT
  3225. static uint8_t get_PRUSA_SN(char* SN)
  3226. {
  3227. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3228. uint8_t rxIndex;
  3229. bool SN_valid = false;
  3230. ShortTimer timeout;
  3231. selectedSerialPort = 0;
  3232. timeout.start();
  3233. while (!SN_valid)
  3234. {
  3235. rxIndex = 0;
  3236. _delay(50);
  3237. MYSERIAL.flush(); //clear RX buffer
  3238. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3239. while (rxIndex < 19)
  3240. {
  3241. if (timeout.expired(250u))
  3242. goto exit;
  3243. if (MYSERIAL.available() > 0)
  3244. {
  3245. SN[rxIndex] = MYSERIAL.read();
  3246. rxIndex++;
  3247. }
  3248. }
  3249. SN[rxIndex] = 0;
  3250. // printf_P(PSTR("SN:%s\n"), SN);
  3251. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3252. }
  3253. exit:
  3254. selectedSerialPort = selectedSerialPort_bak;
  3255. return !SN_valid;
  3256. }
  3257. #endif //PRUSA_SN_SUPPORT
  3258. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3259. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3260. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3261. //! it may even interfere with other functions of the printer! You have been warned!
  3262. //! The test idea is to measure the time necessary to charge the capacitor.
  3263. //! So the algorithm is as follows:
  3264. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3265. //! 2. Wait a few ms
  3266. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3267. //! Repeat 1.-3. several times
  3268. //! Good RAMBo's times are in the range of approx. 260-320 us
  3269. //! Bad RAMBo's times are approx. 260-1200 us
  3270. //! So basically we are interested in maximum time, the minima are mostly the same.
  3271. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3272. static void gcode_PRUSA_BadRAMBoFanTest(){
  3273. //printf_P(PSTR("Enter fan pin test\n"));
  3274. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3275. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3276. unsigned long tach1max = 0;
  3277. uint8_t tach1cntr = 0;
  3278. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3279. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3280. SET_OUTPUT(TACH_1);
  3281. WRITE(TACH_1, LOW);
  3282. _delay(20); // the delay may be lower
  3283. unsigned long tachMeasure = _micros();
  3284. cli();
  3285. SET_INPUT(TACH_1);
  3286. // just wait brutally in an endless cycle until we reach HIGH
  3287. // if this becomes a problem it may be improved to non-endless cycle
  3288. while( READ(TACH_1) == 0 ) ;
  3289. sei();
  3290. tachMeasure = _micros() - tachMeasure;
  3291. if( tach1max < tachMeasure )
  3292. tach1max = tachMeasure;
  3293. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3294. }
  3295. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3296. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3297. if( tach1max > 500 ){
  3298. // bad RAMBo
  3299. SERIAL_PROTOCOLLNPGM("BAD");
  3300. } else {
  3301. SERIAL_PROTOCOLLNPGM("OK");
  3302. }
  3303. // cleanup after the test function
  3304. SET_INPUT(TACH_1);
  3305. WRITE(TACH_1, HIGH);
  3306. #endif
  3307. }
  3308. // G92 - Set current position to coordinates given
  3309. static void gcode_G92()
  3310. {
  3311. bool codes[NUM_AXIS];
  3312. float values[NUM_AXIS];
  3313. // Check which axes need to be set
  3314. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3315. {
  3316. codes[i] = code_seen(axis_codes[i]);
  3317. if(codes[i])
  3318. values[i] = code_value();
  3319. }
  3320. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3321. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3322. {
  3323. // As a special optimization, when _just_ clearing the E position
  3324. // we schedule a flag asynchronously along with the next block to
  3325. // reset the starting E position instead of stopping the planner
  3326. current_position[E_AXIS] = 0;
  3327. plan_reset_next_e();
  3328. }
  3329. else
  3330. {
  3331. // In any other case we're forced to synchronize
  3332. st_synchronize();
  3333. for(uint8_t i = 0; i < 3; ++i)
  3334. {
  3335. if(codes[i])
  3336. current_position[i] = values[i] + cs.add_homing[i];
  3337. }
  3338. if(codes[E_AXIS])
  3339. current_position[E_AXIS] = values[E_AXIS];
  3340. // Set all at once
  3341. plan_set_position_curposXYZE();
  3342. }
  3343. }
  3344. #ifdef EXTENDED_CAPABILITIES_REPORT
  3345. static void cap_line(const char* name, bool ena = false) {
  3346. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3347. }
  3348. static void extended_capabilities_report()
  3349. {
  3350. // AUTOREPORT_TEMP (M155)
  3351. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3352. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3353. // AUTOREPORT_FANS (M123)
  3354. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3355. #endif //FANCHECK and TACH_0 or TACH_1
  3356. // AUTOREPORT_POSITION (M114)
  3357. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3358. // EXTENDED_M20 (support for L and T parameters)
  3359. cap_line(PSTR("EXTENDED_M20"), 1);
  3360. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3361. }
  3362. #endif //EXTENDED_CAPABILITIES_REPORT
  3363. #ifdef BACKLASH_X
  3364. extern uint8_t st_backlash_x;
  3365. #endif //BACKLASH_X
  3366. #ifdef BACKLASH_Y
  3367. extern uint8_t st_backlash_y;
  3368. #endif //BACKLASH_Y
  3369. //! \ingroup marlin_main
  3370. //! @brief Parse and process commands
  3371. //!
  3372. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3373. //!
  3374. //!
  3375. //! Implemented Codes
  3376. //! -------------------
  3377. //!
  3378. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3379. //!
  3380. //!@n PRUSA CODES
  3381. //!@n P F - Returns FW versions
  3382. //!@n P R - Returns revision of printer
  3383. //!
  3384. //!@n G0 -> G1
  3385. //!@n G1 - Coordinated Movement X Y Z E
  3386. //!@n G2 - CW ARC
  3387. //!@n G3 - CCW ARC
  3388. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3389. //!@n G10 - retract filament according to settings of M207
  3390. //!@n G11 - retract recover filament according to settings of M208
  3391. //!@n G28 - Home all Axes
  3392. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3393. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3394. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3395. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3396. //!@n G80 - Automatic mesh bed leveling
  3397. //!@n G81 - Print bed profile
  3398. //!@n G90 - Use Absolute Coordinates
  3399. //!@n G91 - Use Relative Coordinates
  3400. //!@n G92 - Set current position to coordinates given
  3401. //!
  3402. //!@n M Codes
  3403. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3404. //!@n M1 - Same as M0
  3405. //!@n M17 - Enable/Power all stepper motors
  3406. //!@n M18 - Disable all stepper motors; same as M84
  3407. //!@n M20 - List SD card
  3408. //!@n M21 - Init SD card
  3409. //!@n M22 - Release SD card
  3410. //!@n M23 - Select SD file (M23 filename.g)
  3411. //!@n M24 - Start/resume SD print
  3412. //!@n M25 - Pause SD print
  3413. //!@n M26 - Set SD position in bytes (M26 S12345)
  3414. //!@n M27 - Report SD print status
  3415. //!@n M28 - Start SD write (M28 filename.g)
  3416. //!@n M29 - Stop SD write
  3417. //!@n M30 - Delete file from SD (M30 filename.g)
  3418. //!@n M31 - Output time since last M109 or SD card start to serial
  3419. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3420. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3421. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3422. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3423. //!@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.
  3424. //!@n M73 - Show percent done and print time remaining
  3425. //!@n M80 - Turn on Power Supply
  3426. //!@n M81 - Turn off Power Supply
  3427. //!@n M82 - Set E codes absolute (default)
  3428. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3429. //!@n M84 - Disable steppers until next move,
  3430. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3431. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3432. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3433. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3434. //!@n M104 - Set extruder target temp
  3435. //!@n M105 - Read current temp
  3436. //!@n M106 - Fan on
  3437. //!@n M107 - Fan off
  3438. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3439. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3440. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3441. //!@n M112 - Emergency stop
  3442. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3443. //!@n M114 - Output current position to serial port
  3444. //!@n M115 - Capabilities string
  3445. //!@n M117 - display message
  3446. //!@n M119 - Output Endstop status to serial port
  3447. //!@n M123 - Tachometer value
  3448. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3449. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3450. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3451. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3452. //!@n M140 - Set bed target temp
  3453. //!@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.
  3454. //!@n M155 - Automatically send temperatures, fan speeds, position
  3455. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3456. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3457. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3458. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3459. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3460. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3461. //!@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
  3462. //!@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
  3463. //!@n M206 - set additional homing offset
  3464. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3465. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3466. //!@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.
  3467. //!@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>
  3468. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3469. //!@n M220 S<factor in percent>- set speed factor override percentage
  3470. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3471. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3472. //!@n M240 - Trigger a camera to take a photograph
  3473. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3474. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3475. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3476. //!@n M301 - Set PID parameters P I and D
  3477. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3478. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3479. //!@n M304 - Set bed PID parameters P I and D
  3480. //!@n M310 - Temperature model settings
  3481. //!@n M400 - Finish all moves
  3482. //!@n M401 - Lower z-probe if present
  3483. //!@n M402 - Raise z-probe if present
  3484. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3485. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3486. //!@n M406 - Turn off Filament Sensor extrusion control
  3487. //!@n M407 - Displays measured filament diameter
  3488. //!@n M500 - stores parameters in EEPROM
  3489. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3490. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3491. //!@n M503 - print the current settings (from memory not from EEPROM)
  3492. //!@n M509 - force language selection on next restart
  3493. //!@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)
  3494. //!@n M552 - Set IP address
  3495. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3496. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3497. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3498. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3499. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3500. //!@n M907 - Set digital trimpot motor current using axis codes.
  3501. //!@n M908 - Control digital trimpot directly.
  3502. //!@n M350 - Set microstepping mode.
  3503. //!@n M351 - Toggle MS1 MS2 pins directly.
  3504. //!
  3505. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3506. //!@n M999 - Restart after being stopped by error
  3507. //! <br><br>
  3508. /** @defgroup marlin_main Marlin main */
  3509. /** \ingroup GCodes */
  3510. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3511. /**
  3512. They are shown in order of appearance in the code.
  3513. There are reasons why some G Codes aren't in numerical order.
  3514. */
  3515. void process_commands()
  3516. {
  3517. if (!buflen) return; //empty command
  3518. #ifdef CMDBUFFER_DEBUG
  3519. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3520. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3521. SERIAL_ECHOLNPGM("");
  3522. SERIAL_ECHOPGM("In cmdqueue: ");
  3523. SERIAL_ECHO(buflen);
  3524. SERIAL_ECHOLNPGM("");
  3525. #endif /* CMDBUFFER_DEBUG */
  3526. unsigned long codenum; //throw away variable
  3527. char *starpos = NULL;
  3528. #ifdef ENABLE_AUTO_BED_LEVELING
  3529. float x_tmp, y_tmp, z_tmp, real_z;
  3530. #endif
  3531. // PRUSA GCODES
  3532. KEEPALIVE_STATE(IN_HANDLER);
  3533. /*!
  3534. ---------------------------------------------------------------------------------
  3535. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3536. This causes the given message to be shown in the status line on an attached LCD.
  3537. It is processed early as to allow printing messages that contain G, M, N or T.
  3538. ---------------------------------------------------------------------------------
  3539. ### Special internal commands
  3540. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3541. They are processed early as the commands are complex (strings).
  3542. These are only available on the MK3(S) as these require TMC2130 drivers:
  3543. - CRASH DETECTED
  3544. - CRASH RECOVER
  3545. - CRASH_CANCEL
  3546. - TMC_SET_WAVE
  3547. - TMC_SET_STEP
  3548. - TMC_SET_CHOP
  3549. */
  3550. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3551. {
  3552. starpos = (strchr(strchr_pointer + 5, '*'));
  3553. if (starpos != NULL)
  3554. *(starpos) = '\0';
  3555. lcd_setstatus(strchr_pointer + 5);
  3556. custom_message_type = CustomMsg::M117;
  3557. }
  3558. /*!
  3559. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3560. #### Usage
  3561. M0 [P<ms<] [S<sec>] [string]
  3562. M1 [P<ms>] [S<sec>] [string]
  3563. #### Parameters
  3564. - `P<ms>` - Expire time, in milliseconds
  3565. - `S<sec>` - Expire time, in seconds
  3566. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3567. */
  3568. 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
  3569. const char *src = strchr_pointer + 2;
  3570. codenum = 0;
  3571. bool hasP = false, hasS = false;
  3572. if (code_seen('P')) {
  3573. codenum = code_value_long(); // milliseconds to wait
  3574. hasP = codenum > 0;
  3575. }
  3576. if (code_seen('S')) {
  3577. codenum = code_value_long() * 1000; // seconds to wait
  3578. hasS = codenum > 0;
  3579. }
  3580. starpos = strchr(src, '*');
  3581. if (starpos != NULL) *(starpos) = '\0';
  3582. while (*src == ' ') ++src;
  3583. custom_message_type = CustomMsg::M0Wait;
  3584. if (!hasP && !hasS && *src != '\0') {
  3585. lcd_setstatus(src);
  3586. } else {
  3587. // farmers want to abuse a bug from the previous firmware releases
  3588. // - they need to see the filename on the status screen instead of "Wait for user..."
  3589. // So we won't update the message in farm mode...
  3590. if( ! farm_mode){
  3591. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3592. } else {
  3593. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3594. }
  3595. }
  3596. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3597. st_synchronize();
  3598. previous_millis_cmd.start();
  3599. if (codenum > 0 ) {
  3600. codenum += _millis(); // keep track of when we started waiting
  3601. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3602. while(_millis() < codenum && !lcd_clicked()) {
  3603. manage_heater();
  3604. manage_inactivity(true);
  3605. lcd_update(0);
  3606. }
  3607. KEEPALIVE_STATE(IN_HANDLER);
  3608. lcd_ignore_click(false);
  3609. } else {
  3610. marlin_wait_for_click();
  3611. }
  3612. if (IS_SD_PRINTING)
  3613. custom_message_type = CustomMsg::Status;
  3614. else
  3615. LCD_MESSAGERPGM(MSG_WELCOME);
  3616. }
  3617. #ifdef TMC2130
  3618. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3619. {
  3620. // ### CRASH_DETECTED - TMC2130
  3621. // ---------------------------------
  3622. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3623. {
  3624. uint8_t mask = 0;
  3625. if (code_seen('X')) mask |= X_AXIS_MASK;
  3626. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3627. crashdet_detected(mask);
  3628. }
  3629. // ### CRASH_RECOVER - TMC2130
  3630. // ----------------------------------
  3631. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3632. crashdet_recover();
  3633. // ### CRASH_CANCEL - TMC2130
  3634. // ----------------------------------
  3635. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3636. crashdet_cancel();
  3637. }
  3638. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3639. {
  3640. // ### TMC_SET_WAVE_
  3641. // --------------------
  3642. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3643. {
  3644. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3645. axis = (axis == 'E')?3:(axis - 'X');
  3646. if (axis < 4)
  3647. {
  3648. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3649. tmc2130_set_wave(axis, 247, fac);
  3650. }
  3651. }
  3652. // ### TMC_SET_STEP_
  3653. // ------------------
  3654. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3655. {
  3656. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3657. axis = (axis == 'E')?3:(axis - 'X');
  3658. if (axis < 4)
  3659. {
  3660. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3661. uint16_t res = tmc2130_get_res(axis);
  3662. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3663. }
  3664. }
  3665. // ### TMC_SET_CHOP_
  3666. // -------------------
  3667. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 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 chop0 = tmc2130_chopper_config[axis].toff;
  3674. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3675. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3676. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3677. char* str_end = 0;
  3678. if (CMDBUFFER_CURRENT_STRING[14])
  3679. {
  3680. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3681. if (str_end && *str_end)
  3682. {
  3683. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3684. if (str_end && *str_end)
  3685. {
  3686. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3687. if (str_end && *str_end)
  3688. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3689. }
  3690. }
  3691. }
  3692. tmc2130_chopper_config[axis].toff = chop0;
  3693. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3694. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3695. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3696. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3697. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3698. }
  3699. }
  3700. }
  3701. #ifdef BACKLASH_X
  3702. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3703. {
  3704. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3705. st_backlash_x = bl;
  3706. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3707. }
  3708. #endif //BACKLASH_X
  3709. #ifdef BACKLASH_Y
  3710. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3711. {
  3712. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3713. st_backlash_y = bl;
  3714. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3715. }
  3716. #endif //BACKLASH_Y
  3717. #endif //TMC2130
  3718. else if(code_seen_P(PSTR("PRUSA"))){
  3719. /*!
  3720. ---------------------------------------------------------------------------------
  3721. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3722. Set of internal PRUSA commands
  3723. #### Usage
  3724. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3725. #### Parameters
  3726. - `PRN` - Prints revision of the printer
  3727. - `FAN` - Prints fan details
  3728. - `thx`
  3729. - `uvlo`
  3730. - `MMURES` - Reset MMU
  3731. - `RESET` - (Careful!)
  3732. - `fv` - ?
  3733. - `M28`
  3734. - `SN`
  3735. - `Fir` - Prints firmware version
  3736. - `Rev`- Prints filament size, elelectronics, nozzle type
  3737. - `Lang` - Reset the language
  3738. - `Lz`
  3739. - `FR` - Full factory reset
  3740. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3741. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3742. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3743. */
  3744. if (farm_prusa_code_seen()) {}
  3745. else if(code_seen_P(PSTR("FANPINTST"))) {
  3746. gcode_PRUSA_BadRAMBoFanTest();
  3747. }
  3748. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3749. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3750. }
  3751. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3752. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3753. enquecommand_P(PSTR("M24"));
  3754. }
  3755. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3756. {
  3757. mmu_reset();
  3758. }
  3759. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3760. #ifdef WATCHDOG
  3761. #if defined(XFLASH) && defined(BOOTAPP)
  3762. boot_app_magic = BOOT_APP_MAGIC;
  3763. boot_app_flags = BOOT_APP_FLG_RUN;
  3764. #endif //defined(XFLASH) && defined(BOOTAPP)
  3765. softReset();
  3766. #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.
  3767. asm volatile("jmp 0x3E000");
  3768. #endif
  3769. }
  3770. #ifdef PRUSA_SN_SUPPORT
  3771. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3772. char SN[20];
  3773. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3774. if (SN[19])
  3775. puts_P(PSTR("SN invalid"));
  3776. else
  3777. puts(SN);
  3778. }
  3779. #endif //PRUSA_SN_SUPPORT
  3780. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3781. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3782. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3783. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3784. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3785. lang_reset();
  3786. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3787. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3788. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3789. // Factory full reset
  3790. factory_reset(0);
  3791. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3792. // Change the MBL status without changing the logical Z position.
  3793. if(code_seen('V')) {
  3794. bool value = code_value_short();
  3795. st_synchronize();
  3796. if(value != mbl.active) {
  3797. mbl.active = value;
  3798. // Use plan_set_z_position to reset the physical values
  3799. plan_set_z_position(current_position[Z_AXIS]);
  3800. }
  3801. }
  3802. //-//
  3803. /*
  3804. } else if(code_seen("rrr")) {
  3805. MYSERIAL.println("=== checking ===");
  3806. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3807. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3808. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3809. MYSERIAL.println(farm_mode,DEC);
  3810. MYSERIAL.println(eCheckMode,DEC);
  3811. } else if(code_seen("www")) {
  3812. MYSERIAL.println("=== @ FF ===");
  3813. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3814. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3815. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3816. */
  3817. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3818. uint16_t nDiameter;
  3819. if(code_seen('D'))
  3820. {
  3821. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3822. nozzle_diameter_check(nDiameter);
  3823. }
  3824. else if(code_seen_P(PSTR("set")) && farm_mode)
  3825. {
  3826. strchr_pointer++; // skip 1st char (~ 's')
  3827. strchr_pointer++; // skip 2nd char (~ 'e')
  3828. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3829. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3830. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3831. }
  3832. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3833. //-// !!! SupportMenu
  3834. /*
  3835. // musi byt PRED "PRUSA model"
  3836. } else if (code_seen("smodel")) { //! PRUSA smodel
  3837. size_t nOffset;
  3838. // ! -> "l"
  3839. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3840. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3841. if(*(strchr_pointer+1+nOffset))
  3842. printer_smodel_check(strchr_pointer);
  3843. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3844. } else if (code_seen("model")) { //! PRUSA model
  3845. uint16_t nPrinterModel;
  3846. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3847. nPrinterModel=(uint16_t)code_value_long();
  3848. if(nPrinterModel!=0)
  3849. printer_model_check(nPrinterModel);
  3850. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3851. } else if (code_seen("version")) { //! PRUSA version
  3852. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3853. while(*strchr_pointer==' ') // skip leading spaces
  3854. strchr_pointer++;
  3855. if(*strchr_pointer!=0)
  3856. fw_version_check(strchr_pointer);
  3857. else SERIAL_PROTOCOLLN(FW_VERSION);
  3858. } else if (code_seen("gcode")) { //! PRUSA gcode
  3859. uint16_t nGcodeLevel;
  3860. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3861. nGcodeLevel=(uint16_t)code_value_long();
  3862. if(nGcodeLevel!=0)
  3863. gcode_level_check(nGcodeLevel);
  3864. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3865. */
  3866. }
  3867. //else if (code_seen('Cal')) {
  3868. // lcd_calibration();
  3869. // }
  3870. }
  3871. // This prevents reading files with "^" in their names.
  3872. // Since it is unclear, if there is some usage of this construct,
  3873. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3874. // else if (code_seen('^')) {
  3875. // // nothing, this is a version line
  3876. // }
  3877. else if(code_seen('G'))
  3878. {
  3879. gcode_in_progress = code_value_short();
  3880. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3881. switch (gcode_in_progress)
  3882. {
  3883. /*!
  3884. ---------------------------------------------------------------------------------
  3885. # G Codes
  3886. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3887. In Prusa Firmware G0 and G1 are the same.
  3888. #### Usage
  3889. G0 [ X | Y | Z | E | F | S ]
  3890. G1 [ X | Y | Z | E | F | S ]
  3891. #### Parameters
  3892. - `X` - The position to move to on the X axis
  3893. - `Y` - The position to move to on the Y axis
  3894. - `Z` - The position to move to on the Z axis
  3895. - `E` - The amount to extrude between the starting point and ending point
  3896. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3897. */
  3898. case 0: // G0 -> G1
  3899. case 1: // G1
  3900. {
  3901. uint16_t start_segment_idx = restore_interrupted_gcode();
  3902. get_coordinates(); // For X Y Z E F
  3903. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3904. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3905. }
  3906. #ifdef FWRETRACT
  3907. if(cs.autoretract_enabled) {
  3908. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3909. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3910. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3911. st_synchronize();
  3912. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3913. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3914. retract(!retracted[active_extruder]);
  3915. return;
  3916. }
  3917. }
  3918. }
  3919. #endif //FWRETRACT
  3920. prepare_move(start_segment_idx);
  3921. //ClearToSend();
  3922. }
  3923. break;
  3924. /*!
  3925. ### 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>
  3926. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3927. #### Usage
  3928. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3929. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3930. #### Parameters
  3931. - `X` - The position to move to on the X axis
  3932. - `Y` - The position to move to on the Y axis
  3933. - 'Z' - The position to move to on the Z axis
  3934. - `I` - The point in X space from the current X position to maintain a constant distance from
  3935. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3936. - `E` - The amount to extrude between the starting point and ending point
  3937. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3938. */
  3939. case 2:
  3940. case 3:
  3941. {
  3942. uint16_t start_segment_idx = restore_interrupted_gcode();
  3943. #ifdef SF_ARC_FIX
  3944. bool relative_mode_backup = relative_mode;
  3945. relative_mode = true;
  3946. #endif
  3947. get_coordinates(); // For X Y Z E F
  3948. #ifdef SF_ARC_FIX
  3949. relative_mode=relative_mode_backup;
  3950. #endif
  3951. offset[0] = code_seen('I') ? code_value() : 0.f;
  3952. offset[1] = code_seen('J') ? code_value() : 0.f;
  3953. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3954. } break;
  3955. /*!
  3956. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3957. Pause the machine for a period of time.
  3958. #### Usage
  3959. G4 [ P | S ]
  3960. #### Parameters
  3961. - `P` - Time to wait, in milliseconds
  3962. - `S` - Time to wait, in seconds
  3963. */
  3964. case 4:
  3965. codenum = 0;
  3966. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3967. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3968. if(codenum != 0)
  3969. {
  3970. if(custom_message_type != CustomMsg::M117)
  3971. {
  3972. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3973. }
  3974. }
  3975. st_synchronize();
  3976. codenum += _millis(); // keep track of when we started waiting
  3977. previous_millis_cmd.start();
  3978. while(_millis() < codenum) {
  3979. manage_heater();
  3980. manage_inactivity();
  3981. lcd_update(0);
  3982. }
  3983. break;
  3984. #ifdef FWRETRACT
  3985. /*!
  3986. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3987. Retracts filament according to settings of `M207`
  3988. */
  3989. case 10:
  3990. #if EXTRUDERS > 1
  3991. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3992. retract(true,retracted_swap[active_extruder]);
  3993. #else
  3994. retract(true);
  3995. #endif
  3996. break;
  3997. /*!
  3998. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3999. Unretracts/recovers filament according to settings of `M208`
  4000. */
  4001. case 11:
  4002. #if EXTRUDERS > 1
  4003. retract(false,retracted_swap[active_extruder]);
  4004. #else
  4005. retract(false);
  4006. #endif
  4007. break;
  4008. #endif //FWRETRACT
  4009. /*!
  4010. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  4011. Units are in millimeters. Prusa doesn't support inches.
  4012. */
  4013. case 21:
  4014. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  4015. /*!
  4016. ### 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>
  4017. 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).
  4018. #### Usage
  4019. G28 [ X | Y | Z | W | C ]
  4020. #### Parameters
  4021. - `X` - Flag to go back to the X axis origin
  4022. - `Y` - Flag to go back to the Y axis origin
  4023. - `Z` - Flag to go back to the Z axis origin
  4024. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  4025. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  4026. */
  4027. case 28:
  4028. {
  4029. long home_x_value = 0;
  4030. long home_y_value = 0;
  4031. long home_z_value = 0;
  4032. // Which axes should be homed?
  4033. bool home_x = code_seen(axis_codes[X_AXIS]);
  4034. if (home_x) home_x_value = code_value_long();
  4035. bool home_y = code_seen(axis_codes[Y_AXIS]);
  4036. if (home_y) home_y_value = code_value_long();
  4037. bool home_z = code_seen(axis_codes[Z_AXIS]);
  4038. if (home_z) home_z_value = code_value_long();
  4039. bool without_mbl = code_seen('W');
  4040. // calibrate?
  4041. #ifdef TMC2130
  4042. bool calib = code_seen('C');
  4043. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4044. #else
  4045. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4046. #endif //TMC2130
  4047. if ((home_x || home_y || without_mbl || home_z) == false) {
  4048. gcode_G80();
  4049. }
  4050. break;
  4051. }
  4052. #ifdef ENABLE_AUTO_BED_LEVELING
  4053. /*!
  4054. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4055. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4056. See `G81`
  4057. */
  4058. case 29:
  4059. {
  4060. #if Z_MIN_PIN == -1
  4061. #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."
  4062. #endif
  4063. // Prevent user from running a G29 without first homing in X and Y
  4064. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4065. {
  4066. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4067. SERIAL_ECHO_START;
  4068. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4069. break; // abort G29, since we don't know where we are
  4070. }
  4071. st_synchronize();
  4072. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4073. //vector_3 corrected_position = plan_get_position_mm();
  4074. //corrected_position.debug("position before G29");
  4075. plan_bed_level_matrix.set_to_identity();
  4076. vector_3 uncorrected_position = plan_get_position();
  4077. //uncorrected_position.debug("position durring G29");
  4078. current_position[X_AXIS] = uncorrected_position.x;
  4079. current_position[Y_AXIS] = uncorrected_position.y;
  4080. current_position[Z_AXIS] = uncorrected_position.z;
  4081. plan_set_position_curposXYZE();
  4082. int l_feedmultiply = setup_for_endstop_move();
  4083. feedrate = homing_feedrate[Z_AXIS];
  4084. #ifdef AUTO_BED_LEVELING_GRID
  4085. // probe at the points of a lattice grid
  4086. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4087. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4088. // solve the plane equation ax + by + d = z
  4089. // A is the matrix with rows [x y 1] for all the probed points
  4090. // B is the vector of the Z positions
  4091. // 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
  4092. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4093. // "A" matrix of the linear system of equations
  4094. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4095. // "B" vector of Z points
  4096. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4097. int probePointCounter = 0;
  4098. bool zig = true;
  4099. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4100. {
  4101. int xProbe, xInc;
  4102. if (zig)
  4103. {
  4104. xProbe = LEFT_PROBE_BED_POSITION;
  4105. //xEnd = RIGHT_PROBE_BED_POSITION;
  4106. xInc = xGridSpacing;
  4107. zig = false;
  4108. } else // zag
  4109. {
  4110. xProbe = RIGHT_PROBE_BED_POSITION;
  4111. //xEnd = LEFT_PROBE_BED_POSITION;
  4112. xInc = -xGridSpacing;
  4113. zig = true;
  4114. }
  4115. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4116. {
  4117. float z_before;
  4118. if (probePointCounter == 0)
  4119. {
  4120. // raise before probing
  4121. z_before = Z_RAISE_BEFORE_PROBING;
  4122. } else
  4123. {
  4124. // raise extruder
  4125. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4126. }
  4127. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4128. eqnBVector[probePointCounter] = measured_z;
  4129. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4130. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4131. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4132. probePointCounter++;
  4133. xProbe += xInc;
  4134. }
  4135. }
  4136. clean_up_after_endstop_move(l_feedmultiply);
  4137. // solve lsq problem
  4138. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4139. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4140. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4141. SERIAL_PROTOCOLPGM(" b: ");
  4142. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4143. SERIAL_PROTOCOLPGM(" d: ");
  4144. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4145. set_bed_level_equation_lsq(plane_equation_coefficients);
  4146. free(plane_equation_coefficients);
  4147. #else // AUTO_BED_LEVELING_GRID not defined
  4148. // Probe at 3 arbitrary points
  4149. // probe 1
  4150. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4151. // probe 2
  4152. 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);
  4153. // probe 3
  4154. 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);
  4155. clean_up_after_endstop_move(l_feedmultiply);
  4156. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4157. #endif // AUTO_BED_LEVELING_GRID
  4158. st_synchronize();
  4159. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4160. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4161. // When the bed is uneven, this height must be corrected.
  4162. 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)
  4163. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4164. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4165. z_tmp = current_position[Z_AXIS];
  4166. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4167. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4168. plan_set_position_curposXYZE();
  4169. }
  4170. break;
  4171. #ifndef Z_PROBE_SLED
  4172. /*!
  4173. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4174. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4175. */
  4176. case 30:
  4177. {
  4178. st_synchronize();
  4179. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4180. int l_feedmultiply = setup_for_endstop_move();
  4181. feedrate = homing_feedrate[Z_AXIS];
  4182. run_z_probe();
  4183. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4184. SERIAL_PROTOCOLPGM(" X: ");
  4185. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4186. SERIAL_PROTOCOLPGM(" Y: ");
  4187. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4188. SERIAL_PROTOCOLPGM(" Z: ");
  4189. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4190. SERIAL_PROTOCOLPGM("\n");
  4191. clean_up_after_endstop_move(l_feedmultiply);
  4192. }
  4193. break;
  4194. #else
  4195. /*!
  4196. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4197. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4198. */
  4199. case 31:
  4200. dock_sled(true);
  4201. break;
  4202. /*!
  4203. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4204. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4205. */
  4206. case 32:
  4207. dock_sled(false);
  4208. break;
  4209. #endif // Z_PROBE_SLED
  4210. #endif // ENABLE_AUTO_BED_LEVELING
  4211. #ifdef MESH_BED_LEVELING
  4212. /*!
  4213. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4214. Sensor must be over the bed.
  4215. The maximum travel distance before an error is triggered is 10mm.
  4216. */
  4217. case 30:
  4218. {
  4219. st_synchronize();
  4220. homing_flag = true;
  4221. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4222. int l_feedmultiply = setup_for_endstop_move();
  4223. feedrate = homing_feedrate[Z_AXIS];
  4224. find_bed_induction_sensor_point_z(-10.f, 3);
  4225. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4226. clean_up_after_endstop_move(l_feedmultiply);
  4227. homing_flag = false;
  4228. }
  4229. break;
  4230. /*!
  4231. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4232. Show/print PINDA temperature interpolating.
  4233. */
  4234. case 75:
  4235. {
  4236. for (uint8_t i = 40; i <= 110; i++)
  4237. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4238. }
  4239. break;
  4240. /*!
  4241. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4242. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4243. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4244. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4245. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4246. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4247. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4248. #### Example
  4249. ```
  4250. G76
  4251. echo PINDA probe calibration start
  4252. echo start temperature: 35.0°
  4253. echo ...
  4254. echo PINDA temperature -- Z shift (mm): 0.---
  4255. ```
  4256. */
  4257. case 76:
  4258. {
  4259. #ifdef PINDA_THERMISTOR
  4260. if (!has_temperature_compensation())
  4261. {
  4262. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4263. break;
  4264. }
  4265. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4266. //we need to know accurate position of first calibration point
  4267. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4268. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4269. break;
  4270. }
  4271. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4272. {
  4273. // We don't know where we are! HOME!
  4274. // Push the commands to the front of the message queue in the reverse order!
  4275. // There shall be always enough space reserved for these commands.
  4276. repeatcommand_front(); // repeat G76 with all its parameters
  4277. enquecommand_front_P(G28W0);
  4278. break;
  4279. }
  4280. 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
  4281. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  4282. if (result)
  4283. {
  4284. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4285. plan_buffer_line_curposXYZE(3000 / 60);
  4286. current_position[Z_AXIS] = 50;
  4287. current_position[Y_AXIS] = 180;
  4288. plan_buffer_line_curposXYZE(3000 / 60);
  4289. st_synchronize();
  4290. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4291. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4292. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4293. plan_buffer_line_curposXYZE(3000 / 60);
  4294. st_synchronize();
  4295. gcode_G28(false, false, true);
  4296. }
  4297. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4298. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4299. current_position[Z_AXIS] = 100;
  4300. plan_buffer_line_curposXYZE(3000 / 60);
  4301. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4302. lcd_temp_cal_show_result(false);
  4303. break;
  4304. }
  4305. }
  4306. st_synchronize();
  4307. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4308. lcd_update_enable(true);
  4309. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4310. float zero_z;
  4311. int z_shift = 0; //unit: steps
  4312. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4313. if (start_temp < 35) start_temp = 35;
  4314. if (start_temp < current_temperature_pinda) start_temp += 5;
  4315. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4316. // setTargetHotend(200, 0);
  4317. setTargetBed(70 + (start_temp - 30));
  4318. custom_message_type = CustomMsg::TempCal;
  4319. custom_message_state = 1;
  4320. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4321. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4322. plan_buffer_line_curposXYZE(3000 / 60);
  4323. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4324. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4325. plan_buffer_line_curposXYZE(3000 / 60);
  4326. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4327. plan_buffer_line_curposXYZE(3000 / 60);
  4328. st_synchronize();
  4329. while (current_temperature_pinda < start_temp)
  4330. {
  4331. delay_keep_alive(1000);
  4332. serialecho_temperatures();
  4333. }
  4334. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4335. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4336. plan_buffer_line_curposXYZE(3000 / 60);
  4337. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4338. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4339. plan_buffer_line_curposXYZE(3000 / 60);
  4340. st_synchronize();
  4341. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4342. if (find_z_result == false) {
  4343. lcd_temp_cal_show_result(find_z_result);
  4344. homing_flag = false;
  4345. break;
  4346. }
  4347. zero_z = current_position[Z_AXIS];
  4348. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4349. int i = -1; for (; i < 5; i++)
  4350. {
  4351. float temp = (40 + i * 5);
  4352. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4353. if (i >= 0) {
  4354. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4355. }
  4356. if (start_temp <= temp) break;
  4357. }
  4358. for (i++; i < 5; i++)
  4359. {
  4360. float temp = (40 + i * 5);
  4361. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4362. custom_message_state = i + 2;
  4363. setTargetBed(50 + 10 * (temp - 30) / 5);
  4364. // setTargetHotend(255, 0);
  4365. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4366. plan_buffer_line_curposXYZE(3000 / 60);
  4367. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4368. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4369. plan_buffer_line_curposXYZE(3000 / 60);
  4370. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4371. plan_buffer_line_curposXYZE(3000 / 60);
  4372. st_synchronize();
  4373. while (current_temperature_pinda < temp)
  4374. {
  4375. delay_keep_alive(1000);
  4376. serialecho_temperatures();
  4377. }
  4378. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4379. plan_buffer_line_curposXYZE(3000 / 60);
  4380. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4381. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4382. plan_buffer_line_curposXYZE(3000 / 60);
  4383. st_synchronize();
  4384. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4385. if (find_z_result == false) {
  4386. lcd_temp_cal_show_result(find_z_result);
  4387. break;
  4388. }
  4389. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4390. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4391. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4392. }
  4393. lcd_temp_cal_show_result(true);
  4394. homing_flag = false;
  4395. #else //PINDA_THERMISTOR
  4396. setTargetBed(PINDA_MIN_T);
  4397. float zero_z;
  4398. int z_shift = 0; //unit: steps
  4399. int t_c; // temperature
  4400. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4401. // We don't know where we are! HOME!
  4402. // Push the commands to the front of the message queue in the reverse order!
  4403. // There shall be always enough space reserved for these commands.
  4404. repeatcommand_front(); // repeat G76 with all its parameters
  4405. enquecommand_front_P(G28W0);
  4406. break;
  4407. }
  4408. puts_P(_N("PINDA probe calibration start"));
  4409. custom_message_type = CustomMsg::TempCal;
  4410. custom_message_state = 1;
  4411. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4412. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4413. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4414. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4415. plan_buffer_line_curposXYZE(3000 / 60);
  4416. st_synchronize();
  4417. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4418. delay_keep_alive(1000);
  4419. serialecho_temperatures();
  4420. }
  4421. //enquecommand_P(PSTR("M190 S50"));
  4422. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4423. delay_keep_alive(1000);
  4424. serialecho_temperatures();
  4425. }
  4426. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4427. current_position[Z_AXIS] = 5;
  4428. plan_buffer_line_curposXYZE(3000 / 60);
  4429. current_position[X_AXIS] = BED_X0;
  4430. current_position[Y_AXIS] = BED_Y0;
  4431. plan_buffer_line_curposXYZE(3000 / 60);
  4432. st_synchronize();
  4433. find_bed_induction_sensor_point_z(-1.f);
  4434. zero_z = current_position[Z_AXIS];
  4435. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4436. for (int i = 0; i<5; i++) {
  4437. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4438. custom_message_state = i + 2;
  4439. t_c = 60 + i * 10;
  4440. setTargetBed(t_c);
  4441. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4442. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4443. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4444. plan_buffer_line_curposXYZE(3000 / 60);
  4445. st_synchronize();
  4446. while (degBed() < t_c) {
  4447. delay_keep_alive(1000);
  4448. serialecho_temperatures();
  4449. }
  4450. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4451. delay_keep_alive(1000);
  4452. serialecho_temperatures();
  4453. }
  4454. current_position[Z_AXIS] = 5;
  4455. plan_buffer_line_curposXYZE(3000 / 60);
  4456. current_position[X_AXIS] = BED_X0;
  4457. current_position[Y_AXIS] = BED_Y0;
  4458. plan_buffer_line_curposXYZE(3000 / 60);
  4459. st_synchronize();
  4460. find_bed_induction_sensor_point_z(-1.f);
  4461. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4462. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4463. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4464. }
  4465. custom_message_type = CustomMsg::Status;
  4466. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4467. puts_P(_N("Temperature calibration done."));
  4468. disable_x();
  4469. disable_y();
  4470. disable_z();
  4471. disable_e0();
  4472. disable_e1();
  4473. disable_e2();
  4474. setTargetBed(0); //set bed target temperature back to 0
  4475. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4476. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4477. lcd_update_enable(true);
  4478. lcd_update(2);
  4479. #endif //PINDA_THERMISTOR
  4480. }
  4481. break;
  4482. /*!
  4483. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4484. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4485. #### Usage
  4486. G80 [ N | R | V | L | R | F | B ]
  4487. #### Parameters
  4488. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4489. - `R` - Probe retries. Default 3 max. 10
  4490. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4491. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4492. #### Additional Parameters
  4493. - `L` - Left Bed Level correct value in um.
  4494. - `R` - Right Bed Level correct value in um.
  4495. - `F` - Front Bed Level correct value in um.
  4496. - `B` - Back Bed Level correct value in um.
  4497. */
  4498. /*
  4499. * Probes a grid and produces a mesh to compensate for variable bed height
  4500. * The S0 report the points as below
  4501. * +----> X-axis
  4502. * |
  4503. * |
  4504. * v Y-axis
  4505. */
  4506. case 80: {
  4507. gcode_G80();
  4508. }
  4509. break;
  4510. /*!
  4511. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4512. Prints mesh bed leveling status and bed profile if activated.
  4513. */
  4514. case 81:
  4515. if (mbl.active) {
  4516. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4517. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4518. SERIAL_PROTOCOL(',');
  4519. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4520. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4521. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4522. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4523. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4524. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4525. SERIAL_PROTOCOLPGM(" ");
  4526. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4527. }
  4528. SERIAL_PROTOCOLLN();
  4529. }
  4530. }
  4531. else
  4532. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4533. break;
  4534. #if 0
  4535. /*!
  4536. ### 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>
  4537. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4538. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4539. */
  4540. case 82:
  4541. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4542. int l_feedmultiply = setup_for_endstop_move();
  4543. find_bed_induction_sensor_point_z();
  4544. clean_up_after_endstop_move(l_feedmultiply);
  4545. SERIAL_PROTOCOLPGM("Bed found at: ");
  4546. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4547. SERIAL_PROTOCOLPGM("\n");
  4548. break;
  4549. /*!
  4550. ### 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>
  4551. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4552. */
  4553. case 83:
  4554. {
  4555. int babystepz = code_seen('S') ? code_value() : 0;
  4556. int BabyPosition = code_seen('P') ? code_value() : 0;
  4557. if (babystepz != 0) {
  4558. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4559. // Is the axis indexed starting with zero or one?
  4560. if (BabyPosition > 4) {
  4561. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4562. }else{
  4563. // Save it to the eeprom
  4564. babystepLoadZ = babystepz;
  4565. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4566. // adjust the Z
  4567. babystepsTodoZadd(babystepLoadZ);
  4568. }
  4569. }
  4570. }
  4571. break;
  4572. /*!
  4573. ### 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>
  4574. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4575. */
  4576. case 84:
  4577. babystepsTodoZsubtract(babystepLoadZ);
  4578. // babystepLoadZ = 0;
  4579. break;
  4580. /*!
  4581. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4582. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4583. */
  4584. case 85:
  4585. lcd_pick_babystep();
  4586. break;
  4587. #endif
  4588. /*!
  4589. ### 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>
  4590. This G-code will be performed at the start of a calibration script.
  4591. (Prusa3D specific)
  4592. */
  4593. case 86:
  4594. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4595. break;
  4596. /*!
  4597. ### 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>
  4598. This G-code will be performed at the end of a calibration script.
  4599. (Prusa3D specific)
  4600. */
  4601. case 87:
  4602. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4603. break;
  4604. /*!
  4605. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4606. Currently has no effect.
  4607. */
  4608. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4609. case 88:
  4610. break;
  4611. #endif // ENABLE_MESH_BED_LEVELING
  4612. /*!
  4613. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4614. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4615. */
  4616. case 90: {
  4617. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4618. }
  4619. break;
  4620. /*!
  4621. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4622. All coordinates from now on are relative to the last position. E axis is left intact.
  4623. */
  4624. case 91: {
  4625. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4626. }
  4627. break;
  4628. /*!
  4629. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4630. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4631. If a parameter is omitted, that axis will not be affected.
  4632. 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`).
  4633. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4634. #### Usage
  4635. G92 [ X | Y | Z | E ]
  4636. #### Parameters
  4637. - `X` - new X axis position
  4638. - `Y` - new Y axis position
  4639. - `Z` - new Z axis position
  4640. - `E` - new extruder position
  4641. */
  4642. case 92: {
  4643. gcode_G92();
  4644. }
  4645. break;
  4646. #ifdef PRUSA_FARM
  4647. /*!
  4648. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4649. Enable Prusa-specific Farm functions and g-code.
  4650. See Internal Prusa commands.
  4651. */
  4652. case 98:
  4653. farm_gcode_g98();
  4654. break;
  4655. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4656. Disables Prusa-specific Farm functions and g-code.
  4657. */
  4658. case 99:
  4659. farm_gcode_g99();
  4660. break;
  4661. #endif //PRUSA_FARM
  4662. default:
  4663. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4664. }
  4665. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4666. gcode_in_progress = 0;
  4667. } // end if(code_seen('G'))
  4668. /*!
  4669. ### End of G-Codes
  4670. */
  4671. /*!
  4672. ---------------------------------------------------------------------------------
  4673. # M Commands
  4674. */
  4675. else if(code_seen('M'))
  4676. {
  4677. int index;
  4678. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4679. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4680. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4681. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4682. } else
  4683. {
  4684. mcode_in_progress = code_value_short();
  4685. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4686. switch(mcode_in_progress)
  4687. {
  4688. /*!
  4689. ### 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>
  4690. */
  4691. case 17:
  4692. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4693. enable_x();
  4694. enable_y();
  4695. enable_z();
  4696. enable_e0();
  4697. enable_e1();
  4698. enable_e2();
  4699. break;
  4700. #ifdef SDSUPPORT
  4701. /*!
  4702. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4703. #### Usage
  4704. M20 [ L | T ]
  4705. #### Parameters
  4706. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4707. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4708. */
  4709. case 20:
  4710. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4711. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4712. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4713. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4714. break;
  4715. /*!
  4716. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4717. */
  4718. case 21:
  4719. card.initsd();
  4720. break;
  4721. /*!
  4722. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4723. */
  4724. case 22:
  4725. card.release();
  4726. break;
  4727. /*!
  4728. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4729. #### Usage
  4730. M23 [filename]
  4731. */
  4732. case 23:
  4733. starpos = (strchr(strchr_pointer + 4,'*'));
  4734. if(starpos!=NULL)
  4735. *(starpos)='\0';
  4736. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4737. break;
  4738. /*!
  4739. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4740. */
  4741. case 24:
  4742. if (isPrintPaused)
  4743. lcd_resume_print();
  4744. else
  4745. {
  4746. if (!card.get_sdpos())
  4747. {
  4748. // A new print has started from scratch, reset stats
  4749. failstats_reset_print();
  4750. sdpos_atomic = 0;
  4751. #ifndef LA_NOCOMPAT
  4752. la10c_reset();
  4753. #endif
  4754. }
  4755. card.startFileprint();
  4756. starttime=_millis();
  4757. }
  4758. break;
  4759. /*!
  4760. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4761. Set position in SD card file to index in bytes.
  4762. This command is expected to be called after M23 and before M24.
  4763. Otherwise effect of this command is undefined.
  4764. #### Usage
  4765. M26 [ S ]
  4766. #### Parameters
  4767. - `S` - Index in bytes
  4768. */
  4769. case 26:
  4770. if(card.cardOK && code_seen('S')) {
  4771. long index = code_value_long();
  4772. card.setIndex(index);
  4773. // We don't disable interrupt during update of sdpos_atomic
  4774. // as we expect, that SD card print is not active in this moment
  4775. sdpos_atomic = index;
  4776. }
  4777. break;
  4778. /*!
  4779. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4780. #### Usage
  4781. M27 [ P ]
  4782. #### Parameters
  4783. - `P` - Show full SFN path instead of LFN only.
  4784. */
  4785. case 27:
  4786. card.getStatus(code_seen('P'));
  4787. break;
  4788. /*!
  4789. ### 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>
  4790. */
  4791. case 28:
  4792. starpos = (strchr(strchr_pointer + 4,'*'));
  4793. if(starpos != NULL){
  4794. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4795. strchr_pointer = strchr(npos,' ') + 1;
  4796. *(starpos) = '\0';
  4797. }
  4798. card.openFileWrite(strchr_pointer+4);
  4799. break;
  4800. /*! ### 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>
  4801. 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.
  4802. */
  4803. case 29:
  4804. //processed in write to file routine above
  4805. //card,saving = false;
  4806. break;
  4807. /*!
  4808. ### 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>
  4809. #### Usage
  4810. M30 [filename]
  4811. */
  4812. case 30:
  4813. if (card.cardOK){
  4814. card.closefile();
  4815. starpos = (strchr(strchr_pointer + 4,'*'));
  4816. if(starpos != NULL){
  4817. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4818. strchr_pointer = strchr(npos,' ') + 1;
  4819. *(starpos) = '\0';
  4820. }
  4821. card.removeFile(strchr_pointer + 4);
  4822. }
  4823. break;
  4824. /*!
  4825. ### 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>
  4826. @todo What are the parameters P and S for in M32?
  4827. */
  4828. case 32:
  4829. {
  4830. if(card.sdprinting) {
  4831. st_synchronize();
  4832. }
  4833. starpos = (strchr(strchr_pointer + 4,'*'));
  4834. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4835. if(namestartpos==NULL)
  4836. {
  4837. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4838. }
  4839. else
  4840. namestartpos++; //to skip the '!'
  4841. if(starpos!=NULL)
  4842. *(starpos)='\0';
  4843. bool call_procedure=(code_seen('P'));
  4844. if(strchr_pointer>namestartpos)
  4845. call_procedure=false; //false alert, 'P' found within filename
  4846. if( card.cardOK )
  4847. {
  4848. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4849. if(code_seen('S'))
  4850. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4851. card.setIndex(code_value_long());
  4852. card.startFileprint();
  4853. if(!call_procedure)
  4854. {
  4855. if(!card.get_sdpos())
  4856. {
  4857. // A new print has started from scratch, reset stats
  4858. failstats_reset_print();
  4859. sdpos_atomic = 0;
  4860. #ifndef LA_NOCOMPAT
  4861. la10c_reset();
  4862. #endif
  4863. }
  4864. starttime=_millis(); // procedure calls count as normal print time.
  4865. }
  4866. }
  4867. } break;
  4868. /*!
  4869. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4870. #### Usage
  4871. M928 [filename]
  4872. */
  4873. case 928:
  4874. starpos = (strchr(strchr_pointer + 5,'*'));
  4875. if(starpos != NULL){
  4876. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4877. strchr_pointer = strchr(npos,' ') + 1;
  4878. *(starpos) = '\0';
  4879. }
  4880. card.openLogFile(strchr_pointer+5);
  4881. break;
  4882. #endif //SDSUPPORT
  4883. /*!
  4884. ### 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>
  4885. */
  4886. case 31: //M31 take time since the start of the SD print or an M109 command
  4887. {
  4888. stoptime=_millis();
  4889. char time[30];
  4890. unsigned long t=(stoptime-starttime)/1000;
  4891. int sec,min;
  4892. min=t/60;
  4893. sec=t%60;
  4894. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4895. SERIAL_ECHO_START;
  4896. SERIAL_ECHOLN(time);
  4897. lcd_setstatus(time);
  4898. autotempShutdown();
  4899. }
  4900. break;
  4901. /*!
  4902. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4903. #### Usage
  4904. M42 [ P | S ]
  4905. #### Parameters
  4906. - `P` - Pin number.
  4907. - `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.
  4908. */
  4909. case 42:
  4910. if (code_seen('S'))
  4911. {
  4912. uint8_t pin_status = code_value_uint8();
  4913. int8_t pin_number = LED_PIN;
  4914. if (code_seen('P'))
  4915. pin_number = code_value_uint8();
  4916. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4917. {
  4918. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4919. {
  4920. pin_number = -1;
  4921. break;
  4922. }
  4923. }
  4924. #if defined(FAN_PIN) && FAN_PIN > -1
  4925. if (pin_number == FAN_PIN)
  4926. fanSpeed = pin_status;
  4927. #endif
  4928. if (pin_number > -1)
  4929. {
  4930. pinMode(pin_number, OUTPUT);
  4931. digitalWrite(pin_number, pin_status);
  4932. analogWrite(pin_number, pin_status);
  4933. }
  4934. }
  4935. break;
  4936. /*!
  4937. ### 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>
  4938. */
  4939. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4940. // Reset the baby step value and the baby step applied flag.
  4941. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4942. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4943. // Reset the skew and offset in both RAM and EEPROM.
  4944. reset_bed_offset_and_skew();
  4945. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4946. // the planner will not perform any adjustments in the XY plane.
  4947. // Wait for the motors to stop and update the current position with the absolute values.
  4948. world2machine_revert_to_uncorrected();
  4949. break;
  4950. /*!
  4951. ### 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>
  4952. #### Usage
  4953. M45 [ V ]
  4954. #### Parameters
  4955. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4956. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4957. */
  4958. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4959. {
  4960. int8_t verbosity_level = 0;
  4961. bool only_Z = code_seen('Z');
  4962. #ifdef SUPPORT_VERBOSITY
  4963. if (code_seen('V'))
  4964. {
  4965. // Just 'V' without a number counts as V1.
  4966. char c = strchr_pointer[1];
  4967. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4968. }
  4969. #endif //SUPPORT_VERBOSITY
  4970. gcode_M45(only_Z, verbosity_level);
  4971. }
  4972. break;
  4973. /*!
  4974. ### 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>
  4975. */
  4976. case 46:
  4977. {
  4978. // M46: Prusa3D: Show the assigned IP address.
  4979. if (card.ToshibaFlashAir_isEnabled()) {
  4980. uint8_t ip[4];
  4981. if (card.ToshibaFlashAir_GetIP(ip)) {
  4982. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  4983. SERIAL_PROTOCOL(uint8_t(ip[0]));
  4984. SERIAL_PROTOCOL('.');
  4985. SERIAL_PROTOCOL(uint8_t(ip[1]));
  4986. SERIAL_PROTOCOL('.');
  4987. SERIAL_PROTOCOL(uint8_t(ip[2]));
  4988. SERIAL_PROTOCOL('.');
  4989. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  4990. } else {
  4991. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  4992. }
  4993. } else {
  4994. SERIAL_PROTOCOLLNPGM("n/a");
  4995. }
  4996. break;
  4997. }
  4998. /*!
  4999. ### 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>
  5000. */
  5001. case 47:
  5002. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5003. lcd_diag_show_end_stops();
  5004. KEEPALIVE_STATE(IN_HANDLER);
  5005. break;
  5006. #if 0
  5007. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5008. {
  5009. // Disable the default update procedure of the display. We will do a modal dialog.
  5010. lcd_update_enable(false);
  5011. // Let the planner use the uncorrected coordinates.
  5012. mbl.reset();
  5013. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5014. // the planner will not perform any adjustments in the XY plane.
  5015. // Wait for the motors to stop and update the current position with the absolute values.
  5016. world2machine_revert_to_uncorrected();
  5017. // Move the print head close to the bed.
  5018. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5019. 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);
  5020. st_synchronize();
  5021. // Home in the XY plane.
  5022. set_destination_to_current();
  5023. int l_feedmultiply = setup_for_endstop_move();
  5024. home_xy();
  5025. int8_t verbosity_level = 0;
  5026. if (code_seen('V')) {
  5027. // Just 'V' without a number counts as V1.
  5028. char c = strchr_pointer[1];
  5029. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5030. }
  5031. bool success = scan_bed_induction_points(verbosity_level);
  5032. clean_up_after_endstop_move(l_feedmultiply);
  5033. // Print head up.
  5034. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5035. 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);
  5036. st_synchronize();
  5037. lcd_update_enable(true);
  5038. break;
  5039. }
  5040. #endif
  5041. #ifdef ENABLE_AUTO_BED_LEVELING
  5042. #ifdef Z_PROBE_REPEATABILITY_TEST
  5043. /*!
  5044. ### 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>
  5045. 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.
  5046. 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.
  5047. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5048. #### Usage
  5049. M48 [ n | X | Y | V | L ]
  5050. #### Parameters
  5051. - `n` - Number of samples. Valid values 4-50
  5052. - `X` - X position for samples
  5053. - `Y` - Y position for samples
  5054. - `V` - Verbose level. Valid values 1-4
  5055. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5056. */
  5057. case 48: // M48 Z-Probe repeatability
  5058. {
  5059. #if Z_MIN_PIN == -1
  5060. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5061. #endif
  5062. double sum=0.0;
  5063. double mean=0.0;
  5064. double sigma=0.0;
  5065. double sample_set[50];
  5066. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5067. double X_current, Y_current, Z_current;
  5068. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5069. if (code_seen('V') || code_seen('v')) {
  5070. verbose_level = code_value();
  5071. if (verbose_level<0 || verbose_level>4 ) {
  5072. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5073. goto Sigma_Exit;
  5074. }
  5075. }
  5076. if (verbose_level > 0) {
  5077. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5078. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5079. }
  5080. if (code_seen('n')) {
  5081. n_samples = code_value();
  5082. if (n_samples<4 || n_samples>50 ) {
  5083. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5084. goto Sigma_Exit;
  5085. }
  5086. }
  5087. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5088. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5089. Z_current = st_get_position_mm(Z_AXIS);
  5090. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5091. ext_position = st_get_position_mm(E_AXIS);
  5092. if (code_seen('X') || code_seen('x') ) {
  5093. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5094. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5095. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5096. goto Sigma_Exit;
  5097. }
  5098. }
  5099. if (code_seen('Y') || code_seen('y') ) {
  5100. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5101. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5102. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5103. goto Sigma_Exit;
  5104. }
  5105. }
  5106. if (code_seen('L') || code_seen('l') ) {
  5107. n_legs = code_value();
  5108. if ( n_legs==1 )
  5109. n_legs = 2;
  5110. if ( n_legs<0 || n_legs>15 ) {
  5111. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5112. goto Sigma_Exit;
  5113. }
  5114. }
  5115. //
  5116. // Do all the preliminary setup work. First raise the probe.
  5117. //
  5118. st_synchronize();
  5119. plan_bed_level_matrix.set_to_identity();
  5120. plan_buffer_line( X_current, Y_current, Z_start_location,
  5121. ext_position,
  5122. homing_feedrate[Z_AXIS]/60,
  5123. active_extruder);
  5124. st_synchronize();
  5125. //
  5126. // Now get everything to the specified probe point So we can safely do a probe to
  5127. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5128. // use that as a starting point for each probe.
  5129. //
  5130. if (verbose_level > 2)
  5131. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5132. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5133. ext_position,
  5134. homing_feedrate[X_AXIS]/60,
  5135. active_extruder);
  5136. st_synchronize();
  5137. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5138. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5139. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5140. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5141. //
  5142. // OK, do the inital probe to get us close to the bed.
  5143. // Then retrace the right amount and use that in subsequent probes
  5144. //
  5145. int l_feedmultiply = setup_for_endstop_move();
  5146. run_z_probe();
  5147. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5148. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5149. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5150. ext_position,
  5151. homing_feedrate[X_AXIS]/60,
  5152. active_extruder);
  5153. st_synchronize();
  5154. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5155. for( n=0; n<n_samples; n++) {
  5156. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5157. if ( n_legs) {
  5158. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5159. int rotational_direction, l;
  5160. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5161. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5162. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5163. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5164. //SERIAL_ECHOPAIR(" theta: ",theta);
  5165. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5166. //SERIAL_PROTOCOLLNPGM("");
  5167. for( l=0; l<n_legs-1; l++) {
  5168. if (rotational_direction==1)
  5169. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5170. else
  5171. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5172. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5173. if ( radius<0.0 )
  5174. radius = -radius;
  5175. X_current = X_probe_location + cos(theta) * radius;
  5176. Y_current = Y_probe_location + sin(theta) * radius;
  5177. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5178. X_current = X_MIN_POS;
  5179. if ( X_current>X_MAX_POS)
  5180. X_current = X_MAX_POS;
  5181. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5182. Y_current = Y_MIN_POS;
  5183. if ( Y_current>Y_MAX_POS)
  5184. Y_current = Y_MAX_POS;
  5185. if (verbose_level>3 ) {
  5186. SERIAL_ECHOPAIR("x: ", X_current);
  5187. SERIAL_ECHOPAIR("y: ", Y_current);
  5188. SERIAL_PROTOCOLLNPGM("");
  5189. }
  5190. do_blocking_move_to( X_current, Y_current, Z_current );
  5191. }
  5192. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5193. }
  5194. int l_feedmultiply = setup_for_endstop_move();
  5195. run_z_probe();
  5196. sample_set[n] = current_position[Z_AXIS];
  5197. //
  5198. // Get the current mean for the data points we have so far
  5199. //
  5200. sum=0.0;
  5201. for( j=0; j<=n; j++) {
  5202. sum = sum + sample_set[j];
  5203. }
  5204. mean = sum / (double (n+1));
  5205. //
  5206. // Now, use that mean to calculate the standard deviation for the
  5207. // data points we have so far
  5208. //
  5209. sum=0.0;
  5210. for( j=0; j<=n; j++) {
  5211. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5212. }
  5213. sigma = sqrt( sum / (double (n+1)) );
  5214. if (verbose_level > 1) {
  5215. SERIAL_PROTOCOL(n+1);
  5216. SERIAL_PROTOCOL(" of ");
  5217. SERIAL_PROTOCOL(n_samples);
  5218. SERIAL_PROTOCOLPGM(" z: ");
  5219. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5220. }
  5221. if (verbose_level > 2) {
  5222. SERIAL_PROTOCOL(" mean: ");
  5223. SERIAL_PROTOCOL_F(mean,6);
  5224. SERIAL_PROTOCOL(" sigma: ");
  5225. SERIAL_PROTOCOL_F(sigma,6);
  5226. }
  5227. if (verbose_level > 0)
  5228. SERIAL_PROTOCOLPGM("\n");
  5229. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5230. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5231. st_synchronize();
  5232. }
  5233. _delay(1000);
  5234. clean_up_after_endstop_move(l_feedmultiply);
  5235. // enable_endstops(true);
  5236. if (verbose_level > 0) {
  5237. SERIAL_PROTOCOLPGM("Mean: ");
  5238. SERIAL_PROTOCOL_F(mean, 6);
  5239. SERIAL_PROTOCOLPGM("\n");
  5240. }
  5241. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5242. SERIAL_PROTOCOL_F(sigma, 6);
  5243. SERIAL_PROTOCOLPGM("\n\n");
  5244. Sigma_Exit:
  5245. break;
  5246. }
  5247. #endif // Z_PROBE_REPEATABILITY_TEST
  5248. #endif // ENABLE_AUTO_BED_LEVELING
  5249. /*!
  5250. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5251. #### Usage
  5252. M73 [ P | R | Q | S | C | D ]
  5253. #### Parameters
  5254. - `P` - Percent in normal mode
  5255. - `R` - Time remaining in normal mode
  5256. - `Q` - Percent in silent mode
  5257. - `S` - Time in silent mode
  5258. - `C` - Time to change/pause/user interaction in normal mode
  5259. - `D` - Time to change/pause/user interaction in silent mode
  5260. */
  5261. case 73: //M73 show percent done, time remaining and time to change/pause
  5262. {
  5263. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5264. if(code_seen('R')) print_time_remaining_normal = code_value();
  5265. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5266. if(code_seen('S')) print_time_remaining_silent = code_value();
  5267. if(code_seen('C')){
  5268. float print_time_to_change_normal_f = code_value_float();
  5269. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5270. }
  5271. if(code_seen('D')){
  5272. float print_time_to_change_silent_f = code_value_float();
  5273. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5274. }
  5275. {
  5276. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5277. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5278. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5279. }
  5280. break;
  5281. }
  5282. /*!
  5283. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5284. #### Usage
  5285. M104 [ S ]
  5286. #### Parameters
  5287. - `S` - Target temperature
  5288. */
  5289. case 104: // M104
  5290. {
  5291. uint8_t extruder;
  5292. if(setTargetedHotend(104,extruder)){
  5293. break;
  5294. }
  5295. if (code_seen('S'))
  5296. {
  5297. setTargetHotendSafe(code_value(), extruder);
  5298. }
  5299. break;
  5300. }
  5301. /*!
  5302. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5303. It is processed much earlier as to bypass the cmdqueue.
  5304. */
  5305. case 112:
  5306. kill(MSG_M112_KILL, 3);
  5307. break;
  5308. /*!
  5309. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5310. #### Usage
  5311. M140 [ S ]
  5312. #### Parameters
  5313. - `S` - Target temperature
  5314. */
  5315. case 140:
  5316. if (code_seen('S')) setTargetBed(code_value());
  5317. break;
  5318. /*!
  5319. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5320. Prints temperatures:
  5321. - `T:` - Hotend (actual / target)
  5322. - `B:` - Bed (actual / target)
  5323. - `Tx:` - x Tool (actual / target)
  5324. - `@:` - Hotend power
  5325. - `B@:` - Bed power
  5326. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5327. - `A:` - Ambient actual (only MK3/s)
  5328. _Example:_
  5329. 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
  5330. */
  5331. case 105:
  5332. {
  5333. uint8_t extruder;
  5334. if(setTargetedHotend(105, extruder)){
  5335. break;
  5336. }
  5337. SERIAL_PROTOCOLPGM("ok ");
  5338. gcode_M105(extruder);
  5339. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5340. cmdbuffer_front_already_processed = true;
  5341. break;
  5342. }
  5343. #if defined(AUTO_REPORT)
  5344. /*!
  5345. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5346. #### Usage
  5347. M155 [ S ] [ C ]
  5348. #### Parameters
  5349. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5350. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5351. bit 0 = Auto-report temperatures
  5352. bit 1 = Auto-report fans
  5353. bit 2 = Auto-report position
  5354. bit 3 = free
  5355. bit 4 = free
  5356. bit 5 = free
  5357. bit 6 = free
  5358. bit 7 = free
  5359. */
  5360. case 155:
  5361. {
  5362. if (code_seen('S')){
  5363. autoReportFeatures.SetPeriod( code_value_uint8() );
  5364. }
  5365. if (code_seen('C')){
  5366. autoReportFeatures.SetMask(code_value_uint8());
  5367. } else{
  5368. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5369. }
  5370. }
  5371. break;
  5372. #endif //AUTO_REPORT
  5373. /*!
  5374. ### 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>
  5375. #### Usage
  5376. M104 [ B | R | S ]
  5377. #### Parameters (not mandatory)
  5378. - `S` - Set extruder temperature
  5379. - `R` - Set extruder temperature
  5380. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5381. Parameters S and R are treated identically.
  5382. Command always waits for both cool down and heat up.
  5383. If no parameters are supplied waits for previously set extruder temperature.
  5384. */
  5385. case 109:
  5386. {
  5387. uint8_t extruder;
  5388. if(setTargetedHotend(109, extruder)){
  5389. break;
  5390. }
  5391. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5392. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5393. prusa_statistics(1);
  5394. #ifdef AUTOTEMP
  5395. autotemp_enabled=false;
  5396. #endif
  5397. if (code_seen('S')) {
  5398. setTargetHotendSafe(code_value(), extruder);
  5399. } else if (code_seen('R')) {
  5400. setTargetHotendSafe(code_value(), extruder);
  5401. }
  5402. #ifdef AUTOTEMP
  5403. if (code_seen('S')) autotemp_min=code_value();
  5404. if (code_seen('B')) autotemp_max=code_value();
  5405. if (code_seen('F'))
  5406. {
  5407. autotemp_factor=code_value();
  5408. autotemp_enabled=true;
  5409. }
  5410. #endif
  5411. codenum = _millis();
  5412. /* See if we are heating up or cooling down */
  5413. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5414. cancel_heatup = false;
  5415. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5416. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5417. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5418. prusa_statistics(2);
  5419. //starttime=_millis();
  5420. previous_millis_cmd.start();
  5421. }
  5422. break;
  5423. /*!
  5424. ### 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>
  5425. #### Usage
  5426. M190 [ R | S ]
  5427. #### Parameters (not mandatory)
  5428. - `S` - Set extruder temperature and wait for heating
  5429. - `R` - Set extruder temperature and wait for heating or cooling
  5430. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5431. */
  5432. case 190:
  5433. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5434. {
  5435. bool CooldownNoWait = false;
  5436. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5437. heating_status = HeatingStatus::BED_HEATING;
  5438. prusa_statistics(1);
  5439. if (code_seen('S'))
  5440. {
  5441. setTargetBed(code_value());
  5442. CooldownNoWait = true;
  5443. }
  5444. else if (code_seen('R'))
  5445. {
  5446. setTargetBed(code_value());
  5447. }
  5448. codenum = _millis();
  5449. cancel_heatup = false;
  5450. target_direction = isHeatingBed(); // true if heating, false if cooling
  5451. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5452. {
  5453. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5454. {
  5455. if (!farm_mode) {
  5456. float tt = degHotend(active_extruder);
  5457. SERIAL_PROTOCOLPGM("T:");
  5458. SERIAL_PROTOCOL(tt);
  5459. SERIAL_PROTOCOLPGM(" E:");
  5460. SERIAL_PROTOCOL((int)active_extruder);
  5461. SERIAL_PROTOCOLPGM(" B:");
  5462. SERIAL_PROTOCOL_F(degBed(), 1);
  5463. SERIAL_PROTOCOLLN();
  5464. }
  5465. codenum = _millis();
  5466. }
  5467. manage_heater();
  5468. manage_inactivity();
  5469. lcd_update(0);
  5470. }
  5471. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5472. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5473. previous_millis_cmd.start();
  5474. }
  5475. #endif
  5476. break;
  5477. #if defined(FAN_PIN) && FAN_PIN > -1
  5478. /*!
  5479. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5480. #### Usage
  5481. M106 [ S ]
  5482. #### Parameters
  5483. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5484. */
  5485. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5486. if (code_seen('S')){
  5487. fanSpeed = code_value_uint8();
  5488. }
  5489. else {
  5490. fanSpeed = 255;
  5491. }
  5492. break;
  5493. /*!
  5494. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5495. */
  5496. case 107:
  5497. fanSpeed = 0;
  5498. break;
  5499. #endif //FAN_PIN
  5500. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5501. /*!
  5502. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5503. Only works if the firmware is compiled with PS_ON_PIN defined.
  5504. */
  5505. case 80:
  5506. SET_OUTPUT(PS_ON_PIN); //GND
  5507. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5508. // If you have a switch on suicide pin, this is useful
  5509. // if you want to start another print with suicide feature after
  5510. // a print without suicide...
  5511. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5512. SET_OUTPUT(SUICIDE_PIN);
  5513. WRITE(SUICIDE_PIN, HIGH);
  5514. #endif
  5515. powersupply = true;
  5516. LCD_MESSAGERPGM(MSG_WELCOME);
  5517. lcd_update(0);
  5518. break;
  5519. /*!
  5520. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5521. Only works if the firmware is compiled with PS_ON_PIN defined.
  5522. */
  5523. case 81:
  5524. disable_heater();
  5525. st_synchronize();
  5526. disable_e0();
  5527. disable_e1();
  5528. disable_e2();
  5529. finishAndDisableSteppers();
  5530. fanSpeed = 0;
  5531. _delay(1000); // Wait a little before to switch off
  5532. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5533. st_synchronize();
  5534. suicide();
  5535. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5536. SET_OUTPUT(PS_ON_PIN);
  5537. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5538. #endif
  5539. powersupply = false;
  5540. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5541. lcd_update(0);
  5542. break;
  5543. #endif
  5544. /*!
  5545. ### 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>
  5546. Makes the extruder interpret extrusion as absolute positions.
  5547. */
  5548. case 82:
  5549. axis_relative_modes &= ~E_AXIS_MASK;
  5550. break;
  5551. /*!
  5552. ### 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>
  5553. Makes the extruder interpret extrusion values as relative positions.
  5554. */
  5555. case 83:
  5556. axis_relative_modes |= E_AXIS_MASK;
  5557. break;
  5558. /*!
  5559. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5560. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5561. This command can be used without any additional parameters. In that case all steppers are disabled.
  5562. 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.
  5563. M84 [ S | X | Y | Z | E ]
  5564. - `S` - Seconds
  5565. - `X` - X axis
  5566. - `Y` - Y axis
  5567. - `Z` - Z axis
  5568. - `E` - Extruder
  5569. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5570. Equal to M84 (compatibility)
  5571. */
  5572. case 18: //compatibility
  5573. case 84: // M84
  5574. if(code_seen('S')){
  5575. stepper_inactive_time = code_value() * 1000;
  5576. }
  5577. else
  5578. {
  5579. 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])));
  5580. if(all_axis)
  5581. {
  5582. st_synchronize();
  5583. disable_e0();
  5584. disable_e1();
  5585. disable_e2();
  5586. finishAndDisableSteppers();
  5587. }
  5588. else
  5589. {
  5590. st_synchronize();
  5591. if (code_seen('X')) disable_x();
  5592. if (code_seen('Y')) disable_y();
  5593. if (code_seen('Z')) disable_z();
  5594. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5595. if (code_seen('E')) {
  5596. disable_e0();
  5597. disable_e1();
  5598. disable_e2();
  5599. }
  5600. #endif
  5601. }
  5602. }
  5603. break;
  5604. /*!
  5605. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5606. #### Usage
  5607. M85 [ S ]
  5608. #### Parameters
  5609. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5610. */
  5611. case 85: // M85
  5612. if(code_seen('S')) {
  5613. max_inactive_time = code_value() * 1000;
  5614. }
  5615. break;
  5616. #ifdef SAFETYTIMER
  5617. /*!
  5618. ### 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>
  5619. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5620. #### Usage
  5621. M86 [ S ]
  5622. #### Parameters
  5623. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5624. */
  5625. case 86:
  5626. if (code_seen('S')) {
  5627. safetytimer_inactive_time = code_value() * 1000;
  5628. safetyTimer.start();
  5629. }
  5630. break;
  5631. #endif
  5632. /*!
  5633. ### 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>
  5634. 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)
  5635. #### Usage
  5636. M92 [ X | Y | Z | E ]
  5637. #### Parameters
  5638. - `X` - Steps per unit for the X drive
  5639. - `Y` - Steps per unit for the Y drive
  5640. - `Z` - Steps per unit for the Z drive
  5641. - `E` - Steps per unit for the extruder drive
  5642. */
  5643. case 92:
  5644. for(int8_t i=0; i < NUM_AXIS; i++)
  5645. {
  5646. if(code_seen(axis_codes[i]))
  5647. {
  5648. if(i == E_AXIS) { // E
  5649. float value = code_value();
  5650. if(value < 20.0) {
  5651. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5652. cs.max_jerk[E_AXIS] *= factor;
  5653. max_feedrate[i] *= factor;
  5654. axis_steps_per_sqr_second[i] *= factor;
  5655. }
  5656. cs.axis_steps_per_unit[i] = value;
  5657. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  5658. fsensor.init();
  5659. #endif
  5660. }
  5661. else {
  5662. cs.axis_steps_per_unit[i] = code_value();
  5663. }
  5664. }
  5665. }
  5666. reset_acceleration_rates();
  5667. break;
  5668. /*!
  5669. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5670. Sets the line number in G-code
  5671. #### Usage
  5672. M110 [ N ]
  5673. #### Parameters
  5674. - `N` - Line number
  5675. */
  5676. case 110:
  5677. if (code_seen('N'))
  5678. gcode_LastN = code_value_long();
  5679. break;
  5680. /*!
  5681. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5682. 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).
  5683. #### Usage
  5684. M113 [ S ]
  5685. #### Parameters
  5686. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5687. */
  5688. case 113:
  5689. if (code_seen('S')) {
  5690. host_keepalive_interval = code_value_uint8();
  5691. // NOMORE(host_keepalive_interval, 60);
  5692. }
  5693. else {
  5694. SERIAL_ECHO_START;
  5695. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5696. SERIAL_PROTOCOLLN();
  5697. }
  5698. break;
  5699. /*!
  5700. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5701. Print the firmware info and capabilities
  5702. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5703. `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.
  5704. _Examples:_
  5705. `M115` results:
  5706. `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`
  5707. `M115 V` results:
  5708. `3.8.1`
  5709. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5710. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5711. #### Usage
  5712. M115 [ V | U ]
  5713. #### Parameters
  5714. - V - Report current installed firmware version
  5715. - U - Firmware version provided by G-code to be compared to current one.
  5716. */
  5717. case 115: // M115
  5718. if (code_seen('V')) {
  5719. // Report the Prusa version number.
  5720. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5721. } else if (code_seen('U')) {
  5722. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5723. // pause the print for 30s and ask the user to upgrade the firmware.
  5724. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5725. } else {
  5726. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5727. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5728. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5729. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5730. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5731. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5732. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5733. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5734. SERIAL_ECHOPGM(" UUID:");
  5735. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5736. #ifdef EXTENDED_CAPABILITIES_REPORT
  5737. extended_capabilities_report();
  5738. #endif //EXTENDED_CAPABILITIES_REPORT
  5739. }
  5740. break;
  5741. /*!
  5742. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5743. */
  5744. case 114:
  5745. gcode_M114();
  5746. break;
  5747. /*
  5748. M117 moved up to get the high priority
  5749. case 117: // M117 display message
  5750. starpos = (strchr(strchr_pointer + 5,'*'));
  5751. if(starpos!=NULL)
  5752. *(starpos)='\0';
  5753. lcd_setstatus(strchr_pointer + 5);
  5754. break;*/
  5755. #ifdef M120_M121_ENABLED
  5756. /*!
  5757. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5758. */
  5759. case 120:
  5760. enable_endstops(true) ;
  5761. break;
  5762. /*!
  5763. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5764. */
  5765. case 121:
  5766. enable_endstops(false) ;
  5767. break;
  5768. #endif //M120_M121_ENABLED
  5769. /*!
  5770. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5771. 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.
  5772. */
  5773. case 119:
  5774. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5775. SERIAL_PROTOCOLLN();
  5776. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5777. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5778. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5779. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5780. }else{
  5781. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5782. }
  5783. SERIAL_PROTOCOLLN();
  5784. #endif
  5785. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5786. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5787. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5788. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5789. }else{
  5790. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5791. }
  5792. SERIAL_PROTOCOLLN();
  5793. #endif
  5794. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5795. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5796. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5797. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5798. }else{
  5799. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5800. }
  5801. SERIAL_PROTOCOLLN();
  5802. #endif
  5803. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5804. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5805. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5806. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5807. }else{
  5808. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5809. }
  5810. SERIAL_PROTOCOLLN();
  5811. #endif
  5812. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5813. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5814. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5815. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5816. }else{
  5817. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5818. }
  5819. SERIAL_PROTOCOLLN();
  5820. #endif
  5821. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5822. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5823. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5824. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5825. }else{
  5826. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5827. }
  5828. SERIAL_PROTOCOLLN();
  5829. #endif
  5830. break;
  5831. //!@todo update for all axes, use for loop
  5832. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5833. /*!
  5834. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5835. This command is used to report fan speeds and fan pwm values.
  5836. #### Usage
  5837. M123
  5838. - E0: - Hotend fan speed in RPM
  5839. - PRN1: - Part cooling fans speed in RPM
  5840. - E0@: - Hotend fan PWM value
  5841. - PRN1@: -Part cooling fan PWM value
  5842. _Example:_
  5843. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5844. */
  5845. case 123:
  5846. gcode_M123();
  5847. break;
  5848. #endif //FANCHECK and TACH_0 and TACH_1
  5849. #ifdef BLINKM
  5850. /*!
  5851. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5852. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5853. #### Usage
  5854. M150 [ R | U | B ]
  5855. #### Parameters
  5856. - `R` - Red color value
  5857. - `U` - Green color value. It is NOT `G`!
  5858. - `B` - Blue color value
  5859. */
  5860. case 150:
  5861. {
  5862. byte red;
  5863. byte grn;
  5864. byte blu;
  5865. if(code_seen('R')) red = code_value();
  5866. if(code_seen('U')) grn = code_value();
  5867. if(code_seen('B')) blu = code_value();
  5868. SendColors(red,grn,blu);
  5869. }
  5870. break;
  5871. #endif //BLINKM
  5872. /*!
  5873. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5874. #### Usage
  5875. M200 [ D | T ]
  5876. #### Parameters
  5877. - `D` - Diameter in mm
  5878. - `T` - Number of extruder (MMUs)
  5879. */
  5880. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5881. {
  5882. uint8_t extruder = active_extruder;
  5883. if(code_seen('T')) {
  5884. extruder = code_value_uint8();
  5885. if(extruder >= EXTRUDERS) {
  5886. SERIAL_ECHO_START;
  5887. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5888. break;
  5889. }
  5890. }
  5891. if(code_seen('D')) {
  5892. float diameter = code_value();
  5893. if (diameter == 0.0) {
  5894. // setting any extruder filament size disables volumetric on the assumption that
  5895. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5896. // for all extruders
  5897. cs.volumetric_enabled = false;
  5898. } else {
  5899. cs.filament_size[extruder] = code_value();
  5900. // make sure all extruders have some sane value for the filament size
  5901. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5902. #if EXTRUDERS > 1
  5903. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5904. #if EXTRUDERS > 2
  5905. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5906. #endif
  5907. #endif
  5908. cs.volumetric_enabled = true;
  5909. }
  5910. } else {
  5911. //reserved for setting filament diameter via UFID or filament measuring device
  5912. break;
  5913. }
  5914. calculate_extruder_multipliers();
  5915. }
  5916. break;
  5917. /*!
  5918. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5919. For each axis individually.
  5920. ##### Usage
  5921. M201 [ X | Y | Z | E ]
  5922. ##### Parameters
  5923. - `X` - Acceleration for X axis in units/s^2
  5924. - `Y` - Acceleration for Y axis in units/s^2
  5925. - `Z` - Acceleration for Z axis in units/s^2
  5926. - `E` - Acceleration for the active or specified extruder in units/s^2
  5927. */
  5928. case 201:
  5929. for (int8_t i = 0; i < NUM_AXIS; i++)
  5930. {
  5931. if (code_seen(axis_codes[i]))
  5932. {
  5933. unsigned long val = code_value();
  5934. #ifdef TMC2130
  5935. unsigned long val_silent = val;
  5936. if ((i == X_AXIS) || (i == Y_AXIS))
  5937. {
  5938. if (val > NORMAL_MAX_ACCEL_XY)
  5939. val = NORMAL_MAX_ACCEL_XY;
  5940. if (val_silent > SILENT_MAX_ACCEL_XY)
  5941. val_silent = SILENT_MAX_ACCEL_XY;
  5942. }
  5943. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5944. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5945. #else //TMC2130
  5946. max_acceleration_units_per_sq_second[i] = val;
  5947. #endif //TMC2130
  5948. }
  5949. }
  5950. // 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)
  5951. reset_acceleration_rates();
  5952. break;
  5953. #if 0 // Not used for Sprinter/grbl gen6
  5954. case 202: // M202
  5955. for(int8_t i=0; i < NUM_AXIS; i++) {
  5956. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5957. }
  5958. break;
  5959. #endif
  5960. /*!
  5961. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5962. For each axis individually.
  5963. ##### Usage
  5964. M203 [ X | Y | Z | E ]
  5965. ##### Parameters
  5966. - `X` - Maximum feedrate for X axis
  5967. - `Y` - Maximum feedrate for Y axis
  5968. - `Z` - Maximum feedrate for Z axis
  5969. - `E` - Maximum feedrate for extruder drives
  5970. */
  5971. case 203: // M203 max feedrate mm/sec
  5972. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5973. {
  5974. if (code_seen(axis_codes[i]))
  5975. {
  5976. float val = code_value();
  5977. #ifdef TMC2130
  5978. float val_silent = val;
  5979. if ((i == X_AXIS) || (i == Y_AXIS))
  5980. {
  5981. if (val > NORMAL_MAX_FEEDRATE_XY)
  5982. val = NORMAL_MAX_FEEDRATE_XY;
  5983. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5984. val_silent = SILENT_MAX_FEEDRATE_XY;
  5985. }
  5986. cs.max_feedrate_normal[i] = val;
  5987. cs.max_feedrate_silent[i] = val_silent;
  5988. #else //TMC2130
  5989. max_feedrate[i] = val;
  5990. #endif //TMC2130
  5991. }
  5992. }
  5993. break;
  5994. /*!
  5995. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  5996. #### Old format:
  5997. ##### Usage
  5998. M204 [ S | T ]
  5999. ##### Parameters
  6000. - `S` - normal moves
  6001. - `T` - filmanent only moves
  6002. #### New format:
  6003. ##### Usage
  6004. M204 [ P | R | T ]
  6005. ##### Parameters
  6006. - `P` - printing moves
  6007. - `R` - filmanent only moves
  6008. - `T` - travel moves (as of now T is ignored)
  6009. */
  6010. case 204:
  6011. {
  6012. if(code_seen('S')) {
  6013. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6014. // and it is also generated by Slic3r to control acceleration per extrusion type
  6015. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6016. cs.acceleration = cs.travel_acceleration = code_value();
  6017. // Interpret the T value as retract acceleration in the old Marlin format.
  6018. if(code_seen('T'))
  6019. cs.retract_acceleration = code_value();
  6020. } else {
  6021. // New acceleration format, compatible with the upstream Marlin.
  6022. if(code_seen('P'))
  6023. cs.acceleration = code_value();
  6024. if(code_seen('R'))
  6025. cs.retract_acceleration = code_value();
  6026. if(code_seen('T'))
  6027. cs.travel_acceleration = code_value();
  6028. }
  6029. }
  6030. break;
  6031. /*!
  6032. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6033. Set some advanced settings related to movement.
  6034. #### Usage
  6035. M205 [ S | T | B | X | Y | Z | E ]
  6036. #### Parameters
  6037. - `S` - Minimum feedrate for print moves (unit/s)
  6038. - `T` - Minimum feedrate for travel moves (units/s)
  6039. - `B` - Minimum segment time (us)
  6040. - `X` - Maximum X jerk (units/s)
  6041. - `Y` - Maximum Y jerk (units/s)
  6042. - `Z` - Maximum Z jerk (units/s)
  6043. - `E` - Maximum E jerk (units/s)
  6044. */
  6045. case 205:
  6046. {
  6047. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6048. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6049. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6050. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6051. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6052. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6053. if(code_seen('E'))
  6054. {
  6055. float e = code_value();
  6056. #ifndef LA_NOCOMPAT
  6057. e = la10c_jerk(e);
  6058. #endif
  6059. cs.max_jerk[E_AXIS] = e;
  6060. }
  6061. }
  6062. break;
  6063. /*!
  6064. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6065. #### Usage
  6066. M206 [ X | Y | Z ]
  6067. #### Parameters
  6068. - `X` - X axis offset
  6069. - `Y` - Y axis offset
  6070. - `Z` - Z axis offset
  6071. */
  6072. case 206:
  6073. for(uint8_t i=0; i < 3; i++)
  6074. {
  6075. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6076. }
  6077. break;
  6078. #ifdef FWRETRACT
  6079. /*!
  6080. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6081. #### Usage
  6082. M207 [ S | F | Z ]
  6083. #### Parameters
  6084. - `S` - positive length to retract, in mm
  6085. - `F` - retraction feedrate, in mm/min
  6086. - `Z` - additional zlift/hop
  6087. */
  6088. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6089. {
  6090. if(code_seen('S'))
  6091. {
  6092. cs.retract_length = code_value() ;
  6093. }
  6094. if(code_seen('F'))
  6095. {
  6096. cs.retract_feedrate = code_value()/60 ;
  6097. }
  6098. if(code_seen('Z'))
  6099. {
  6100. cs.retract_zlift = code_value() ;
  6101. }
  6102. }break;
  6103. /*!
  6104. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6105. #### Usage
  6106. M208 [ S | F ]
  6107. #### Parameters
  6108. - `S` - positive length surplus to the M207 Snnn, in mm
  6109. - `F` - feedrate, in mm/sec
  6110. */
  6111. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6112. {
  6113. if(code_seen('S'))
  6114. {
  6115. cs.retract_recover_length = code_value() ;
  6116. }
  6117. if(code_seen('F'))
  6118. {
  6119. cs.retract_recover_feedrate = code_value()/60 ;
  6120. }
  6121. }break;
  6122. /*!
  6123. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6124. 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.
  6125. #### Usage
  6126. M209 [ S ]
  6127. #### Parameters
  6128. - `S` - 1=true or 0=false
  6129. */
  6130. 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.
  6131. {
  6132. if(code_seen('S'))
  6133. {
  6134. switch(code_value_uint8())
  6135. {
  6136. case 0:
  6137. {
  6138. cs.autoretract_enabled=false;
  6139. retracted[0]=false;
  6140. #if EXTRUDERS > 1
  6141. retracted[1]=false;
  6142. #endif
  6143. #if EXTRUDERS > 2
  6144. retracted[2]=false;
  6145. #endif
  6146. }break;
  6147. case 1:
  6148. {
  6149. cs.autoretract_enabled=true;
  6150. retracted[0]=false;
  6151. #if EXTRUDERS > 1
  6152. retracted[1]=false;
  6153. #endif
  6154. #if EXTRUDERS > 2
  6155. retracted[2]=false;
  6156. #endif
  6157. }break;
  6158. default:
  6159. SERIAL_ECHO_START;
  6160. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6161. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6162. SERIAL_ECHOLNPGM("\"(1)");
  6163. }
  6164. }
  6165. }break;
  6166. #endif // FWRETRACT
  6167. /*!
  6168. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6169. #### Usage
  6170. M214 [P] [S] [N] [R] [F]
  6171. #### Parameters
  6172. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6173. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6174. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6175. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6176. except when the results in segment lengths greater than or less than the minimum
  6177. and maximum segment length. Set to 0 to disable.
  6178. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6179. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6180. */
  6181. 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>
  6182. {
  6183. // Extract all possible parameters if they appear
  6184. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6185. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6186. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6187. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6188. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6189. // 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
  6190. if (p <=0 || s < 0 || p < s)
  6191. {
  6192. // Should we display some error here?
  6193. break;
  6194. }
  6195. cs.mm_per_arc_segment = p;
  6196. cs.min_mm_per_arc_segment = s;
  6197. cs.n_arc_correction = n;
  6198. cs.min_arc_segments = r;
  6199. cs.arc_segments_per_sec = f;
  6200. }break;
  6201. #if EXTRUDERS > 1
  6202. /*!
  6203. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6204. 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.
  6205. #### Usage
  6206. M218 [ X | Y ]
  6207. #### Parameters
  6208. - `X` - X offset
  6209. - `Y` - Y offset
  6210. */
  6211. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6212. {
  6213. uint8_t extruder;
  6214. if(setTargetedHotend(218, extruder)){
  6215. break;
  6216. }
  6217. if(code_seen('X'))
  6218. {
  6219. extruder_offset[X_AXIS][extruder] = code_value();
  6220. }
  6221. if(code_seen('Y'))
  6222. {
  6223. extruder_offset[Y_AXIS][extruder] = code_value();
  6224. }
  6225. SERIAL_ECHO_START;
  6226. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6227. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6228. {
  6229. SERIAL_ECHO(" ");
  6230. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6231. SERIAL_ECHO(",");
  6232. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6233. }
  6234. SERIAL_ECHOLN("");
  6235. }break;
  6236. #endif
  6237. /*!
  6238. ### 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>
  6239. #### Usage
  6240. M220 [ B | S | R ]
  6241. #### Parameters
  6242. - `B` - Backup current speed factor
  6243. - `S` - Speed factor override percentage (0..100 or higher)
  6244. - `R` - Restore previous speed factor
  6245. */
  6246. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6247. {
  6248. bool codesWereSeen = false;
  6249. if (code_seen('B')) //backup current speed factor
  6250. {
  6251. saved_feedmultiply_mm = feedmultiply;
  6252. codesWereSeen = true;
  6253. }
  6254. if (code_seen('S'))
  6255. {
  6256. feedmultiply = code_value_short();
  6257. codesWereSeen = true;
  6258. }
  6259. if (code_seen('R')) //restore previous feedmultiply
  6260. {
  6261. feedmultiply = saved_feedmultiply_mm;
  6262. codesWereSeen = true;
  6263. }
  6264. if (!codesWereSeen)
  6265. {
  6266. printf_P(PSTR("%i%%\n"), feedmultiply);
  6267. }
  6268. }
  6269. break;
  6270. /*!
  6271. ### 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>
  6272. #### Usage
  6273. M221 [ S | T ]
  6274. #### Parameters
  6275. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6276. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6277. */
  6278. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6279. {
  6280. if (code_seen('S'))
  6281. {
  6282. int tmp_code = code_value_short();
  6283. if (code_seen('T'))
  6284. {
  6285. uint8_t extruder;
  6286. if (setTargetedHotend(221, extruder))
  6287. break;
  6288. extruder_multiply[extruder] = tmp_code;
  6289. }
  6290. else
  6291. {
  6292. extrudemultiply = tmp_code ;
  6293. }
  6294. }
  6295. else
  6296. {
  6297. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6298. }
  6299. calculate_extruder_multipliers();
  6300. }
  6301. break;
  6302. /*!
  6303. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6304. Wait until the specified pin reaches the state required
  6305. #### Usage
  6306. M226 [ P | S ]
  6307. #### Parameters
  6308. - `P` - pin number
  6309. - `S` - pin state
  6310. */
  6311. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6312. {
  6313. if(code_seen('P')){
  6314. int pin_number = code_value_short(); // pin number
  6315. int pin_state = -1; // required pin state - default is inverted
  6316. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6317. if(pin_state >= -1 && pin_state <= 1){
  6318. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6319. {
  6320. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6321. {
  6322. pin_number = -1;
  6323. break;
  6324. }
  6325. }
  6326. if (pin_number > -1)
  6327. {
  6328. int target = LOW;
  6329. st_synchronize();
  6330. pinMode(pin_number, INPUT);
  6331. switch(pin_state){
  6332. case 1:
  6333. target = HIGH;
  6334. break;
  6335. case 0:
  6336. target = LOW;
  6337. break;
  6338. case -1:
  6339. target = !digitalRead(pin_number);
  6340. break;
  6341. }
  6342. while(digitalRead(pin_number) != target){
  6343. manage_heater();
  6344. manage_inactivity();
  6345. lcd_update(0);
  6346. }
  6347. }
  6348. }
  6349. }
  6350. }
  6351. break;
  6352. #if NUM_SERVOS > 0
  6353. /*!
  6354. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6355. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6356. #### Usage
  6357. M280 [ P | S ]
  6358. #### Parameters
  6359. - `P` - Servo index (id)
  6360. - `S` - Target position
  6361. */
  6362. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6363. {
  6364. int servo_index = -1;
  6365. int servo_position = 0;
  6366. if (code_seen('P'))
  6367. servo_index = code_value();
  6368. if (code_seen('S')) {
  6369. servo_position = code_value();
  6370. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6371. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6372. servos[servo_index].attach(0);
  6373. #endif
  6374. servos[servo_index].write(servo_position);
  6375. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6376. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6377. servos[servo_index].detach();
  6378. #endif
  6379. }
  6380. else {
  6381. SERIAL_ECHO_START;
  6382. SERIAL_ECHO("Servo ");
  6383. SERIAL_ECHO(servo_index);
  6384. SERIAL_ECHOLN(" out of range");
  6385. }
  6386. }
  6387. else if (servo_index >= 0) {
  6388. SERIAL_PROTOCOL(MSG_OK);
  6389. SERIAL_PROTOCOL(" Servo ");
  6390. SERIAL_PROTOCOL(servo_index);
  6391. SERIAL_PROTOCOL(": ");
  6392. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6393. }
  6394. }
  6395. break;
  6396. #endif // NUM_SERVOS > 0
  6397. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6398. /*!
  6399. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6400. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6401. #### Usage
  6402. M300 [ S | P ]
  6403. #### Parameters
  6404. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6405. - `P` - duration in milliseconds
  6406. */
  6407. case 300: // M300
  6408. {
  6409. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6410. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6411. #if BEEPER > 0
  6412. if (beepP > 0)
  6413. Sound_MakeCustom(beepP,beepS,false);
  6414. #endif
  6415. }
  6416. break;
  6417. #endif // M300
  6418. #ifdef PIDTEMP
  6419. /*!
  6420. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6421. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6422. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6423. #### Usage
  6424. M301 [ P | I | D ]
  6425. #### Parameters
  6426. - `P` - proportional (Kp)
  6427. - `I` - integral (Ki)
  6428. - `D` - derivative (Kd)
  6429. */
  6430. case 301:
  6431. {
  6432. if(code_seen('P')) cs.Kp = code_value();
  6433. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6434. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6435. updatePID();
  6436. SERIAL_PROTOCOLRPGM(MSG_OK);
  6437. SERIAL_PROTOCOLPGM(" p:");
  6438. SERIAL_PROTOCOL(cs.Kp);
  6439. SERIAL_PROTOCOLPGM(" i:");
  6440. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6441. SERIAL_PROTOCOLPGM(" d:");
  6442. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6443. SERIAL_PROTOCOLLN();
  6444. }
  6445. break;
  6446. #endif //PIDTEMP
  6447. #ifdef PIDTEMPBED
  6448. /*!
  6449. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6450. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6451. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6452. #### Usage
  6453. M304 [ P | I | D ]
  6454. #### Parameters
  6455. - `P` - proportional (Kp)
  6456. - `I` - integral (Ki)
  6457. - `D` - derivative (Kd)
  6458. */
  6459. case 304:
  6460. {
  6461. if(code_seen('P')) cs.bedKp = code_value();
  6462. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6463. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6464. updatePID();
  6465. SERIAL_PROTOCOLRPGM(MSG_OK);
  6466. SERIAL_PROTOCOLPGM(" p:");
  6467. SERIAL_PROTOCOL(cs.bedKp);
  6468. SERIAL_PROTOCOLPGM(" i:");
  6469. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6470. SERIAL_PROTOCOLPGM(" d:");
  6471. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6472. }
  6473. break;
  6474. #endif //PIDTEMP
  6475. /*!
  6476. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6477. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6478. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6479. */
  6480. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6481. {
  6482. #ifdef CHDK
  6483. SET_OUTPUT(CHDK);
  6484. WRITE(CHDK, HIGH);
  6485. chdkHigh = _millis();
  6486. chdkActive = true;
  6487. #else
  6488. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6489. const uint8_t NUM_PULSES=16;
  6490. const float PULSE_LENGTH=0.01524;
  6491. for(int i=0; i < NUM_PULSES; i++) {
  6492. WRITE(PHOTOGRAPH_PIN, HIGH);
  6493. _delay_ms(PULSE_LENGTH);
  6494. WRITE(PHOTOGRAPH_PIN, LOW);
  6495. _delay_ms(PULSE_LENGTH);
  6496. }
  6497. _delay(7.33);
  6498. for(int i=0; i < NUM_PULSES; i++) {
  6499. WRITE(PHOTOGRAPH_PIN, HIGH);
  6500. _delay_ms(PULSE_LENGTH);
  6501. WRITE(PHOTOGRAPH_PIN, LOW);
  6502. _delay_ms(PULSE_LENGTH);
  6503. }
  6504. #endif
  6505. #endif //chdk end if
  6506. }
  6507. break;
  6508. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6509. /*!
  6510. ### 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>
  6511. 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.
  6512. #### Usage
  6513. M302 [ S ]
  6514. #### Parameters
  6515. - `S` - Cold extrude minimum temperature
  6516. */
  6517. case 302:
  6518. {
  6519. int temp = 0;
  6520. if (code_seen('S')) temp=code_value_short();
  6521. set_extrude_min_temp(temp);
  6522. }
  6523. break;
  6524. #endif
  6525. /*!
  6526. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6527. 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.
  6528. #### Usage
  6529. M303 [ E | S | C ]
  6530. #### Parameters
  6531. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6532. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6533. - `C` - Cycles, default `5`
  6534. */
  6535. case 303:
  6536. {
  6537. float temp = 150.0;
  6538. int e = 0;
  6539. int c = 5;
  6540. if (code_seen('E')) e = code_value_short();
  6541. if (e < 0)
  6542. temp = 70;
  6543. if (code_seen('S')) temp = code_value();
  6544. if (code_seen('C')) c = code_value_short();
  6545. PID_autotune(temp, e, c);
  6546. }
  6547. break;
  6548. #ifdef TEMP_MODEL
  6549. /*!
  6550. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6551. #### Usage
  6552. M310 ; report values
  6553. M310 [ A ] [ F ] ; autotune
  6554. M310 [ S ] ; set 0=disable 1=enable
  6555. M310 [ I ] [ R ] ; set resistance at index
  6556. M310 [ P | C ] ; set power, capacitance
  6557. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6558. M310 [ T ] ; set ambient temperature correction
  6559. #### Parameters
  6560. - `I` - resistance index position (0-15)
  6561. - `R` - resistance value at index (K/W; requires `I`)
  6562. - `P` - power (W)
  6563. - `C` - capacitance (J/K)
  6564. - `S` - set 0=disable 1=enable
  6565. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6566. - `E` - error threshold (K/s; default in variant)
  6567. - `W` - warning threshold (K/s; default in variant)
  6568. - `T` - ambient temperature correction (K; default in variant)
  6569. - `A` - autotune C+R values
  6570. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6571. */
  6572. case 310:
  6573. {
  6574. // parse all parameters
  6575. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6576. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6577. if(code_seen('C')) C = code_value();
  6578. if(code_seen('P')) P = code_value();
  6579. if(code_seen('I')) I = code_value_short();
  6580. if(code_seen('R')) R = code_value();
  6581. if(code_seen('S')) S = code_value_short();
  6582. if(code_seen('B')) B = code_value_short();
  6583. if(code_seen('E')) E = code_value();
  6584. if(code_seen('W')) W = code_value();
  6585. if(code_seen('T')) T = code_value();
  6586. if(code_seen('A')) A = code_value_short();
  6587. if(code_seen('F')) F = code_value_short();
  6588. // report values if nothing has been requested
  6589. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6590. temp_model_report_settings();
  6591. break;
  6592. }
  6593. // update all parameters
  6594. if(B >= 0) temp_model_set_warn_beep(B);
  6595. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6596. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6597. // enable the model last, if requested
  6598. if(S >= 0) temp_model_set_enabled(S);
  6599. // run autotune
  6600. if(A >= 0) temp_model_autotune(A, F > 0);
  6601. }
  6602. break;
  6603. #endif
  6604. /*!
  6605. ### 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>
  6606. Finishes all current moves and and thus clears the buffer.
  6607. Equivalent to `G4` with no parameters.
  6608. */
  6609. case 400:
  6610. {
  6611. st_synchronize();
  6612. }
  6613. break;
  6614. /*!
  6615. ### 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>
  6616. Currently three different materials are needed (default, flex and PVA).
  6617. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6618. #### Usage
  6619. M403 [ E | F ]
  6620. #### Parameters
  6621. - `E` - Extruder number. 0-indexed.
  6622. - `F` - Filament type
  6623. */
  6624. case 403:
  6625. {
  6626. // currently three different materials are needed (default, flex and PVA)
  6627. // add storing this information for different load/unload profiles etc. in the future
  6628. // firmware does not wait for "ok" from mmu
  6629. if (mmu_enabled)
  6630. {
  6631. uint8_t extruder = 255;
  6632. uint8_t filament = FILAMENT_UNDEFINED;
  6633. if(code_seen('E')) extruder = code_value_uint8();
  6634. if(code_seen('F')) filament = code_value_uint8();
  6635. mmu_set_filament_type(extruder, filament);
  6636. }
  6637. }
  6638. break;
  6639. /*!
  6640. ### 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>
  6641. Save current parameters to EEPROM.
  6642. */
  6643. case 500:
  6644. {
  6645. Config_StoreSettings();
  6646. }
  6647. break;
  6648. /*!
  6649. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6650. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6651. */
  6652. case 501:
  6653. {
  6654. Config_RetrieveSettings();
  6655. }
  6656. break;
  6657. /*!
  6658. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6659. 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.
  6660. */
  6661. case 502:
  6662. {
  6663. Config_ResetDefault();
  6664. }
  6665. break;
  6666. /*!
  6667. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6668. 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.
  6669. */
  6670. case 503:
  6671. {
  6672. Config_PrintSettings();
  6673. }
  6674. break;
  6675. /*!
  6676. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6677. Resets the language to English.
  6678. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6679. */
  6680. case 509:
  6681. {
  6682. lang_reset();
  6683. SERIAL_ECHO_START;
  6684. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6685. }
  6686. break;
  6687. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6688. /*!
  6689. ### 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>
  6690. 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`.
  6691. #### Usage
  6692. M540 [ S ]
  6693. #### Parameters
  6694. - `S` - disabled=0, enabled=1
  6695. */
  6696. case 540:
  6697. {
  6698. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6699. }
  6700. break;
  6701. #endif
  6702. #ifdef ENABLE_AUTO_BED_LEVELING
  6703. /*!
  6704. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6705. 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.
  6706. 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.)
  6707. #### Usage
  6708. M851 [ Z ]
  6709. #### Parameters
  6710. - `Z` - Z offset probe to nozzle.
  6711. */
  6712. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6713. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6714. {
  6715. float value;
  6716. if (code_seen('Z'))
  6717. {
  6718. value = code_value();
  6719. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6720. {
  6721. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6722. SERIAL_ECHO_START;
  6723. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6724. SERIAL_PROTOCOLLN();
  6725. }
  6726. else
  6727. {
  6728. SERIAL_ECHO_START;
  6729. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6730. SERIAL_ECHORPGM(MSG_Z_MIN);
  6731. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6732. SERIAL_ECHORPGM(MSG_Z_MAX);
  6733. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6734. SERIAL_PROTOCOLLN();
  6735. }
  6736. }
  6737. else
  6738. {
  6739. SERIAL_ECHO_START;
  6740. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6741. SERIAL_ECHO(-cs.zprobe_zoffset);
  6742. SERIAL_PROTOCOLLN();
  6743. }
  6744. break;
  6745. }
  6746. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6747. #endif // ENABLE_AUTO_BED_LEVELING
  6748. /*!
  6749. ### 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>
  6750. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6751. If P is not specified nothing happens.
  6752. 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.
  6753. #### Usage
  6754. M552 [ P<IP_address> ]
  6755. #### Parameters
  6756. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6757. */
  6758. case 552:
  6759. {
  6760. if (code_seen('P'))
  6761. {
  6762. uint8_t valCnt = 0;
  6763. IP_address = 0;
  6764. do
  6765. {
  6766. *strchr_pointer = '*';
  6767. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6768. valCnt++;
  6769. } while ((valCnt < 4) && code_seen('.'));
  6770. if (valCnt != 4)
  6771. IP_address = 0;
  6772. }
  6773. } break;
  6774. #ifdef FILAMENTCHANGEENABLE
  6775. /*!
  6776. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6777. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6778. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6779. #### Usage
  6780. M600 [ X | Y | Z | E | L | AUTO ]
  6781. - `X` - X position, default 211
  6782. - `Y` - Y position, default 0
  6783. - `Z` - relative lift Z, default 2.
  6784. - `E` - initial retract, default -2
  6785. - `L` - later retract distance for removal, default -80
  6786. - `AUTO` - Automatically (only with MMU)
  6787. */
  6788. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6789. {
  6790. st_synchronize();
  6791. float x_position = current_position[X_AXIS];
  6792. float y_position = current_position[Y_AXIS];
  6793. float z_shift = 0; // is it necessary to be a float?
  6794. float e_shift_init = 0;
  6795. float e_shift_late = 0;
  6796. bool automatic = false;
  6797. //Retract extruder
  6798. if(code_seen('E'))
  6799. {
  6800. e_shift_init = code_value();
  6801. }
  6802. else
  6803. {
  6804. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6805. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6806. #endif
  6807. }
  6808. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6809. if (code_seen('L'))
  6810. {
  6811. e_shift_late = code_value();
  6812. }
  6813. else
  6814. {
  6815. #ifdef FILAMENTCHANGE_FINALRETRACT
  6816. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6817. #endif
  6818. }
  6819. //Lift Z
  6820. if(code_seen('Z'))
  6821. {
  6822. z_shift = code_value();
  6823. }
  6824. else
  6825. {
  6826. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6827. }
  6828. //Move XY to side
  6829. if(code_seen('X'))
  6830. {
  6831. x_position = code_value();
  6832. }
  6833. else
  6834. {
  6835. #ifdef FILAMENTCHANGE_XPOS
  6836. x_position = FILAMENTCHANGE_XPOS;
  6837. #endif
  6838. }
  6839. if(code_seen('Y'))
  6840. {
  6841. y_position = code_value();
  6842. }
  6843. else
  6844. {
  6845. #ifdef FILAMENTCHANGE_YPOS
  6846. y_position = FILAMENTCHANGE_YPOS ;
  6847. #endif
  6848. }
  6849. if (mmu_enabled && code_seen_P(PSTR("AUTO")))
  6850. automatic = true;
  6851. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6852. }
  6853. break;
  6854. #endif //FILAMENTCHANGEENABLE
  6855. /*!
  6856. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6857. */
  6858. /*!
  6859. ### M125 - Pause print (TODO: not implemented)
  6860. */
  6861. /*!
  6862. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6863. */
  6864. case 25:
  6865. case 601:
  6866. {
  6867. if (!isPrintPaused) {
  6868. st_synchronize();
  6869. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6870. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6871. lcd_pause_print();
  6872. }
  6873. }
  6874. break;
  6875. /*!
  6876. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6877. */
  6878. case 602:
  6879. {
  6880. if (isPrintPaused) lcd_resume_print();
  6881. }
  6882. break;
  6883. /*!
  6884. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6885. */
  6886. case 603: {
  6887. lcd_print_stop();
  6888. }
  6889. break;
  6890. #ifdef PINDA_THERMISTOR
  6891. /*!
  6892. ### 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>
  6893. Wait for PINDA thermistor to reach target temperature
  6894. #### Usage
  6895. M860 [ S ]
  6896. #### Parameters
  6897. - `S` - Target temperature
  6898. */
  6899. case 860:
  6900. {
  6901. int set_target_pinda = 0;
  6902. if (code_seen('S')) {
  6903. set_target_pinda = code_value_short();
  6904. }
  6905. else {
  6906. break;
  6907. }
  6908. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6909. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6910. SERIAL_PROTOCOLLN(set_target_pinda);
  6911. codenum = _millis();
  6912. cancel_heatup = false;
  6913. bool is_pinda_cooling = false;
  6914. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6915. is_pinda_cooling = true;
  6916. }
  6917. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6918. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6919. {
  6920. SERIAL_PROTOCOLPGM("P:");
  6921. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6922. SERIAL_PROTOCOL('/');
  6923. SERIAL_PROTOCOLLN(set_target_pinda);
  6924. codenum = _millis();
  6925. }
  6926. manage_heater();
  6927. manage_inactivity();
  6928. lcd_update(0);
  6929. }
  6930. LCD_MESSAGERPGM(MSG_OK);
  6931. break;
  6932. }
  6933. /*!
  6934. ### 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>
  6935. Set compensation ustep value `S` for compensation table index `I`.
  6936. #### Usage
  6937. M861 [ ? | ! | Z | S | I ]
  6938. #### Parameters
  6939. - `?` - Print current EEPROM offset values
  6940. - `!` - Set factory default values
  6941. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6942. - `S` - Microsteps
  6943. - `I` - Table index
  6944. */
  6945. case 861: {
  6946. const char * const _header = PSTR("index, temp, ustep, um");
  6947. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6948. int16_t usteps = 0;
  6949. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6950. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6951. SERIAL_PROTOCOLLNRPGM(_header);
  6952. for (uint8_t i = 0; i < 6; i++)
  6953. {
  6954. if(i > 0) {
  6955. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6956. }
  6957. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6958. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6959. SERIAL_PROTOCOLPGM(", ");
  6960. SERIAL_PROTOCOL(35 + (i * 5));
  6961. SERIAL_PROTOCOLPGM(", ");
  6962. SERIAL_PROTOCOL(usteps);
  6963. SERIAL_PROTOCOLPGM(", ");
  6964. SERIAL_PROTOCOLLN(mm * 1000);
  6965. }
  6966. }
  6967. else if (code_seen('!')) { // ! - Set factory default values
  6968. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6969. int16_t z_shift = 8; //40C - 20um - 8usteps
  6970. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6971. z_shift = 24; //45C - 60um - 24usteps
  6972. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6973. z_shift = 48; //50C - 120um - 48usteps
  6974. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6975. z_shift = 80; //55C - 200um - 80usteps
  6976. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6977. z_shift = 120; //60C - 300um - 120usteps
  6978. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6979. SERIAL_PROTOCOLLNPGM("factory restored");
  6980. }
  6981. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6982. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6983. int16_t z_shift = 0;
  6984. for (uint8_t i = 0; i < 5; i++) {
  6985. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  6986. }
  6987. SERIAL_PROTOCOLLNPGM("zerorized");
  6988. }
  6989. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6990. int16_t usteps = code_value_short();
  6991. if (code_seen('I')) {
  6992. uint8_t index = code_value_uint8();
  6993. if (index < 5) {
  6994. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  6995. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6996. SERIAL_PROTOCOLLNRPGM(_header);
  6997. for (uint8_t i = 0; i < 6; i++)
  6998. {
  6999. usteps = 0;
  7000. if (i > 0) {
  7001. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  7002. }
  7003. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7004. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7005. SERIAL_PROTOCOLPGM(", ");
  7006. SERIAL_PROTOCOL(35 + (i * 5));
  7007. SERIAL_PROTOCOLPGM(", ");
  7008. SERIAL_PROTOCOL(usteps);
  7009. SERIAL_PROTOCOLPGM(", ");
  7010. SERIAL_PROTOCOLLN(mm * 1000);
  7011. }
  7012. }
  7013. }
  7014. }
  7015. else {
  7016. SERIAL_PROTOCOLLNPGM("no valid command");
  7017. }
  7018. } break;
  7019. #endif //PINDA_THERMISTOR
  7020. /*!
  7021. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  7022. Checks the parameters of the printer and gcode and performs compatibility check
  7023. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  7024. - M862.2 { P<model_code> | Q }
  7025. - M862.3 { P"<model_name>" | Q }
  7026. - M862.4 { P<fw_version> | Q }
  7027. - M862.5 { P<gcode_level> | Q }
  7028. When run with P<> argument, the check is performed against the input value.
  7029. When run with Q argument, the current value is shown.
  7030. M862.3 accepts text identifiers of printer types too.
  7031. The syntax of M862.3 is (note the quotes around the type):
  7032. M862.3 P "MK3S"
  7033. Accepted printer type identifiers and their numeric counterparts:
  7034. - MK1 (100)
  7035. - MK2 (200)
  7036. - MK2MM (201)
  7037. - MK2S (202)
  7038. - MK2SMM (203)
  7039. - MK2.5 (250)
  7040. - MK2.5MMU2 (20250)
  7041. - MK2.5S (252)
  7042. - MK2.5SMMU2S (20252)
  7043. - MK3 (300)
  7044. - MK3MMU2 (20300)
  7045. - MK3S (302)
  7046. - MK3SMMU2S (20302)
  7047. */
  7048. case 862: // M862: print checking
  7049. float nDummy;
  7050. uint8_t nCommand;
  7051. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7052. switch((ClPrintChecking)nCommand)
  7053. {
  7054. case ClPrintChecking::_Nozzle: // ~ .1
  7055. uint16_t nDiameter;
  7056. if(code_seen('P'))
  7057. {
  7058. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7059. nozzle_diameter_check(nDiameter);
  7060. }
  7061. else if(code_seen('Q'))
  7062. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7063. break;
  7064. case ClPrintChecking::_Model: // ~ .2
  7065. if(code_seen('P'))
  7066. {
  7067. uint16_t nPrinterModel;
  7068. nPrinterModel=(uint16_t)code_value_long();
  7069. printer_model_check(nPrinterModel);
  7070. }
  7071. else if(code_seen('Q'))
  7072. SERIAL_PROTOCOLLN(nPrinterType);
  7073. break;
  7074. case ClPrintChecking::_Smodel: // ~ .3
  7075. if(code_seen('P'))
  7076. printer_smodel_check(strchr_pointer);
  7077. else if(code_seen('Q'))
  7078. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7079. break;
  7080. case ClPrintChecking::_Version: // ~ .4
  7081. if(code_seen('P'))
  7082. fw_version_check(++strchr_pointer);
  7083. else if(code_seen('Q'))
  7084. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7085. break;
  7086. case ClPrintChecking::_Gcode: // ~ .5
  7087. if(code_seen('P'))
  7088. {
  7089. uint16_t nGcodeLevel;
  7090. nGcodeLevel=(uint16_t)code_value_long();
  7091. gcode_level_check(nGcodeLevel);
  7092. }
  7093. else if(code_seen('Q'))
  7094. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7095. break;
  7096. }
  7097. break;
  7098. #ifdef LIN_ADVANCE
  7099. /*!
  7100. ### 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>
  7101. 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.
  7102. #### Usage
  7103. M900 [ K | R | W | H | D]
  7104. #### Parameters
  7105. - `K` - Advance K factor
  7106. - `R` - Set ratio directly (overrides WH/D)
  7107. - `W` - Width
  7108. - `H` - Height
  7109. - `D` - Diameter Set ratio from WH/D
  7110. */
  7111. case 900:
  7112. gcode_M900();
  7113. break;
  7114. #endif
  7115. /*!
  7116. ### 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>
  7117. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7118. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7119. #### Usage
  7120. M907 [ X | Y | Z | E | B | S ]
  7121. #### Parameters
  7122. - `X` - X motor driver
  7123. - `Y` - Y motor driver
  7124. - `Z` - Z motor driver
  7125. - `E` - Extruder motor driver
  7126. - `B` - Second Extruder motor driver
  7127. - `S` - All motors
  7128. */
  7129. case 907:
  7130. {
  7131. #ifdef TMC2130
  7132. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7133. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7134. if(code_seen(axis_codes[i])){
  7135. if( i == E_AXIS && FarmOrUserECool() ){
  7136. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7137. SERIAL_ECHOLNPGM(", M907 E ignored");
  7138. continue;
  7139. }
  7140. long cur_mA = code_value_long();
  7141. uint8_t val = tmc2130_cur2val(cur_mA);
  7142. tmc2130_set_current_h(i, val);
  7143. tmc2130_set_current_r(i, val);
  7144. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7145. }
  7146. }
  7147. #else //TMC2130
  7148. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7149. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7150. if(code_seen('B')) st_current_set(4,code_value());
  7151. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7152. #endif
  7153. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7154. if(code_seen('X')) st_current_set(0, code_value());
  7155. #endif
  7156. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7157. if(code_seen('Z')) st_current_set(1, code_value());
  7158. #endif
  7159. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7160. if(code_seen('E')) st_current_set(2, code_value());
  7161. #endif
  7162. #endif //TMC2130
  7163. }
  7164. break;
  7165. /*!
  7166. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7167. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7168. #### Usage
  7169. M908 [ P | S ]
  7170. #### Parameters
  7171. - `P` - channel
  7172. - `S` - current
  7173. */
  7174. case 908:
  7175. {
  7176. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7177. uint8_t channel,current;
  7178. if(code_seen('P')) channel=code_value();
  7179. if(code_seen('S')) current=code_value();
  7180. digitalPotWrite(channel, current);
  7181. #endif
  7182. }
  7183. break;
  7184. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7185. /*!
  7186. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7187. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7188. */
  7189. case 910:
  7190. {
  7191. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7192. }
  7193. break;
  7194. /*!
  7195. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7196. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7197. #### Usage
  7198. M911 [ X | Y | Z | E ]
  7199. #### Parameters
  7200. - `X` - X stepper driver holding current value
  7201. - `Y` - Y stepper driver holding current value
  7202. - `Z` - Z stepper driver holding current value
  7203. - `E` - Extruder stepper driver holding current value
  7204. */
  7205. case 911:
  7206. {
  7207. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7208. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7209. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7210. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7211. }
  7212. break;
  7213. /*!
  7214. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7215. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7216. #### Usage
  7217. M912 [ X | Y | Z | E ]
  7218. #### Parameters
  7219. - `X` - X stepper driver running current value
  7220. - `Y` - Y stepper driver running current value
  7221. - `Z` - Z stepper driver running current value
  7222. - `E` - Extruder stepper driver running current value
  7223. */
  7224. case 912:
  7225. {
  7226. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7227. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7228. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7229. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7230. }
  7231. break;
  7232. /*!
  7233. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7234. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7235. Shows TMC2130 currents.
  7236. */
  7237. case 913:
  7238. {
  7239. tmc2130_print_currents();
  7240. }
  7241. break;
  7242. /*!
  7243. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7244. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7245. */
  7246. case 914:
  7247. {
  7248. tmc2130_mode = TMC2130_MODE_NORMAL;
  7249. update_mode_profile();
  7250. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7251. }
  7252. break;
  7253. /*!
  7254. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7255. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7256. */
  7257. case 915:
  7258. {
  7259. tmc2130_mode = TMC2130_MODE_SILENT;
  7260. update_mode_profile();
  7261. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7262. }
  7263. break;
  7264. /*!
  7265. ### 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>
  7266. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7267. #### Usage
  7268. M916 [ X | Y | Z | E ]
  7269. #### Parameters
  7270. - `X` - X stepper driver stallguard sensitivity threshold value
  7271. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7272. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7273. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7274. */
  7275. case 916:
  7276. {
  7277. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7278. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7279. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7280. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7281. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7282. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7283. }
  7284. break;
  7285. /*!
  7286. ### 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>
  7287. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7288. #### Usage
  7289. M917 [ X | Y | Z | E ]
  7290. #### Parameters
  7291. - `X` - X stepper driver PWM amplitude offset value
  7292. - `Y` - Y stepper driver PWM amplitude offset value
  7293. - `Z` - Z stepper driver PWM amplitude offset value
  7294. - `E` - Extruder stepper driver PWM amplitude offset value
  7295. */
  7296. case 917:
  7297. {
  7298. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7299. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7300. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7301. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7302. }
  7303. break;
  7304. /*!
  7305. ### 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>
  7306. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7307. #### Usage
  7308. M918 [ X | Y | Z | E ]
  7309. #### Parameters
  7310. - `X` - X stepper driver PWM amplitude gradient value
  7311. - `Y` - Y stepper driver PWM amplitude gradient value
  7312. - `Z` - Z stepper driver PWM amplitude gradient value
  7313. - `E` - Extruder stepper driver PWM amplitude gradient value
  7314. */
  7315. case 918:
  7316. {
  7317. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7318. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7319. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7320. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7321. }
  7322. break;
  7323. #endif //TMC2130_SERVICE_CODES_M910_M918
  7324. /*!
  7325. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7326. 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!
  7327. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7328. #### Usage
  7329. M350 [ X | Y | Z | E | B | S ]
  7330. #### Parameters
  7331. - `X` - X new resolution
  7332. - `Y` - Y new resolution
  7333. - `Z` - Z new resolution
  7334. - `E` - E new resolution
  7335. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7336. - `B` - Second extruder new resolution
  7337. - `S` - All axes new resolution
  7338. */
  7339. case 350:
  7340. {
  7341. #ifdef TMC2130
  7342. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7343. {
  7344. if(code_seen(axis_codes[i]))
  7345. {
  7346. uint16_t res_new = code_value();
  7347. #ifdef ALLOW_ALL_MRES
  7348. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7349. #else
  7350. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7351. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7352. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7353. #endif
  7354. if (res_valid)
  7355. {
  7356. st_synchronize();
  7357. uint16_t res = tmc2130_get_res(i);
  7358. tmc2130_set_res(i, res_new);
  7359. cs.axis_ustep_resolution[i] = res_new;
  7360. if (res_new > res)
  7361. {
  7362. uint16_t fac = (res_new / res);
  7363. cs.axis_steps_per_unit[i] *= fac;
  7364. position[i] *= fac;
  7365. }
  7366. else
  7367. {
  7368. uint16_t fac = (res / res_new);
  7369. cs.axis_steps_per_unit[i] /= fac;
  7370. position[i] /= fac;
  7371. }
  7372. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  7373. if (i == E_AXIS)
  7374. fsensor.init();
  7375. #endif
  7376. }
  7377. }
  7378. }
  7379. reset_acceleration_rates();
  7380. #else //TMC2130
  7381. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7382. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7383. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7384. if(code_seen('B')) microstep_mode(4,code_value());
  7385. microstep_readings();
  7386. #endif
  7387. #endif //TMC2130
  7388. }
  7389. break;
  7390. /*!
  7391. ### 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>
  7392. Toggle MS1 MS2 pins directly.
  7393. #### Usage
  7394. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7395. #### Parameters
  7396. - `X` - Update X axis
  7397. - `Y` - Update Y axis
  7398. - `Z` - Update Z axis
  7399. - `E` - Update E axis
  7400. - `S` - which MSx pin to toggle
  7401. - `B` - new pin value
  7402. */
  7403. case 351:
  7404. {
  7405. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7406. if(code_seen('S')) switch((int)code_value())
  7407. {
  7408. case 1:
  7409. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7410. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7411. break;
  7412. case 2:
  7413. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7414. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7415. break;
  7416. }
  7417. microstep_readings();
  7418. #endif
  7419. }
  7420. break;
  7421. /*!
  7422. ### M701 - Load filament <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7423. #### Usage
  7424. M701 [ E | T ]
  7425. #### Parameters
  7426. - `E` - ID of filament to load, ranges from 0 to 4
  7427. - `T` - Alias of `E`. Used for compatibility with Marlin
  7428. */
  7429. case 701:
  7430. {
  7431. if (mmu_enabled && (code_seen('E') || code_seen('T')))
  7432. tmp_extruder = code_value_uint8();
  7433. gcode_M701();
  7434. }
  7435. break;
  7436. /*!
  7437. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7438. #### Usage
  7439. M702 [ C ]
  7440. #### Parameters
  7441. - `C` - Unload just current filament
  7442. - without any parameters unload all filaments
  7443. */
  7444. case 702:
  7445. {
  7446. if (code_seen('C')) {
  7447. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  7448. }
  7449. else {
  7450. if(mmu_enabled) extr_unload(); //! unload current filament
  7451. else unload_filament();
  7452. }
  7453. }
  7454. break;
  7455. /*!
  7456. #### End of M-Commands
  7457. */
  7458. default:
  7459. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7460. }
  7461. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7462. mcode_in_progress = 0;
  7463. }
  7464. }
  7465. // end if(code_seen('M')) (end of M codes)
  7466. /*!
  7467. -----------------------------------------------------------------------------------------
  7468. # T Codes
  7469. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7470. #### For MMU_V2:
  7471. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7472. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7473. @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.
  7474. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7475. */
  7476. else if(code_seen('T'))
  7477. {
  7478. static const char duplicate_Tcode_ignored[] PROGMEM = "Duplicate T-code ignored.";
  7479. int index;
  7480. bool load_to_nozzle = false;
  7481. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  7482. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  7483. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  7484. SERIAL_ECHOLNPGM("Invalid T code.");
  7485. }
  7486. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  7487. if (mmu_enabled)
  7488. {
  7489. tmp_extruder = choose_menu_P(_T(MSG_SELECT_FILAMENT), _T(MSG_FILAMENT));
  7490. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7491. {
  7492. puts_P(duplicate_Tcode_ignored);
  7493. }
  7494. else
  7495. {
  7496. st_synchronize();
  7497. mmu_command(MmuCmd::T0 + tmp_extruder);
  7498. manage_response(true, true, MMU_TCODE_MOVE);
  7499. }
  7500. }
  7501. }
  7502. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  7503. if (mmu_enabled)
  7504. {
  7505. st_synchronize();
  7506. mmu_continue_loading(usb_timer.running() || (lcd_commands_type == LcdCommands::Layer1Cal));
  7507. mmu_extruder = tmp_extruder; //filament change is finished
  7508. mmu_load_to_nozzle();
  7509. }
  7510. }
  7511. else {
  7512. if (*(strchr_pointer + index) == '?')
  7513. {
  7514. if(mmu_enabled)
  7515. {
  7516. tmp_extruder = choose_menu_P(_T(MSG_SELECT_FILAMENT), _T(MSG_FILAMENT));
  7517. load_to_nozzle = true;
  7518. } else
  7519. {
  7520. tmp_extruder = choose_menu_P(_T(MSG_SELECT_EXTRUDER), _T(MSG_EXTRUDER));
  7521. }
  7522. }
  7523. else {
  7524. tmp_extruder = code_value();
  7525. if (mmu_enabled && lcd_autoDepleteEnabled())
  7526. {
  7527. tmp_extruder = ad_getAlternative(tmp_extruder);
  7528. }
  7529. }
  7530. st_synchronize();
  7531. if (mmu_enabled)
  7532. {
  7533. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7534. {
  7535. puts_P(duplicate_Tcode_ignored);
  7536. }
  7537. else
  7538. {
  7539. #if defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7540. if (EEPROM_MMU_CUTTER_ENABLED_always == eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED))
  7541. {
  7542. mmu_command(MmuCmd::K0 + tmp_extruder);
  7543. manage_response(true, true, MMU_UNLOAD_MOVE);
  7544. }
  7545. #endif //defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7546. mmu_command(MmuCmd::T0 + tmp_extruder);
  7547. manage_response(true, true, MMU_TCODE_MOVE);
  7548. mmu_continue_loading(usb_timer.running() || (lcd_commands_type == LcdCommands::Layer1Cal));
  7549. mmu_extruder = tmp_extruder; //filament change is finished
  7550. if (load_to_nozzle)// for single material usage with mmu
  7551. {
  7552. mmu_load_to_nozzle();
  7553. }
  7554. }
  7555. }
  7556. else
  7557. {
  7558. if (tmp_extruder >= EXTRUDERS) {
  7559. SERIAL_ECHO_START;
  7560. SERIAL_ECHO('T');
  7561. SERIAL_PROTOCOLLN((int)tmp_extruder);
  7562. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER
  7563. }
  7564. else {
  7565. #if EXTRUDERS > 1
  7566. bool make_move = false;
  7567. #endif
  7568. if (code_seen('F')) {
  7569. #if EXTRUDERS > 1
  7570. make_move = true;
  7571. #endif
  7572. next_feedrate = code_value();
  7573. if (next_feedrate > 0.0) {
  7574. feedrate = next_feedrate;
  7575. }
  7576. }
  7577. #if EXTRUDERS > 1
  7578. if (tmp_extruder != active_extruder) {
  7579. // Save current position to return to after applying extruder offset
  7580. set_destination_to_current();
  7581. // Offset extruder (only by XY)
  7582. int i;
  7583. for (i = 0; i < 2; i++) {
  7584. current_position[i] = current_position[i] -
  7585. extruder_offset[i][active_extruder] +
  7586. extruder_offset[i][tmp_extruder];
  7587. }
  7588. // Set the new active extruder and position
  7589. active_extruder = tmp_extruder;
  7590. plan_set_position_curposXYZE();
  7591. // Move to the old position if 'F' was in the parameters
  7592. if (make_move) {
  7593. prepare_move();
  7594. }
  7595. }
  7596. #endif
  7597. SERIAL_ECHO_START;
  7598. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER
  7599. SERIAL_PROTOCOLLN((int)active_extruder);
  7600. }
  7601. }
  7602. }
  7603. } // end if(code_seen('T')) (end of T codes)
  7604. /*!
  7605. #### End of T-Codes
  7606. */
  7607. /**
  7608. *---------------------------------------------------------------------------------
  7609. *# D codes
  7610. */
  7611. else if (code_seen('D')) // D codes (debug)
  7612. {
  7613. switch(code_value_short())
  7614. {
  7615. /*!
  7616. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7617. */
  7618. case -1:
  7619. dcode__1(); break;
  7620. #ifdef DEBUG_DCODES
  7621. /*!
  7622. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7623. #### Usage
  7624. D0 [ B ]
  7625. #### Parameters
  7626. - `B` - Bootloader
  7627. */
  7628. case 0:
  7629. dcode_0(); break;
  7630. /*!
  7631. *
  7632. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7633. D1
  7634. *
  7635. */
  7636. case 1:
  7637. dcode_1(); break;
  7638. #endif
  7639. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7640. /*!
  7641. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7642. This command can be used without any additional parameters. It will read the entire RAM.
  7643. #### Usage
  7644. D2 [ A | C | X ]
  7645. #### Parameters
  7646. - `A` - Address (x0000-x1fff)
  7647. - `C` - Count (1-8192)
  7648. - `X` - Data
  7649. #### Notes
  7650. - The hex address needs to be lowercase without the 0 before the x
  7651. - Count is decimal
  7652. - The hex data needs to be lowercase
  7653. */
  7654. case 2:
  7655. dcode_2(); break;
  7656. #endif //DEBUG_DCODES
  7657. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7658. /*!
  7659. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7660. This command can be used without any additional parameters. It will read the entire eeprom.
  7661. #### Usage
  7662. D3 [ A | C | X ]
  7663. #### Parameters
  7664. - `A` - Address (x0000-x0fff)
  7665. - `C` - Count (1-4096)
  7666. - `X` - Data (hex)
  7667. #### Notes
  7668. - The hex address needs to be lowercase without the 0 before the x
  7669. - Count is decimal
  7670. - The hex data needs to be lowercase
  7671. */
  7672. case 3:
  7673. dcode_3(); break;
  7674. #endif //DEBUG_DCODE3
  7675. #ifdef DEBUG_DCODES
  7676. /*!
  7677. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7678. To read the digital value of a pin you need only to define the pin number.
  7679. #### Usage
  7680. D4 [ P | F | V ]
  7681. #### Parameters
  7682. - `P` - Pin (0-255)
  7683. - `F` - Function in/out (0/1)
  7684. - `V` - Value (0/1)
  7685. */
  7686. case 4:
  7687. dcode_4(); break;
  7688. #endif //DEBUG_DCODES
  7689. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7690. /*!
  7691. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7692. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7693. #### Usage
  7694. D5 [ A | C | X | E ]
  7695. #### Parameters
  7696. - `A` - Address (x00000-x3ffff)
  7697. - `C` - Count (1-8192)
  7698. - `X` - Data (hex)
  7699. - `E` - Erase
  7700. #### Notes
  7701. - The hex address needs to be lowercase without the 0 before the x
  7702. - Count is decimal
  7703. - The hex data needs to be lowercase
  7704. */
  7705. case 5:
  7706. dcode_5(); break;
  7707. #endif //DEBUG_DCODE5
  7708. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7709. /*!
  7710. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7711. Reserved
  7712. */
  7713. case 6:
  7714. dcode_6(); break;
  7715. #endif
  7716. #ifdef DEBUG_DCODES
  7717. /*!
  7718. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7719. Reserved
  7720. */
  7721. case 7:
  7722. dcode_7(); break;
  7723. /*!
  7724. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7725. #### Usage
  7726. D8 [ ? | ! | P | Z ]
  7727. #### Parameters
  7728. - `?` - Read PINDA temperature shift values
  7729. - `!` - Reset PINDA temperature shift values to default
  7730. - `P` - Pinda temperature [C]
  7731. - `Z` - Z Offset [mm]
  7732. */
  7733. case 8:
  7734. dcode_8(); break;
  7735. /*!
  7736. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7737. #### Usage
  7738. D9 [ I | V ]
  7739. #### Parameters
  7740. - `I` - ADC channel index
  7741. - `0` - Heater 0 temperature
  7742. - `1` - Heater 1 temperature
  7743. - `2` - Bed temperature
  7744. - `3` - PINDA temperature
  7745. - `4` - PWR voltage
  7746. - `5` - Ambient temperature
  7747. - `6` - BED voltage
  7748. - `V` Value to be written as simulated
  7749. */
  7750. case 9:
  7751. dcode_9(); break;
  7752. /*!
  7753. ### 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>
  7754. */
  7755. case 10:
  7756. dcode_10(); break;
  7757. /*!
  7758. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7759. Writes the current time in the log file.
  7760. */
  7761. #endif //DEBUG_DCODES
  7762. #ifdef XFLASH_DUMP
  7763. /*!
  7764. ### 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>
  7765. Generate a crash dump for later retrival.
  7766. #### Usage
  7767. D20 [E]
  7768. ### Parameters
  7769. - `E` - Perform an emergency crash dump (resets the printer).
  7770. ### Notes
  7771. - A crash dump can be later recovered with D21, or cleared with D22.
  7772. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7773. is completed.
  7774. */
  7775. case 20: {
  7776. dcode_20();
  7777. break;
  7778. };
  7779. /*!
  7780. ### 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>
  7781. Output the complete crash dump (if present) to the serial.
  7782. #### Usage
  7783. D21
  7784. ### Notes
  7785. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7786. */
  7787. case 21: {
  7788. dcode_21();
  7789. break;
  7790. };
  7791. /*!
  7792. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7793. Clear an existing internal crash dump.
  7794. #### Usage
  7795. D22
  7796. */
  7797. case 22: {
  7798. dcode_22();
  7799. break;
  7800. };
  7801. #endif //XFLASH_DUMP
  7802. #ifdef EMERGENCY_SERIAL_DUMP
  7803. /*!
  7804. ### 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>
  7805. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7806. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7807. #### Usage
  7808. D23 [E] [R]
  7809. #### Parameters
  7810. - `E` - Perform an emergency crash dump (resets the printer).
  7811. - `R` - Disable online dumps.
  7812. */
  7813. case 23: {
  7814. dcode_23();
  7815. break;
  7816. };
  7817. #endif
  7818. #ifdef TEMP_MODEL_DEBUG
  7819. /*!
  7820. ## D70 - Enable low-level temperature model logging for offline simulation
  7821. #### Usage
  7822. D70 [ S ]
  7823. #### Parameters
  7824. - `S` - Enable 0-1 (default 0)
  7825. */
  7826. case 70: {
  7827. if(code_seen('S'))
  7828. temp_model_log_enable(code_value_short());
  7829. break;
  7830. }
  7831. #endif
  7832. #ifdef HEATBED_ANALYSIS
  7833. /*!
  7834. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7835. This command will log data to SD card file "mesh.txt".
  7836. #### Usage
  7837. D80 [ E | F | G | H | I | J ]
  7838. #### Parameters
  7839. - `E` - Dimension X (default 40)
  7840. - `F` - Dimention Y (default 40)
  7841. - `G` - Points X (default 40)
  7842. - `H` - Points Y (default 40)
  7843. - `I` - Offset X (default 74)
  7844. - `J` - Offset Y (default 34)
  7845. */
  7846. case 80:
  7847. dcode_80(); break;
  7848. /*!
  7849. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7850. This command will log data to SD card file "wldsd.txt".
  7851. #### Usage
  7852. D81 [ E | F | G | H | I | J ]
  7853. #### Parameters
  7854. - `E` - Dimension X (default 40)
  7855. - `F` - Dimention Y (default 40)
  7856. - `G` - Points X (default 40)
  7857. - `H` - Points Y (default 40)
  7858. - `I` - Offset X (default 74)
  7859. - `J` - Offset Y (default 34)
  7860. */
  7861. case 81:
  7862. dcode_81(); break;
  7863. #endif //HEATBED_ANALYSIS
  7864. #ifdef DEBUG_DCODES
  7865. /*!
  7866. ### 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>
  7867. */
  7868. case 106:
  7869. dcode_106(); break;
  7870. #ifdef TMC2130
  7871. /*!
  7872. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7873. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7874. #### Usage
  7875. D2130 [ Axis | Command | Subcommand | Value ]
  7876. #### Parameters
  7877. - Axis
  7878. - `X` - X stepper driver
  7879. - `Y` - Y stepper driver
  7880. - `Z` - Z stepper driver
  7881. - `E` - Extruder stepper driver
  7882. - Commands
  7883. - `0` - Current off
  7884. - `1` - Current on
  7885. - `+` - Single step
  7886. - `-` - Single step oposite direction
  7887. - `NNN` - Value sereval steps
  7888. - `?` - Read register
  7889. - Subcommands for read register
  7890. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7891. - `step` - Step
  7892. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7893. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7894. - `wave` - Microstep linearity compensation curve
  7895. - `!` - Set register
  7896. - Subcommands for set register
  7897. - `mres` - Micro step resolution
  7898. - `step` - Step
  7899. - `wave` - Microstep linearity compensation curve
  7900. - Values for set register
  7901. - `0, 180 --> 250` - Off
  7902. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7903. - `@` - Home calibrate axis
  7904. Examples:
  7905. D2130E?wave
  7906. Print extruder microstep linearity compensation curve
  7907. D2130E!wave0
  7908. Disable extruder linearity compensation curve, (sine curve is used)
  7909. D2130E!wave220
  7910. (sin(x))^1.1 extruder microstep compensation curve used
  7911. Notes:
  7912. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7913. *
  7914. */
  7915. case 2130:
  7916. dcode_2130(); break;
  7917. #endif //TMC2130
  7918. #if (defined (FILAMENT_SENSOR) && defined(PAT9125))
  7919. /*!
  7920. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7921. #### Usage
  7922. D9125 [ ? | ! | R | X | Y | L ]
  7923. #### Parameters
  7924. - `?` - Print values
  7925. - `!` - Print values
  7926. - `R` - Resolution. Not active in code
  7927. - `X` - X values
  7928. - `Y` - Y values
  7929. - `L` - Activate filament sensor log
  7930. */
  7931. case 9125:
  7932. dcode_9125(); break;
  7933. #endif //FILAMENT_SENSOR
  7934. #endif //DEBUG_DCODES
  7935. default:
  7936. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7937. }
  7938. }
  7939. else
  7940. {
  7941. SERIAL_ECHO_START;
  7942. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7943. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7944. SERIAL_ECHOLNPGM("\"(2)");
  7945. }
  7946. KEEPALIVE_STATE(NOT_BUSY);
  7947. ClearToSend();
  7948. }
  7949. /*!
  7950. #### End of D-Codes
  7951. */
  7952. /** @defgroup GCodes G-Code List
  7953. */
  7954. // ---------------------------------------------------
  7955. void FlushSerialRequestResend()
  7956. {
  7957. //char cmdbuffer[bufindr][100]="Resend:";
  7958. MYSERIAL.flush();
  7959. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7960. }
  7961. // Confirm the execution of a command, if sent from a serial line.
  7962. // Execution of a command from a SD card will not be confirmed.
  7963. void ClearToSend()
  7964. {
  7965. previous_millis_cmd.start();
  7966. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7967. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7968. }
  7969. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7970. void update_currents() {
  7971. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7972. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7973. float tmp_motor[3];
  7974. //SERIAL_ECHOLNPGM("Currents updated: ");
  7975. if (destination[Z_AXIS] < Z_SILENT) {
  7976. //SERIAL_ECHOLNPGM("LOW");
  7977. for (uint8_t i = 0; i < 3; i++) {
  7978. st_current_set(i, current_low[i]);
  7979. /*MYSERIAL.print(int(i));
  7980. SERIAL_ECHOPGM(": ");
  7981. MYSERIAL.println(current_low[i]);*/
  7982. }
  7983. }
  7984. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7985. //SERIAL_ECHOLNPGM("HIGH");
  7986. for (uint8_t i = 0; i < 3; i++) {
  7987. st_current_set(i, current_high[i]);
  7988. /*MYSERIAL.print(int(i));
  7989. SERIAL_ECHOPGM(": ");
  7990. MYSERIAL.println(current_high[i]);*/
  7991. }
  7992. }
  7993. else {
  7994. for (uint8_t i = 0; i < 3; i++) {
  7995. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7996. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7997. st_current_set(i, tmp_motor[i]);
  7998. /*MYSERIAL.print(int(i));
  7999. SERIAL_ECHOPGM(": ");
  8000. MYSERIAL.println(tmp_motor[i]);*/
  8001. }
  8002. }
  8003. }
  8004. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8005. void get_coordinates() {
  8006. bool seen[4]={false,false,false,false};
  8007. for(int8_t i=0; i < NUM_AXIS; i++) {
  8008. if(code_seen(axis_codes[i]))
  8009. {
  8010. bool relative = axis_relative_modes & (1 << i);
  8011. destination[i] = code_value();
  8012. if (i == E_AXIS) {
  8013. float emult = extruder_multiplier[active_extruder];
  8014. if (emult != 1.) {
  8015. if (! relative) {
  8016. destination[i] -= current_position[i];
  8017. relative = true;
  8018. }
  8019. destination[i] *= emult;
  8020. }
  8021. }
  8022. if (relative)
  8023. destination[i] += current_position[i];
  8024. seen[i]=true;
  8025. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8026. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  8027. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8028. }
  8029. else destination[i] = current_position[i]; //Are these else lines really needed?
  8030. }
  8031. if(code_seen('F')) {
  8032. next_feedrate = code_value();
  8033. if(next_feedrate > 0.0) feedrate = next_feedrate;
  8034. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  8035. {
  8036. // float e_max_speed =
  8037. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  8038. }
  8039. }
  8040. }
  8041. void clamp_to_software_endstops(float target[3])
  8042. {
  8043. #ifdef DEBUG_DISABLE_SWLIMITS
  8044. return;
  8045. #endif //DEBUG_DISABLE_SWLIMITS
  8046. world2machine_clamp(target[0], target[1]);
  8047. // Clamp the Z coordinate.
  8048. if (min_software_endstops) {
  8049. float negative_z_offset = 0;
  8050. #ifdef ENABLE_AUTO_BED_LEVELING
  8051. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8052. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8053. #endif
  8054. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8055. }
  8056. if (max_software_endstops) {
  8057. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8058. }
  8059. }
  8060. uint16_t restore_interrupted_gcode() {
  8061. // When recovering from a previous print move, restore the originally
  8062. // calculated start position on the first USB/SD command. This accounts
  8063. // properly for relative moves
  8064. if (
  8065. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  8066. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  8067. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  8068. )
  8069. ) {
  8070. memcpy(current_position, saved_start_position, sizeof(current_position));
  8071. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  8072. return saved_segment_idx;
  8073. }
  8074. else
  8075. return 1; //begin with the first segment
  8076. }
  8077. #ifdef MESH_BED_LEVELING
  8078. 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) {
  8079. float dx = x - current_position[X_AXIS];
  8080. float dy = y - current_position[Y_AXIS];
  8081. uint16_t n_segments = 0;
  8082. if (mbl.active) {
  8083. float len = fabs(dx) + fabs(dy);
  8084. if (len > 0)
  8085. // Split to 3cm segments or shorter.
  8086. n_segments = uint16_t(ceil(len / 30.f));
  8087. }
  8088. if (n_segments > 1 && start_segment_idx) {
  8089. float dz = z - current_position[Z_AXIS];
  8090. float de = e - current_position[E_AXIS];
  8091. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  8092. float t = float(i) / float(n_segments);
  8093. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8094. current_position[Y_AXIS] + t * dy,
  8095. current_position[Z_AXIS] + t * dz,
  8096. current_position[E_AXIS] + t * de,
  8097. feed_rate, extruder, current_position, i);
  8098. if (planner_aborted)
  8099. return;
  8100. }
  8101. }
  8102. // The rest of the path.
  8103. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  8104. }
  8105. #endif // MESH_BED_LEVELING
  8106. void prepare_move(uint16_t start_segment_idx)
  8107. {
  8108. clamp_to_software_endstops(destination);
  8109. previous_millis_cmd.start();
  8110. // Do not use feedmultiply for E or Z only moves
  8111. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8112. plan_buffer_line_destinationXYZE(feedrate/60);
  8113. }
  8114. else {
  8115. #ifdef MESH_BED_LEVELING
  8116. 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);
  8117. #else
  8118. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8119. #endif
  8120. }
  8121. set_current_to_destination();
  8122. }
  8123. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8124. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8125. // Trace the arc
  8126. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8127. // As far as the parser is concerned, the position is now == target. In reality the
  8128. // motion control system might still be processing the action and the real tool position
  8129. // in any intermediate location.
  8130. set_current_to_destination();
  8131. previous_millis_cmd.start();
  8132. }
  8133. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8134. #if defined(FAN_PIN)
  8135. #if CONTROLLERFAN_PIN == FAN_PIN
  8136. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8137. #endif
  8138. #endif
  8139. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8140. unsigned long lastMotorCheck = 0;
  8141. void controllerFan()
  8142. {
  8143. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8144. {
  8145. lastMotorCheck = _millis();
  8146. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8147. #if EXTRUDERS > 2
  8148. || !READ(E2_ENABLE_PIN)
  8149. #endif
  8150. #if EXTRUDER > 1
  8151. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8152. || !READ(X2_ENABLE_PIN)
  8153. #endif
  8154. || !READ(E1_ENABLE_PIN)
  8155. #endif
  8156. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8157. {
  8158. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8159. }
  8160. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8161. {
  8162. digitalWrite(CONTROLLERFAN_PIN, 0);
  8163. analogWrite(CONTROLLERFAN_PIN, 0);
  8164. }
  8165. else
  8166. {
  8167. // allows digital or PWM fan output to be used (see M42 handling)
  8168. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8169. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8170. }
  8171. }
  8172. }
  8173. #endif
  8174. #ifdef SAFETYTIMER
  8175. /**
  8176. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8177. *
  8178. * Full screen blocking notification message is shown after heater turning off.
  8179. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8180. * damage print.
  8181. *
  8182. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8183. */
  8184. static void handleSafetyTimer()
  8185. {
  8186. #if (EXTRUDERS > 1)
  8187. #error Implemented only for one extruder.
  8188. #endif //(EXTRUDERS > 1)
  8189. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8190. {
  8191. safetyTimer.stop();
  8192. }
  8193. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8194. {
  8195. safetyTimer.start();
  8196. }
  8197. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8198. {
  8199. setTargetBed(0);
  8200. setAllTargetHotends(0);
  8201. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8202. }
  8203. }
  8204. #endif //SAFETYTIMER
  8205. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8206. {
  8207. #ifdef FILAMENT_SENSOR
  8208. if (fsensor.update()) {
  8209. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8210. }
  8211. #endif
  8212. #ifdef SAFETYTIMER
  8213. handleSafetyTimer();
  8214. #endif //SAFETYTIMER
  8215. #if defined(KILL_PIN) && KILL_PIN > -1
  8216. static int killCount = 0; // make the inactivity button a bit less responsive
  8217. const int KILL_DELAY = 10000;
  8218. #endif
  8219. if(buflen < (BUFSIZE-1)){
  8220. get_command();
  8221. }
  8222. if(previous_millis_cmd.expired(max_inactive_time))
  8223. if(max_inactive_time)
  8224. kill(_n("Inactivity Shutdown"), 4);
  8225. if(stepper_inactive_time) {
  8226. if(previous_millis_cmd.expired(stepper_inactive_time))
  8227. {
  8228. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8229. disable_x();
  8230. disable_y();
  8231. disable_z();
  8232. disable_e0();
  8233. disable_e1();
  8234. disable_e2();
  8235. }
  8236. }
  8237. }
  8238. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8239. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8240. {
  8241. chdkActive = false;
  8242. WRITE(CHDK, LOW);
  8243. }
  8244. #endif
  8245. #if defined(KILL_PIN) && KILL_PIN > -1
  8246. // Check if the kill button was pressed and wait just in case it was an accidental
  8247. // key kill key press
  8248. // -------------------------------------------------------------------------------
  8249. if( 0 == READ(KILL_PIN) )
  8250. {
  8251. killCount++;
  8252. }
  8253. else if (killCount > 0)
  8254. {
  8255. killCount--;
  8256. }
  8257. // Exceeded threshold and we can confirm that it was not accidental
  8258. // KILL the machine
  8259. // ----------------------------------------------------------------
  8260. if ( killCount >= KILL_DELAY)
  8261. {
  8262. kill(NULL, 5);
  8263. }
  8264. #endif
  8265. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8266. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8267. #endif
  8268. #ifdef EXTRUDER_RUNOUT_PREVENT
  8269. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8270. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8271. {
  8272. bool oldstatus=READ(E0_ENABLE_PIN);
  8273. enable_e0();
  8274. float oldepos=current_position[E_AXIS];
  8275. float oldedes=destination[E_AXIS];
  8276. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8277. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8278. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8279. current_position[E_AXIS]=oldepos;
  8280. destination[E_AXIS]=oldedes;
  8281. plan_set_e_position(oldepos);
  8282. previous_millis_cmd.start();
  8283. st_synchronize();
  8284. WRITE(E0_ENABLE_PIN,oldstatus);
  8285. }
  8286. #endif
  8287. check_axes_activity();
  8288. mmu_loop();
  8289. // handle longpress
  8290. if(lcd_longpress_trigger)
  8291. {
  8292. // long press is not possible in modal mode, wait until ready
  8293. if (lcd_longpress_func && lcd_update_enabled)
  8294. {
  8295. lcd_longpress_func();
  8296. lcd_longpress_trigger = 0;
  8297. }
  8298. }
  8299. #if defined(AUTO_REPORT)
  8300. host_autoreport();
  8301. #endif //AUTO_REPORT
  8302. host_keepalive();
  8303. }
  8304. void kill(const char *full_screen_message, unsigned char id)
  8305. {
  8306. printf_P(_N("KILL: %d\n"), id);
  8307. //return;
  8308. cli(); // Stop interrupts
  8309. disable_heater();
  8310. disable_x();
  8311. // SERIAL_ECHOLNPGM("kill - disable Y");
  8312. disable_y();
  8313. poweroff_z();
  8314. disable_e0();
  8315. disable_e1();
  8316. disable_e2();
  8317. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8318. pinMode(PS_ON_PIN,INPUT);
  8319. #endif
  8320. SERIAL_ERROR_START;
  8321. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8322. if (full_screen_message != NULL) {
  8323. SERIAL_ERRORLNRPGM(full_screen_message);
  8324. lcd_display_message_fullscreen_P(full_screen_message);
  8325. } else {
  8326. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8327. }
  8328. // FMC small patch to update the LCD before ending
  8329. sei(); // enable interrupts
  8330. for ( int i=5; i--; lcd_update(0))
  8331. {
  8332. _delay(200);
  8333. }
  8334. cli(); // disable interrupts
  8335. suicide();
  8336. while(1)
  8337. {
  8338. #ifdef WATCHDOG
  8339. wdt_reset();
  8340. #endif //WATCHDOG
  8341. /* Intentionally left empty */
  8342. } // Wait for reset
  8343. }
  8344. void UnconditionalStop()
  8345. {
  8346. CRITICAL_SECTION_START;
  8347. // Disable all heaters and unroll the temperature wait loop stack
  8348. disable_heater();
  8349. cancel_heatup = true;
  8350. heating_status = HeatingStatus::NO_HEATING;
  8351. // Clear any saved printing state
  8352. cancel_saved_printing();
  8353. // Abort the planner
  8354. planner_abort_hard();
  8355. // Reset the queue
  8356. cmdqueue_reset();
  8357. cmdqueue_serial_disabled = false;
  8358. // Reset the sd status
  8359. card.sdprinting = false;
  8360. card.closefile();
  8361. st_reset_timer();
  8362. CRITICAL_SECTION_END;
  8363. }
  8364. // Emergency stop used by overtemp functions which allows recovery
  8365. // WARNING: This function is called *continuously* during a thermal failure.
  8366. //
  8367. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8368. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8369. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8370. // kept in busy state and *must* be recovered from the LCD.
  8371. void ThermalStop(bool allow_pause)
  8372. {
  8373. if(Stopped == false) {
  8374. Stopped = true;
  8375. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8376. if (!isPrintPaused) {
  8377. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8378. // we cannot make a distinction for the host here, the pause must be instantaneous
  8379. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8380. // disable heaters and save the original temperatures to saved_*, which will get
  8381. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8382. // original values after the pause handler is called.
  8383. float bed_temp = saved_bed_temperature;
  8384. float ext_temp = saved_extruder_temperature;
  8385. int fan_speed = saved_fan_speed;
  8386. lcd_pause_print();
  8387. saved_bed_temperature = bed_temp;
  8388. saved_extruder_temperature = ext_temp;
  8389. saved_fan_speed = fan_speed;
  8390. }
  8391. } else {
  8392. // We got a hard thermal error and/or there is no print going on. Just stop.
  8393. lcd_print_stop();
  8394. // Also prevent further menu entry
  8395. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8396. }
  8397. // Report the status on the serial, switch to a busy state
  8398. SERIAL_ERROR_START;
  8399. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8400. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8401. // higher-priority alert status message)
  8402. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8403. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8404. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8405. WRITE(BEEPER, HIGH);
  8406. }
  8407. // Return to the status screen to stop any pending menu action which could have been
  8408. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8409. // error is immediately shown.
  8410. if (menu_menu != lcd_status_screen)
  8411. lcd_return_to_status();
  8412. }
  8413. bool IsStopped() { return Stopped; };
  8414. void finishAndDisableSteppers()
  8415. {
  8416. st_synchronize();
  8417. disable_x();
  8418. disable_y();
  8419. disable_z();
  8420. disable_e0();
  8421. disable_e1();
  8422. disable_e2();
  8423. #ifndef LA_NOCOMPAT
  8424. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8425. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8426. // state for the next print.
  8427. la10c_reset();
  8428. #endif
  8429. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8430. print_time_remaining_init();
  8431. }
  8432. #ifdef FAST_PWM_FAN
  8433. void setPwmFrequency(uint8_t pin, int val)
  8434. {
  8435. val &= 0x07;
  8436. switch(digitalPinToTimer(pin))
  8437. {
  8438. #if defined(TCCR0A)
  8439. case TIMER0A:
  8440. case TIMER0B:
  8441. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8442. // TCCR0B |= val;
  8443. break;
  8444. #endif
  8445. #if defined(TCCR1A)
  8446. case TIMER1A:
  8447. case TIMER1B:
  8448. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8449. // TCCR1B |= val;
  8450. break;
  8451. #endif
  8452. #if defined(TCCR2)
  8453. case TIMER2:
  8454. case TIMER2:
  8455. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8456. TCCR2 |= val;
  8457. break;
  8458. #endif
  8459. #if defined(TCCR2A)
  8460. case TIMER2A:
  8461. case TIMER2B:
  8462. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8463. TCCR2B |= val;
  8464. break;
  8465. #endif
  8466. #if defined(TCCR3A)
  8467. case TIMER3A:
  8468. case TIMER3B:
  8469. case TIMER3C:
  8470. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8471. TCCR3B |= val;
  8472. break;
  8473. #endif
  8474. #if defined(TCCR4A)
  8475. case TIMER4A:
  8476. case TIMER4B:
  8477. case TIMER4C:
  8478. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8479. TCCR4B |= val;
  8480. break;
  8481. #endif
  8482. #if defined(TCCR5A)
  8483. case TIMER5A:
  8484. case TIMER5B:
  8485. case TIMER5C:
  8486. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8487. TCCR5B |= val;
  8488. break;
  8489. #endif
  8490. }
  8491. }
  8492. #endif //FAST_PWM_FAN
  8493. //! @brief Get and validate extruder number
  8494. //!
  8495. //! If it is not specified, active_extruder is returned in parameter extruder.
  8496. //! @param [in] code M code number
  8497. //! @param [out] extruder
  8498. //! @return error
  8499. //! @retval true Invalid extruder specified in T code
  8500. //! @retval false Valid extruder specified in T code, or not specifiead
  8501. bool setTargetedHotend(int code, uint8_t &extruder)
  8502. {
  8503. extruder = active_extruder;
  8504. if(code_seen('T')) {
  8505. extruder = code_value_uint8();
  8506. if(extruder >= EXTRUDERS) {
  8507. SERIAL_ECHO_START;
  8508. switch(code){
  8509. case 104:
  8510. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8511. break;
  8512. case 105:
  8513. SERIAL_ECHORPGM(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8514. break;
  8515. case 109:
  8516. SERIAL_ECHORPGM(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8517. break;
  8518. case 218:
  8519. SERIAL_ECHORPGM(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8520. break;
  8521. case 221:
  8522. SERIAL_ECHORPGM(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8523. break;
  8524. }
  8525. SERIAL_PROTOCOLLN((int)extruder);
  8526. return true;
  8527. }
  8528. }
  8529. return false;
  8530. }
  8531. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8532. {
  8533. 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)
  8534. {
  8535. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8536. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8537. }
  8538. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8539. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8540. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8541. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8542. total_filament_used = 0;
  8543. }
  8544. float calculate_extruder_multiplier(float diameter) {
  8545. float out = 1.f;
  8546. if (cs.volumetric_enabled && diameter > 0.f) {
  8547. float area = M_PI * diameter * diameter * 0.25;
  8548. out = 1.f / area;
  8549. }
  8550. if (extrudemultiply != 100)
  8551. out *= float(extrudemultiply) * 0.01f;
  8552. return out;
  8553. }
  8554. void calculate_extruder_multipliers() {
  8555. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8556. #if EXTRUDERS > 1
  8557. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8558. #if EXTRUDERS > 2
  8559. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8560. #endif
  8561. #endif
  8562. }
  8563. void delay_keep_alive(unsigned int ms)
  8564. {
  8565. for (;;) {
  8566. manage_heater();
  8567. // Manage inactivity, but don't disable steppers on timeout.
  8568. manage_inactivity(true);
  8569. lcd_update(0);
  8570. if (ms == 0)
  8571. break;
  8572. else if (ms >= 50) {
  8573. _delay(50);
  8574. ms -= 50;
  8575. } else {
  8576. _delay(ms);
  8577. ms = 0;
  8578. }
  8579. }
  8580. }
  8581. static void wait_for_heater(long codenum, uint8_t extruder) {
  8582. if (!degTargetHotend(extruder))
  8583. return;
  8584. #ifdef TEMP_RESIDENCY_TIME
  8585. long residencyStart;
  8586. residencyStart = -1;
  8587. /* continue to loop until we have reached the target temp
  8588. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8589. cancel_heatup = false;
  8590. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8591. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8592. #else
  8593. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8594. #endif //TEMP_RESIDENCY_TIME
  8595. if ((_millis() - codenum) > 1000UL)
  8596. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8597. if (!farm_mode) {
  8598. SERIAL_PROTOCOLPGM("T:");
  8599. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8600. SERIAL_PROTOCOLPGM(" E:");
  8601. SERIAL_PROTOCOL((int)extruder);
  8602. #ifdef TEMP_RESIDENCY_TIME
  8603. SERIAL_PROTOCOLPGM(" W:");
  8604. if (residencyStart > -1)
  8605. {
  8606. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8607. SERIAL_PROTOCOLLN(codenum);
  8608. }
  8609. else
  8610. {
  8611. SERIAL_PROTOCOLLN('?');
  8612. }
  8613. }
  8614. #else
  8615. SERIAL_PROTOCOLLN();
  8616. #endif
  8617. codenum = _millis();
  8618. }
  8619. manage_heater();
  8620. manage_inactivity(true); //do not disable steppers
  8621. lcd_update(0);
  8622. #ifdef TEMP_RESIDENCY_TIME
  8623. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8624. or when current temp falls outside the hysteresis after target temp was reached */
  8625. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8626. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8627. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8628. {
  8629. residencyStart = _millis();
  8630. }
  8631. #endif //TEMP_RESIDENCY_TIME
  8632. }
  8633. }
  8634. void check_babystep()
  8635. {
  8636. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8637. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8638. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8639. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8640. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8641. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8642. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8643. babystep_z);
  8644. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8645. lcd_update_enable(true);
  8646. }
  8647. }
  8648. #ifdef HEATBED_ANALYSIS
  8649. void d_setup()
  8650. {
  8651. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8652. pinMode(D_DATA, INPUT_PULLUP);
  8653. pinMode(D_REQUIRE, OUTPUT);
  8654. digitalWrite(D_REQUIRE, HIGH);
  8655. }
  8656. float d_ReadData()
  8657. {
  8658. int digit[13];
  8659. String mergeOutput;
  8660. float output;
  8661. digitalWrite(D_REQUIRE, HIGH);
  8662. for (int i = 0; i<13; i++)
  8663. {
  8664. for (int j = 0; j < 4; j++)
  8665. {
  8666. while (digitalRead(D_DATACLOCK) == LOW) {}
  8667. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8668. bitWrite(digit[i], j, digitalRead(D_DATA));
  8669. }
  8670. }
  8671. digitalWrite(D_REQUIRE, LOW);
  8672. mergeOutput = "";
  8673. output = 0;
  8674. for (int r = 5; r <= 10; r++) //Merge digits
  8675. {
  8676. mergeOutput += digit[r];
  8677. }
  8678. output = mergeOutput.toFloat();
  8679. if (digit[4] == 8) //Handle sign
  8680. {
  8681. output *= -1;
  8682. }
  8683. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8684. {
  8685. output /= 10;
  8686. }
  8687. return output;
  8688. }
  8689. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8690. int t1 = 0;
  8691. int t_delay = 0;
  8692. int digit[13];
  8693. int m;
  8694. char str[3];
  8695. //String mergeOutput;
  8696. char mergeOutput[15];
  8697. float output;
  8698. int mesh_point = 0; //index number of calibration point
  8699. 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
  8700. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8701. float mesh_home_z_search = 4;
  8702. float measure_z_height = 0.2f;
  8703. float row[x_points_num];
  8704. int ix = 0;
  8705. int iy = 0;
  8706. const char* filename_wldsd = "mesh.txt";
  8707. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8708. char numb_wldsd[8]; // (" -A.BCD" + null)
  8709. #ifdef MICROMETER_LOGGING
  8710. d_setup();
  8711. #endif //MICROMETER_LOGGING
  8712. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8713. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8714. unsigned int custom_message_type_old = custom_message_type;
  8715. unsigned int custom_message_state_old = custom_message_state;
  8716. custom_message_type = CustomMsg::MeshBedLeveling;
  8717. custom_message_state = (x_points_num * y_points_num) + 10;
  8718. lcd_update(1);
  8719. //mbl.reset();
  8720. babystep_undo();
  8721. card.openFile(filename_wldsd, false);
  8722. /*destination[Z_AXIS] = mesh_home_z_search;
  8723. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8724. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8725. for(int8_t i=0; i < NUM_AXIS; i++) {
  8726. current_position[i] = destination[i];
  8727. }
  8728. st_synchronize();
  8729. */
  8730. destination[Z_AXIS] = measure_z_height;
  8731. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8732. for(int8_t i=0; i < NUM_AXIS; i++) {
  8733. current_position[i] = destination[i];
  8734. }
  8735. st_synchronize();
  8736. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8737. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8738. SERIAL_PROTOCOL(x_points_num);
  8739. SERIAL_PROTOCOLPGM(",");
  8740. SERIAL_PROTOCOL(y_points_num);
  8741. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8742. SERIAL_PROTOCOL(mesh_home_z_search);
  8743. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8744. SERIAL_PROTOCOL(x_dimension);
  8745. SERIAL_PROTOCOLPGM(",");
  8746. SERIAL_PROTOCOL(y_dimension);
  8747. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8748. while (mesh_point != x_points_num * y_points_num) {
  8749. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8750. iy = mesh_point / x_points_num;
  8751. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8752. float z0 = 0.f;
  8753. /*destination[Z_AXIS] = mesh_home_z_search;
  8754. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8755. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8756. for(int8_t i=0; i < NUM_AXIS; i++) {
  8757. current_position[i] = destination[i];
  8758. }
  8759. st_synchronize();*/
  8760. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8761. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8762. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8763. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8764. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8765. set_current_to_destination();
  8766. st_synchronize();
  8767. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8768. delay_keep_alive(1000);
  8769. #ifdef MICROMETER_LOGGING
  8770. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8771. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8772. //strcat(data_wldsd, numb_wldsd);
  8773. //MYSERIAL.println(data_wldsd);
  8774. //delay(1000);
  8775. //delay(3000);
  8776. //t1 = millis();
  8777. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8778. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8779. memset(digit, 0, sizeof(digit));
  8780. //cli();
  8781. digitalWrite(D_REQUIRE, LOW);
  8782. for (int i = 0; i<13; i++)
  8783. {
  8784. //t1 = millis();
  8785. for (int j = 0; j < 4; j++)
  8786. {
  8787. while (digitalRead(D_DATACLOCK) == LOW) {}
  8788. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8789. //printf_P(PSTR("Done %d\n"), j);
  8790. bitWrite(digit[i], j, digitalRead(D_DATA));
  8791. }
  8792. //t_delay = (millis() - t1);
  8793. //SERIAL_PROTOCOLPGM(" ");
  8794. //SERIAL_PROTOCOL_F(t_delay, 5);
  8795. //SERIAL_PROTOCOLPGM(" ");
  8796. }
  8797. //sei();
  8798. digitalWrite(D_REQUIRE, HIGH);
  8799. mergeOutput[0] = '\0';
  8800. output = 0;
  8801. for (int r = 5; r <= 10; r++) //Merge digits
  8802. {
  8803. sprintf(str, "%d", digit[r]);
  8804. strcat(mergeOutput, str);
  8805. }
  8806. output = atof(mergeOutput);
  8807. if (digit[4] == 8) //Handle sign
  8808. {
  8809. output *= -1;
  8810. }
  8811. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8812. {
  8813. output *= 0.1;
  8814. }
  8815. //output = d_ReadData();
  8816. //row[ix] = current_position[Z_AXIS];
  8817. //row[ix] = d_ReadData();
  8818. row[ix] = output;
  8819. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8820. memset(data_wldsd, 0, sizeof(data_wldsd));
  8821. for (int i = 0; i < x_points_num; i++) {
  8822. SERIAL_PROTOCOLPGM(" ");
  8823. SERIAL_PROTOCOL_F(row[i], 5);
  8824. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8825. dtostrf(row[i], 7, 3, numb_wldsd);
  8826. strcat(data_wldsd, numb_wldsd);
  8827. }
  8828. card.write_command(data_wldsd);
  8829. SERIAL_PROTOCOLPGM("\n");
  8830. }
  8831. custom_message_state--;
  8832. mesh_point++;
  8833. lcd_update(1);
  8834. }
  8835. #endif //MICROMETER_LOGGING
  8836. card.closefile();
  8837. //clean_up_after_endstop_move(l_feedmultiply);
  8838. }
  8839. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8840. int t1 = 0;
  8841. int t_delay = 0;
  8842. int digit[13];
  8843. int m;
  8844. char str[3];
  8845. //String mergeOutput;
  8846. char mergeOutput[15];
  8847. float output;
  8848. int mesh_point = 0; //index number of calibration point
  8849. 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
  8850. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8851. float mesh_home_z_search = 4;
  8852. float row[x_points_num];
  8853. int ix = 0;
  8854. int iy = 0;
  8855. const char* filename_wldsd = "wldsd.txt";
  8856. char data_wldsd[70];
  8857. char numb_wldsd[10];
  8858. d_setup();
  8859. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8860. // We don't know where we are! HOME!
  8861. // Push the commands to the front of the message queue in the reverse order!
  8862. // There shall be always enough space reserved for these commands.
  8863. repeatcommand_front(); // repeat G80 with all its parameters
  8864. enquecommand_front_P(G28W0);
  8865. enquecommand_front_P((PSTR("G1 Z5")));
  8866. return;
  8867. }
  8868. unsigned int custom_message_type_old = custom_message_type;
  8869. unsigned int custom_message_state_old = custom_message_state;
  8870. custom_message_type = CustomMsg::MeshBedLeveling;
  8871. custom_message_state = (x_points_num * y_points_num) + 10;
  8872. lcd_update(1);
  8873. mbl.reset();
  8874. babystep_undo();
  8875. card.openFile(filename_wldsd, false);
  8876. current_position[Z_AXIS] = mesh_home_z_search;
  8877. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8878. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8879. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8880. int l_feedmultiply = setup_for_endstop_move(false);
  8881. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8882. SERIAL_PROTOCOL(x_points_num);
  8883. SERIAL_PROTOCOLPGM(",");
  8884. SERIAL_PROTOCOL(y_points_num);
  8885. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8886. SERIAL_PROTOCOL(mesh_home_z_search);
  8887. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8888. SERIAL_PROTOCOL(x_dimension);
  8889. SERIAL_PROTOCOLPGM(",");
  8890. SERIAL_PROTOCOL(y_dimension);
  8891. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8892. while (mesh_point != x_points_num * y_points_num) {
  8893. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8894. iy = mesh_point / x_points_num;
  8895. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8896. float z0 = 0.f;
  8897. current_position[Z_AXIS] = mesh_home_z_search;
  8898. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8899. st_synchronize();
  8900. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8901. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8902. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8903. st_synchronize();
  8904. 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
  8905. break;
  8906. card.closefile();
  8907. }
  8908. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8909. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8910. //strcat(data_wldsd, numb_wldsd);
  8911. //MYSERIAL.println(data_wldsd);
  8912. //_delay(1000);
  8913. //_delay(3000);
  8914. //t1 = _millis();
  8915. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8916. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8917. memset(digit, 0, sizeof(digit));
  8918. //cli();
  8919. digitalWrite(D_REQUIRE, LOW);
  8920. for (int i = 0; i<13; i++)
  8921. {
  8922. //t1 = _millis();
  8923. for (int j = 0; j < 4; j++)
  8924. {
  8925. while (digitalRead(D_DATACLOCK) == LOW) {}
  8926. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8927. bitWrite(digit[i], j, digitalRead(D_DATA));
  8928. }
  8929. //t_delay = (_millis() - t1);
  8930. //SERIAL_PROTOCOLPGM(" ");
  8931. //SERIAL_PROTOCOL_F(t_delay, 5);
  8932. //SERIAL_PROTOCOLPGM(" ");
  8933. }
  8934. //sei();
  8935. digitalWrite(D_REQUIRE, HIGH);
  8936. mergeOutput[0] = '\0';
  8937. output = 0;
  8938. for (int r = 5; r <= 10; r++) //Merge digits
  8939. {
  8940. sprintf(str, "%d", digit[r]);
  8941. strcat(mergeOutput, str);
  8942. }
  8943. output = atof(mergeOutput);
  8944. if (digit[4] == 8) //Handle sign
  8945. {
  8946. output *= -1;
  8947. }
  8948. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8949. {
  8950. output *= 0.1;
  8951. }
  8952. //output = d_ReadData();
  8953. //row[ix] = current_position[Z_AXIS];
  8954. memset(data_wldsd, 0, sizeof(data_wldsd));
  8955. for (int i = 0; i <3; i++) {
  8956. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8957. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8958. strcat(data_wldsd, numb_wldsd);
  8959. strcat(data_wldsd, ";");
  8960. }
  8961. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8962. dtostrf(output, 8, 5, numb_wldsd);
  8963. strcat(data_wldsd, numb_wldsd);
  8964. //strcat(data_wldsd, ";");
  8965. card.write_command(data_wldsd);
  8966. //row[ix] = d_ReadData();
  8967. row[ix] = output; // current_position[Z_AXIS];
  8968. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8969. for (int i = 0; i < x_points_num; i++) {
  8970. SERIAL_PROTOCOLPGM(" ");
  8971. SERIAL_PROTOCOL_F(row[i], 5);
  8972. }
  8973. SERIAL_PROTOCOLPGM("\n");
  8974. }
  8975. custom_message_state--;
  8976. mesh_point++;
  8977. lcd_update(1);
  8978. }
  8979. card.closefile();
  8980. clean_up_after_endstop_move(l_feedmultiply);
  8981. }
  8982. #endif //HEATBED_ANALYSIS
  8983. #ifndef PINDA_THERMISTOR
  8984. static void temp_compensation_start() {
  8985. custom_message_type = CustomMsg::TempCompPreheat;
  8986. custom_message_state = PINDA_HEAT_T + 1;
  8987. lcd_update(2);
  8988. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8989. current_position[E_AXIS] -= default_retraction;
  8990. }
  8991. plan_buffer_line_curposXYZE(400, active_extruder);
  8992. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8993. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8994. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8995. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8996. st_synchronize();
  8997. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8998. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8999. delay_keep_alive(1000);
  9000. custom_message_state = PINDA_HEAT_T - i;
  9001. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  9002. else lcd_update(1);
  9003. }
  9004. custom_message_type = CustomMsg::Status;
  9005. custom_message_state = 0;
  9006. }
  9007. static void temp_compensation_apply() {
  9008. int i_add;
  9009. int z_shift = 0;
  9010. float z_shift_mm;
  9011. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  9012. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  9013. i_add = (target_temperature_bed - 60) / 10;
  9014. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  9015. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  9016. }else {
  9017. //interpolation
  9018. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  9019. }
  9020. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  9021. 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);
  9022. st_synchronize();
  9023. plan_set_z_position(current_position[Z_AXIS]);
  9024. }
  9025. else {
  9026. //we have no temp compensation data
  9027. }
  9028. }
  9029. #endif //ndef PINDA_THERMISTOR
  9030. float temp_comp_interpolation(float inp_temperature) {
  9031. //cubic spline interpolation
  9032. int n, i, j;
  9033. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  9034. int shift[10];
  9035. int temp_C[10];
  9036. n = 6; //number of measured points
  9037. shift[0] = 0;
  9038. for (i = 0; i < n; i++) {
  9039. if (i > 0) {
  9040. //read shift in steps from EEPROM
  9041. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  9042. }
  9043. temp_C[i] = 50 + i * 10; //temperature in C
  9044. #ifdef PINDA_THERMISTOR
  9045. constexpr int start_compensating_temp = 35;
  9046. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  9047. #ifdef SUPERPINDA_SUPPORT
  9048. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  9049. #endif //SUPERPINDA_SUPPORT
  9050. #else
  9051. temp_C[i] = 50 + i * 10; //temperature in C
  9052. #endif
  9053. x[i] = (float)temp_C[i];
  9054. f[i] = (float)shift[i];
  9055. }
  9056. if (inp_temperature < x[0]) return 0;
  9057. for (i = n - 1; i>0; i--) {
  9058. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9059. h[i - 1] = x[i] - x[i - 1];
  9060. }
  9061. //*********** formation of h, s , f matrix **************
  9062. for (i = 1; i<n - 1; i++) {
  9063. m[i][i] = 2 * (h[i - 1] + h[i]);
  9064. if (i != 1) {
  9065. m[i][i - 1] = h[i - 1];
  9066. m[i - 1][i] = h[i - 1];
  9067. }
  9068. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9069. }
  9070. //*********** forward elimination **************
  9071. for (i = 1; i<n - 2; i++) {
  9072. temp = (m[i + 1][i] / m[i][i]);
  9073. for (j = 1; j <= n - 1; j++)
  9074. m[i + 1][j] -= temp*m[i][j];
  9075. }
  9076. //*********** backward substitution *********
  9077. for (i = n - 2; i>0; i--) {
  9078. sum = 0;
  9079. for (j = i; j <= n - 2; j++)
  9080. sum += m[i][j] * s[j];
  9081. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9082. }
  9083. for (i = 0; i<n - 1; i++)
  9084. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9085. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9086. b = s[i] / 2;
  9087. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9088. d = f[i];
  9089. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9090. }
  9091. return sum;
  9092. }
  9093. #ifdef PINDA_THERMISTOR
  9094. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9095. {
  9096. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9097. if (!calibration_status_pinda()) return 0;
  9098. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9099. }
  9100. #endif //PINDA_THERMISTOR
  9101. void long_pause() //long pause print
  9102. {
  9103. st_synchronize();
  9104. start_pause_print = _millis();
  9105. // Stop heaters
  9106. heating_status = HeatingStatus::NO_HEATING;
  9107. setAllTargetHotends(0);
  9108. // Lift z
  9109. raise_z_above(current_position[Z_AXIS] + Z_PAUSE_LIFT, true);
  9110. // Move XY to side
  9111. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9112. current_position[X_AXIS] = X_PAUSE_POS;
  9113. current_position[Y_AXIS] = Y_PAUSE_POS;
  9114. plan_buffer_line_curposXYZE(50);
  9115. }
  9116. // did we come here from a thermal error?
  9117. if(get_temp_error()) {
  9118. // time to stop the error beep
  9119. WRITE(BEEPER, LOW);
  9120. } else {
  9121. // Turn off the print fan
  9122. fanSpeed = 0;
  9123. }
  9124. }
  9125. void serialecho_temperatures() {
  9126. float tt = degHotend(active_extruder);
  9127. SERIAL_PROTOCOLPGM("T:");
  9128. SERIAL_PROTOCOL(tt);
  9129. SERIAL_PROTOCOLPGM(" E:");
  9130. SERIAL_PROTOCOL((int)active_extruder);
  9131. SERIAL_PROTOCOLPGM(" B:");
  9132. SERIAL_PROTOCOL_F(degBed(), 1);
  9133. SERIAL_PROTOCOLLN();
  9134. }
  9135. #ifdef UVLO_SUPPORT
  9136. void uvlo_drain_reset()
  9137. {
  9138. // burn all that residual power
  9139. wdt_enable(WDTO_1S);
  9140. WRITE(BEEPER,HIGH);
  9141. lcd_clear();
  9142. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9143. while(1);
  9144. }
  9145. void uvlo_()
  9146. {
  9147. unsigned long time_start = _millis();
  9148. bool sd_print = card.sdprinting;
  9149. // Conserve power as soon as possible.
  9150. #ifdef LCD_BL_PIN
  9151. backlightMode = BACKLIGHT_MODE_DIM;
  9152. backlightLevel_LOW = 0;
  9153. backlight_update();
  9154. #endif //LCD_BL_PIN
  9155. disable_x();
  9156. disable_y();
  9157. #ifdef TMC2130
  9158. tmc2130_set_current_h(Z_AXIS, 20);
  9159. tmc2130_set_current_r(Z_AXIS, 20);
  9160. tmc2130_set_current_h(E_AXIS, 20);
  9161. tmc2130_set_current_r(E_AXIS, 20);
  9162. #endif //TMC2130
  9163. // Stop all heaters
  9164. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9165. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9166. setAllTargetHotends(0);
  9167. setTargetBed(0);
  9168. // Calculate the file position, from which to resume this print.
  9169. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9170. {
  9171. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9172. sd_position -= sdlen_planner;
  9173. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9174. sd_position -= sdlen_cmdqueue;
  9175. if (sd_position < 0) sd_position = 0;
  9176. }
  9177. // save the global state at planning time
  9178. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9179. uint16_t feedrate_bckp;
  9180. if (current_block && !pos_invalid)
  9181. {
  9182. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9183. feedrate_bckp = current_block->gcode_feedrate;
  9184. saved_segment_idx = current_block->segment_idx;
  9185. }
  9186. else
  9187. {
  9188. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9189. feedrate_bckp = feedrate;
  9190. saved_segment_idx = 0;
  9191. }
  9192. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9193. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9194. // get the physical Z for further manipulation.
  9195. bool mbl_was_active = mbl.active;
  9196. mbl.active = false;
  9197. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9198. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9199. // are in action.
  9200. planner_abort_hard();
  9201. // Store the print logical Z position, which we need to recover (a slight error here would be
  9202. // recovered on the next Gcode instruction, while a physical location error would not)
  9203. float logical_z = current_position[Z_AXIS];
  9204. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9205. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9206. // Store the print E position before we lose track
  9207. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9208. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9209. // Clean the input command queue, inhibit serial processing using saved_printing
  9210. cmdqueue_reset();
  9211. card.sdprinting = false;
  9212. saved_printing = true;
  9213. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9214. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9215. planner_aborted = false;
  9216. sei();
  9217. // Retract
  9218. current_position[E_AXIS] -= default_retraction;
  9219. plan_buffer_line_curposXYZE(95);
  9220. st_synchronize();
  9221. disable_e0();
  9222. // Read out the current Z motor microstep counter to move the axis up towards
  9223. // a full step before powering off. NOTE: we need to ensure to schedule more
  9224. // than "dropsegments" steps in order to move (this is always the case here
  9225. // due to UVLO_Z_AXIS_SHIFT being used)
  9226. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9227. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9228. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9229. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9230. + UVLO_Z_AXIS_SHIFT;
  9231. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9232. st_synchronize();
  9233. poweroff_z();
  9234. // Write the file position.
  9235. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9236. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9237. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9238. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9239. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9240. // Scale the z value to 1u resolution.
  9241. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9242. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9243. }
  9244. // Write the _final_ Z position and motor microstep counter (unused).
  9245. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9246. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9247. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9248. // Store the current position.
  9249. if (pos_invalid)
  9250. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9251. else
  9252. {
  9253. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9254. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9255. }
  9256. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9257. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9258. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9259. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9260. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9261. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9262. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9263. #if EXTRUDERS > 1
  9264. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9265. #if EXTRUDERS > 2
  9266. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9267. #endif
  9268. #endif
  9269. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9270. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9271. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9272. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9273. // Store the saved target
  9274. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9275. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9276. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9277. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9278. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9279. #ifdef LIN_ADVANCE
  9280. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9281. #endif
  9282. // Finaly store the "power outage" flag.
  9283. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9284. // Increment power failure counter
  9285. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9286. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9287. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9288. WRITE(BEEPER,HIGH);
  9289. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9290. poweron_z();
  9291. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9292. plan_buffer_line_curposXYZE(500);
  9293. st_synchronize();
  9294. wdt_enable(WDTO_1S);
  9295. while(1);
  9296. }
  9297. void uvlo_tiny()
  9298. {
  9299. unsigned long time_start = _millis();
  9300. // Conserve power as soon as possible.
  9301. disable_x();
  9302. disable_y();
  9303. disable_e0();
  9304. #ifdef TMC2130
  9305. tmc2130_set_current_h(Z_AXIS, 20);
  9306. tmc2130_set_current_r(Z_AXIS, 20);
  9307. #endif //TMC2130
  9308. // Stop all heaters
  9309. setAllTargetHotends(0);
  9310. setTargetBed(0);
  9311. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9312. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9313. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9314. // Disable MBL (if not already) to work with physical coordinates.
  9315. mbl.active = false;
  9316. planner_abort_hard();
  9317. // Allow for small roundoffs to be ignored
  9318. 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])
  9319. {
  9320. // Clean the input command queue, inhibit serial processing using saved_printing
  9321. cmdqueue_reset();
  9322. card.sdprinting = false;
  9323. saved_printing = true;
  9324. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9325. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9326. planner_aborted = false;
  9327. sei();
  9328. // The axis was moved: adjust Z as done on a regular UVLO.
  9329. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9330. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9331. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9332. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9333. + UVLO_TINY_Z_AXIS_SHIFT;
  9334. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9335. st_synchronize();
  9336. poweroff_z();
  9337. // Update Z position
  9338. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9339. // Update the _final_ Z motor microstep counter (unused).
  9340. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9341. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9342. }
  9343. // Update the the "power outage" flag.
  9344. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9345. // Increment power failure counter
  9346. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9347. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9348. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9349. uvlo_drain_reset();
  9350. }
  9351. #endif //UVLO_SUPPORT
  9352. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9353. void setup_fan_interrupt() {
  9354. //INT7
  9355. DDRE &= ~(1 << 7); //input pin
  9356. PORTE &= ~(1 << 7); //no internal pull-up
  9357. //start with sensing rising edge
  9358. EICRB &= ~(1 << 6);
  9359. EICRB |= (1 << 7);
  9360. //enable INT7 interrupt
  9361. EIMSK |= (1 << 7);
  9362. }
  9363. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9364. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9365. ISR(INT7_vect) {
  9366. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9367. #ifdef FAN_SOFT_PWM
  9368. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9369. #else //FAN_SOFT_PWM
  9370. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9371. #endif //FAN_SOFT_PWM
  9372. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9373. t_fan_rising_edge = millis_nc();
  9374. }
  9375. else { //interrupt was triggered by falling edge
  9376. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9377. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9378. }
  9379. }
  9380. EICRB ^= (1 << 6); //change edge
  9381. }
  9382. #endif
  9383. #ifdef UVLO_SUPPORT
  9384. void setup_uvlo_interrupt() {
  9385. DDRE &= ~(1 << 4); //input pin
  9386. PORTE &= ~(1 << 4); //no internal pull-up
  9387. // sensing falling edge
  9388. EICRB |= (1 << 0);
  9389. EICRB &= ~(1 << 1);
  9390. // enable INT4 interrupt
  9391. EIMSK |= (1 << 4);
  9392. // check if power was lost before we armed the interrupt
  9393. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9394. {
  9395. SERIAL_ECHOLNPGM("INT4");
  9396. uvlo_drain_reset();
  9397. }
  9398. }
  9399. ISR(INT4_vect) {
  9400. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9401. SERIAL_ECHOLNPGM("INT4");
  9402. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9403. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9404. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9405. }
  9406. void recover_print(uint8_t automatic) {
  9407. char cmd[30];
  9408. lcd_update_enable(true);
  9409. lcd_update(2);
  9410. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9411. // Recover position, temperatures and extrude_multipliers
  9412. bool mbl_was_active = recover_machine_state_after_power_panic();
  9413. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9414. // and second also so one may remove the excess priming material.
  9415. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9416. {
  9417. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9418. enquecommand(cmd);
  9419. }
  9420. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9421. // transformation status. G28 will not touch Z when MBL is off.
  9422. enquecommand_P(PSTR("G28 X Y"));
  9423. // Set the target bed and nozzle temperatures and wait.
  9424. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9425. enquecommand(cmd);
  9426. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9427. enquecommand(cmd);
  9428. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9429. enquecommand(cmd);
  9430. enquecommand_P(PSTR("M83")); //E axis relative mode
  9431. // If not automatically recoreverd (long power loss)
  9432. if(automatic == 0){
  9433. //Extrude some filament to stabilize the pressure
  9434. enquecommand_P(PSTR("G1 E5 F120"));
  9435. // Retract to be consistent with a short pause
  9436. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9437. enquecommand(cmd);
  9438. }
  9439. 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]);
  9440. // Restart the print.
  9441. restore_print_from_eeprom(mbl_was_active);
  9442. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9443. }
  9444. bool recover_machine_state_after_power_panic()
  9445. {
  9446. // 1) Preset some dummy values for the XY axes
  9447. current_position[X_AXIS] = 0;
  9448. current_position[Y_AXIS] = 0;
  9449. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9450. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9451. bool mbl_was_active = false;
  9452. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9453. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9454. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9455. // Scale the z value to 10u resolution.
  9456. int16_t v;
  9457. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9458. if (v != 0)
  9459. mbl_was_active = true;
  9460. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9461. }
  9462. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9463. // The current position after power panic is moved to the next closest 0th full step.
  9464. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9465. // Recover last E axis position
  9466. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9467. // 3) Initialize the logical to physical coordinate system transformation.
  9468. world2machine_initialize();
  9469. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9470. // print_mesh_bed_leveling_table();
  9471. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9472. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9473. babystep_load();
  9474. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9475. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9476. clamp_to_software_endstops(current_position);
  9477. set_destination_to_current();
  9478. plan_set_position_curposXYZE();
  9479. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9480. print_world_coordinates();
  9481. // 6) Power up the Z motors, mark their positions as known.
  9482. axis_known_position[Z_AXIS] = true;
  9483. enable_z();
  9484. // 7) Recover the target temperatures.
  9485. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9486. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9487. // 8) Recover extruder multipilers
  9488. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9489. #if EXTRUDERS > 1
  9490. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9491. #if EXTRUDERS > 2
  9492. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9493. #endif
  9494. #endif
  9495. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9496. // 9) Recover the saved target
  9497. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9498. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9499. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9500. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9501. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9502. #ifdef LIN_ADVANCE
  9503. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9504. #endif
  9505. return mbl_was_active;
  9506. }
  9507. void restore_print_from_eeprom(bool mbl_was_active) {
  9508. int feedrate_rec;
  9509. int feedmultiply_rec;
  9510. uint8_t fan_speed_rec;
  9511. char cmd[48];
  9512. char filename[FILENAME_LENGTH];
  9513. uint8_t depth = 0;
  9514. char dir_name[9];
  9515. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9516. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9517. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9518. SERIAL_ECHOPGM("Feedrate:");
  9519. MYSERIAL.print(feedrate_rec);
  9520. SERIAL_ECHOPGM(", feedmultiply:");
  9521. MYSERIAL.println(feedmultiply_rec);
  9522. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9523. MYSERIAL.println(int(depth));
  9524. for (uint8_t i = 0; i < depth; i++) {
  9525. for (uint8_t j = 0; j < 8; j++) {
  9526. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9527. }
  9528. dir_name[8] = '\0';
  9529. MYSERIAL.println(dir_name);
  9530. // strcpy(card.dir_names[i], dir_name);
  9531. card.chdir(dir_name, false);
  9532. }
  9533. for (uint8_t i = 0; i < 8; i++) {
  9534. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9535. }
  9536. filename[8] = '\0';
  9537. MYSERIAL.print(filename);
  9538. strcat_P(filename, PSTR(".gco"));
  9539. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9540. enquecommand(cmd);
  9541. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9542. SERIAL_ECHOPGM("Position read from eeprom:");
  9543. MYSERIAL.println(position);
  9544. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9545. // without shifting Z along the way. This requires performing the move without mbl.
  9546. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9547. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9548. if (pos_x != X_COORD_INVALID)
  9549. {
  9550. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9551. enquecommand(cmd);
  9552. }
  9553. // Enable MBL and switch to logical positioning
  9554. if (mbl_was_active)
  9555. enquecommand_P(PSTR("PRUSA MBL V1"));
  9556. // Move the Z axis down to the print, in logical coordinates.
  9557. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9558. enquecommand(cmd);
  9559. // Restore acceleration settings
  9560. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9561. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9562. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9563. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9564. enquecommand(cmd);
  9565. // Unretract.
  9566. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9567. enquecommand(cmd);
  9568. // Recover final E axis position and mode
  9569. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9570. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9571. enquecommand(cmd);
  9572. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9573. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9574. // Set the feedrates saved at the power panic.
  9575. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9576. enquecommand(cmd);
  9577. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9578. enquecommand(cmd);
  9579. // Set the fan speed saved at the power panic.
  9580. strcpy_P(cmd, PSTR("M106 S"));
  9581. strcat(cmd, itostr3(int(fan_speed_rec)));
  9582. enquecommand(cmd);
  9583. // Set a position in the file.
  9584. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9585. enquecommand(cmd);
  9586. enquecommand_P(PSTR("G4 S0"));
  9587. enquecommand_P(PSTR("PRUSA uvlo"));
  9588. }
  9589. #endif //UVLO_SUPPORT
  9590. //! @brief Immediately stop print moves
  9591. //!
  9592. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9593. //! If printing from sd card, position in file is saved.
  9594. //! If printing from USB, line number is saved.
  9595. //!
  9596. //! @param z_move
  9597. //! @param e_move
  9598. void stop_and_save_print_to_ram(float z_move, float e_move)
  9599. {
  9600. if (saved_printing) return;
  9601. #if 0
  9602. unsigned char nplanner_blocks;
  9603. #endif
  9604. unsigned char nlines;
  9605. uint16_t sdlen_planner;
  9606. uint16_t sdlen_cmdqueue;
  9607. cli();
  9608. if (card.sdprinting) {
  9609. #if 0
  9610. nplanner_blocks = number_of_blocks();
  9611. #endif
  9612. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9613. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9614. saved_sdpos -= sdlen_planner;
  9615. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9616. saved_sdpos -= sdlen_cmdqueue;
  9617. saved_printing_type = PRINTING_TYPE_SD;
  9618. }
  9619. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9620. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9621. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9622. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9623. saved_sdpos -= nlines;
  9624. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9625. saved_printing_type = PRINTING_TYPE_USB;
  9626. }
  9627. else {
  9628. saved_printing_type = PRINTING_TYPE_NONE;
  9629. //not sd printing nor usb printing
  9630. }
  9631. #if 0
  9632. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9633. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9634. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9635. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9636. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9637. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9638. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9639. {
  9640. card.setIndex(saved_sdpos);
  9641. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9642. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9643. MYSERIAL.print(char(card.get()));
  9644. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9645. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9646. MYSERIAL.print(char(card.get()));
  9647. SERIAL_ECHOLNPGM("End of command buffer");
  9648. }
  9649. {
  9650. // Print the content of the planner buffer, line by line:
  9651. card.setIndex(saved_sdpos);
  9652. int8_t iline = 0;
  9653. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9654. SERIAL_ECHOPGM("Planner line (from file): ");
  9655. MYSERIAL.print(int(iline), DEC);
  9656. SERIAL_ECHOPGM(", length: ");
  9657. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9658. SERIAL_ECHOPGM(", steps: (");
  9659. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9660. SERIAL_ECHOPGM(",");
  9661. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9662. SERIAL_ECHOPGM(",");
  9663. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9664. SERIAL_ECHOPGM(",");
  9665. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9666. SERIAL_ECHOPGM("), events: ");
  9667. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9668. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9669. MYSERIAL.print(char(card.get()));
  9670. }
  9671. }
  9672. {
  9673. // Print the content of the command buffer, line by line:
  9674. int8_t iline = 0;
  9675. union {
  9676. struct {
  9677. char lo;
  9678. char hi;
  9679. } lohi;
  9680. uint16_t value;
  9681. } sdlen_single;
  9682. int _bufindr = bufindr;
  9683. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9684. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9685. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9686. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9687. }
  9688. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9689. MYSERIAL.print(int(iline), DEC);
  9690. SERIAL_ECHOPGM(", type: ");
  9691. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9692. SERIAL_ECHOPGM(", len: ");
  9693. MYSERIAL.println(sdlen_single.value, DEC);
  9694. // Print the content of the buffer line.
  9695. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9696. SERIAL_ECHOPGM("Buffer line (from file): ");
  9697. MYSERIAL.println(int(iline), DEC);
  9698. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9699. MYSERIAL.print(char(card.get()));
  9700. if (-- _buflen == 0)
  9701. break;
  9702. // First skip the current command ID and iterate up to the end of the string.
  9703. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9704. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9705. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9706. // If the end of the buffer was empty,
  9707. if (_bufindr == sizeof(cmdbuffer)) {
  9708. // skip to the start and find the nonzero command.
  9709. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9710. }
  9711. }
  9712. }
  9713. #endif
  9714. // save the global state at planning time
  9715. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9716. if (current_block && !pos_invalid)
  9717. {
  9718. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9719. saved_feedrate2 = current_block->gcode_feedrate;
  9720. saved_segment_idx = current_block->segment_idx;
  9721. // 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);
  9722. }
  9723. else
  9724. {
  9725. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9726. saved_feedrate2 = feedrate;
  9727. saved_segment_idx = 0;
  9728. }
  9729. planner_abort_hard(); //abort printing
  9730. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9731. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9732. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9733. saved_active_extruder = active_extruder; //save active_extruder
  9734. saved_extruder_temperature = degTargetHotend(active_extruder);
  9735. saved_bed_temperature = degTargetBed();
  9736. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9737. saved_fan_speed = fanSpeed;
  9738. cmdqueue_reset(); //empty cmdqueue
  9739. card.sdprinting = false;
  9740. // card.closefile();
  9741. saved_printing = true;
  9742. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9743. st_reset_timer();
  9744. sei();
  9745. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9746. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9747. // the caller can continue processing. This is used during powerpanic to save the state as we
  9748. // move away from the print.
  9749. char buf[48];
  9750. if(e_move)
  9751. {
  9752. // First unretract (relative extrusion)
  9753. if(!saved_extruder_relative_mode){
  9754. enquecommand(PSTR("M83"), true);
  9755. }
  9756. //retract 45mm/s
  9757. // A single sprintf may not be faster, but is definitely 20B shorter
  9758. // than a sequence of commands building the string piece by piece
  9759. // A snprintf would have been a safer call, but since it is not used
  9760. // in the whole program, its implementation would bring more bytes to the total size
  9761. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9762. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9763. enquecommand(buf, false);
  9764. }
  9765. if(z_move)
  9766. {
  9767. // Then lift Z axis
  9768. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9769. enquecommand(buf, false);
  9770. }
  9771. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9772. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9773. repeatcommand_front();
  9774. }
  9775. }
  9776. //! @brief Restore print from ram
  9777. //!
  9778. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9779. //! print fan speed, waits for extruder temperature restore, then restores
  9780. //! position and continues print moves.
  9781. //!
  9782. //! Internally lcd_update() is called by wait_for_heater().
  9783. //!
  9784. //! @param e_move
  9785. void restore_print_from_ram_and_continue(float e_move)
  9786. {
  9787. if (!saved_printing) return;
  9788. #ifdef FANCHECK
  9789. // Do not allow resume printing if fans are still not ok
  9790. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9791. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9792. #endif
  9793. // restore bed temperature (bed can be disabled during a thermal warning)
  9794. if (degBed() != saved_bed_temperature)
  9795. setTargetBed(saved_bed_temperature);
  9796. // restore active_extruder
  9797. active_extruder = saved_active_extruder;
  9798. fanSpeed = saved_fan_speed;
  9799. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  9800. {
  9801. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  9802. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9803. wait_for_heater(_millis(), saved_active_extruder);
  9804. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9805. }
  9806. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9807. float e = saved_pos[E_AXIS] - e_move;
  9808. plan_set_e_position(e);
  9809. #ifdef FANCHECK
  9810. fans_check_enabled = false;
  9811. #endif
  9812. // do not restore XY for commands that do not require that
  9813. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9814. {
  9815. saved_pos[X_AXIS] = current_position[X_AXIS];
  9816. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9817. }
  9818. //first move print head in XY to the saved position:
  9819. 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);
  9820. //then move Z
  9821. 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);
  9822. //and finaly unretract (35mm/s)
  9823. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9824. st_synchronize();
  9825. #ifdef FANCHECK
  9826. fans_check_enabled = true;
  9827. #endif
  9828. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9829. feedrate = saved_feedrate2;
  9830. feedmultiply = saved_feedmultiply2;
  9831. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9832. set_destination_to_current();
  9833. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9834. card.setIndex(saved_sdpos);
  9835. sdpos_atomic = saved_sdpos;
  9836. card.sdprinting = true;
  9837. }
  9838. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9839. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9840. serial_count = 0;
  9841. FlushSerialRequestResend();
  9842. }
  9843. else {
  9844. //not sd printing nor usb printing
  9845. }
  9846. lcd_setstatuspgm(MSG_WELCOME);
  9847. saved_printing_type = PRINTING_TYPE_NONE;
  9848. saved_printing = false;
  9849. planner_aborted = true; // unroll the stack
  9850. }
  9851. // Cancel the state related to a currently saved print
  9852. void cancel_saved_printing()
  9853. {
  9854. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9855. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9856. saved_printing_type = PRINTING_TYPE_NONE;
  9857. saved_printing = false;
  9858. }
  9859. void print_world_coordinates()
  9860. {
  9861. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9862. }
  9863. void print_physical_coordinates()
  9864. {
  9865. 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));
  9866. }
  9867. void print_mesh_bed_leveling_table()
  9868. {
  9869. SERIAL_ECHOPGM("mesh bed leveling: ");
  9870. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9871. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9872. MYSERIAL.print(mbl.z_values[y][x], 3);
  9873. SERIAL_ECHO(' ');
  9874. }
  9875. SERIAL_ECHOLN();
  9876. }
  9877. uint8_t calc_percent_done()
  9878. {
  9879. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9880. uint8_t percent_done = 0;
  9881. #ifdef TMC2130
  9882. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9883. {
  9884. percent_done = print_percent_done_normal;
  9885. }
  9886. else if (print_percent_done_silent <= 100)
  9887. {
  9888. percent_done = print_percent_done_silent;
  9889. }
  9890. #else
  9891. if (print_percent_done_normal <= 100)
  9892. {
  9893. percent_done = print_percent_done_normal;
  9894. }
  9895. #endif //TMC2130
  9896. else
  9897. {
  9898. percent_done = card.percentDone();
  9899. }
  9900. return percent_done;
  9901. }
  9902. static void print_time_remaining_init()
  9903. {
  9904. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9905. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9906. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9907. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9908. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9909. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9910. }
  9911. void load_filament_final_feed()
  9912. {
  9913. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9914. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9915. }
  9916. //! @brief Wait for user to check the state
  9917. //! @par nozzle_temp nozzle temperature to load filament
  9918. void M600_check_state(float nozzle_temp)
  9919. {
  9920. lcd_change_fil_state = 0;
  9921. while (lcd_change_fil_state != 1)
  9922. {
  9923. lcd_change_fil_state = 0;
  9924. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9925. lcd_alright();
  9926. KEEPALIVE_STATE(IN_HANDLER);
  9927. switch(lcd_change_fil_state)
  9928. {
  9929. // Filament failed to load so load it again
  9930. case 2:
  9931. if (mmu_enabled)
  9932. mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  9933. else
  9934. M600_load_filament_movements();
  9935. break;
  9936. // Filament loaded properly but color is not clear
  9937. case 3:
  9938. st_synchronize();
  9939. load_filament_final_feed();
  9940. lcd_loading_color();
  9941. st_synchronize();
  9942. break;
  9943. // Everything good
  9944. default:
  9945. lcd_change_success();
  9946. break;
  9947. }
  9948. }
  9949. }
  9950. //! @brief Wait for user action
  9951. //!
  9952. //! Beep, manage nozzle heater and wait for user to start unload filament
  9953. //! If times out, active extruder temperature is set to 0.
  9954. //!
  9955. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9956. void M600_wait_for_user(float HotendTempBckp) {
  9957. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9958. int counterBeep = 0;
  9959. unsigned long waiting_start_time = _millis();
  9960. uint8_t wait_for_user_state = 0;
  9961. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9962. bool bFirst=true;
  9963. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9964. manage_heater();
  9965. manage_inactivity(true);
  9966. #if BEEPER > 0
  9967. if (counterBeep == 500) {
  9968. counterBeep = 0;
  9969. }
  9970. SET_OUTPUT(BEEPER);
  9971. if (counterBeep == 0) {
  9972. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9973. {
  9974. bFirst=false;
  9975. WRITE(BEEPER, HIGH);
  9976. }
  9977. }
  9978. if (counterBeep == 20) {
  9979. WRITE(BEEPER, LOW);
  9980. }
  9981. counterBeep++;
  9982. #endif //BEEPER > 0
  9983. switch (wait_for_user_state) {
  9984. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9985. delay_keep_alive(4);
  9986. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9987. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9988. wait_for_user_state = 1;
  9989. setAllTargetHotends(0);
  9990. st_synchronize();
  9991. disable_e0();
  9992. disable_e1();
  9993. disable_e2();
  9994. }
  9995. break;
  9996. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9997. delay_keep_alive(4);
  9998. if (lcd_clicked()) {
  9999. setTargetHotend(HotendTempBckp, active_extruder);
  10000. lcd_wait_for_heater();
  10001. wait_for_user_state = 2;
  10002. }
  10003. break;
  10004. case 2: //waiting for nozzle to reach target temperature
  10005. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  10006. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10007. waiting_start_time = _millis();
  10008. wait_for_user_state = 0;
  10009. }
  10010. else {
  10011. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  10012. lcd_set_cursor(1, 4);
  10013. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  10014. }
  10015. break;
  10016. }
  10017. }
  10018. WRITE(BEEPER, LOW);
  10019. }
  10020. void M600_load_filament_movements()
  10021. {
  10022. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  10023. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  10024. load_filament_final_feed();
  10025. lcd_loading_filament();
  10026. st_synchronize();
  10027. }
  10028. void M600_load_filament() {
  10029. //load filament for single material and MMU
  10030. lcd_wait_interact();
  10031. //load_filament_time = _millis();
  10032. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10033. while(!lcd_clicked())
  10034. {
  10035. manage_heater();
  10036. manage_inactivity(true);
  10037. #ifdef FILAMENT_SENSOR
  10038. if (fsensor.getFilamentLoadEvent()) {
  10039. Sound_MakeCustom(50,1000,false);
  10040. break;
  10041. }
  10042. #endif //FILAMENT_SENSOR
  10043. }
  10044. KEEPALIVE_STATE(IN_HANDLER);
  10045. M600_load_filament_movements();
  10046. Sound_MakeCustom(50,1000,false);
  10047. lcd_update_enable(false);
  10048. }
  10049. //! @brief Wait for click
  10050. //!
  10051. //! Set
  10052. void marlin_wait_for_click()
  10053. {
  10054. int8_t busy_state_backup = busy_state;
  10055. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10056. lcd_consume_click();
  10057. while(!lcd_clicked())
  10058. {
  10059. manage_heater();
  10060. manage_inactivity(true);
  10061. lcd_update(0);
  10062. }
  10063. KEEPALIVE_STATE(busy_state_backup);
  10064. }
  10065. #define FIL_LOAD_LENGTH 60
  10066. #ifdef PSU_Delta
  10067. bool bEnableForce_z;
  10068. void init_force_z()
  10069. {
  10070. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10071. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10072. disable_force_z();
  10073. }
  10074. void check_force_z()
  10075. {
  10076. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10077. init_force_z(); // causes enforced switching into disable-state
  10078. }
  10079. void disable_force_z()
  10080. {
  10081. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10082. bEnableForce_z=false;
  10083. // switching to silent mode
  10084. #ifdef TMC2130
  10085. tmc2130_mode=TMC2130_MODE_SILENT;
  10086. update_mode_profile();
  10087. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10088. #endif // TMC2130
  10089. }
  10090. void enable_force_z()
  10091. {
  10092. if(bEnableForce_z)
  10093. return; // motor already enabled (may be ;-p )
  10094. bEnableForce_z=true;
  10095. // mode recovering
  10096. #ifdef TMC2130
  10097. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10098. update_mode_profile();
  10099. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10100. #endif // TMC2130
  10101. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10102. }
  10103. #endif // PSU_Delta