Marlin_main.cpp 352 KB

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