Marlin_main.cpp 351 KB

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