Marlin_main.cpp 392 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834
  1. /* -*- c++ -*- */
  2. /**
  3. * @file
  4. */
  5. /**
  6. * @mainpage Reprap 3D printer firmware based on Sprinter and grbl.
  7. *
  8. * @section intro_sec Introduction
  9. *
  10. * This firmware is a mashup between Sprinter and grbl.
  11. * https://github.com/kliment/Sprinter
  12. * https://github.com/simen/grbl/tree
  13. *
  14. * It has preliminary support for Matthew Roberts advance algorithm
  15. * http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  16. *
  17. * Prusa Research s.r.o. https://www.prusa3d.cz
  18. *
  19. * @section copyright_sec Copyright
  20. *
  21. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  22. *
  23. * This program is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation, either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  35. *
  36. * @section notes_sec Notes
  37. *
  38. * * Do not create static objects in global functions.
  39. * Otherwise constructor guard against concurrent calls is generated costing
  40. * about 8B RAM and 14B flash.
  41. *
  42. *
  43. */
  44. //-//
  45. #include "Configuration.h"
  46. #include "Marlin.h"
  47. #include "config.h"
  48. #include "macros.h"
  49. #ifdef ENABLE_AUTO_BED_LEVELING
  50. #include "vector_3.h"
  51. #ifdef AUTO_BED_LEVELING_GRID
  52. #include "qr_solve.h"
  53. #endif
  54. #endif // ENABLE_AUTO_BED_LEVELING
  55. #ifdef MESH_BED_LEVELING
  56. #include "mesh_bed_leveling.h"
  57. #include "mesh_bed_calibration.h"
  58. #endif
  59. #include "printers.h"
  60. #include "menu.h"
  61. #include "ultralcd.h"
  62. #include "backlight.h"
  63. #include "planner.h"
  64. #include "stepper.h"
  65. #include "temperature.h"
  66. #include "motion_control.h"
  67. #include "cardreader.h"
  68. #include "ConfigurationStore.h"
  69. #include "language.h"
  70. #include "pins_arduino.h"
  71. #include "math.h"
  72. #include "util.h"
  73. #include "Timer.h"
  74. #include <avr/wdt.h>
  75. #include <avr/pgmspace.h>
  76. #include "Dcodes.h"
  77. #include "AutoDeplete.h"
  78. #ifndef LA_NOCOMPAT
  79. #include "la10compat.h"
  80. #endif
  81. #ifdef SWSPI
  82. #include "swspi.h"
  83. #endif //SWSPI
  84. #include "spi.h"
  85. #ifdef SWI2C
  86. #include "swi2c.h"
  87. #endif //SWI2C
  88. #ifdef FILAMENT_SENSOR
  89. #include "fsensor.h"
  90. #endif //FILAMENT_SENSOR
  91. #ifdef TMC2130
  92. #include "tmc2130.h"
  93. #endif //TMC2130
  94. #ifdef W25X20CL
  95. #include "w25x20cl.h"
  96. #include "optiboot_w25x20cl.h"
  97. #endif //W25X20CL
  98. #ifdef BLINKM
  99. #include "BlinkM.h"
  100. #include "Wire.h"
  101. #endif
  102. #ifdef ULTRALCD
  103. #include "ultralcd.h"
  104. #endif
  105. #if NUM_SERVOS > 0
  106. #include "Servo.h"
  107. #endif
  108. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  109. #include <SPI.h>
  110. #endif
  111. #include "mmu.h"
  112. #define VERSION_STRING "1.0.2"
  113. #include "ultralcd.h"
  114. #include "sound.h"
  115. #include "cmdqueue.h"
  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. //Although this flag and many others like this could be represented with a struct/bitfield for each axis (more readable and efficient code), the implementation
  142. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  143. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  144. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  145. uint8_t axis_relative_modes = 0;
  146. int feedmultiply=100; //100->1 200->2
  147. int extrudemultiply=100; //100->1 200->2
  148. int extruder_multiply[EXTRUDERS] = {100
  149. #if EXTRUDERS > 1
  150. , 100
  151. #if EXTRUDERS > 2
  152. , 100
  153. #endif
  154. #endif
  155. };
  156. int bowden_length[4] = {385, 385, 385, 385};
  157. bool is_usb_printing = false;
  158. bool homing_flag = false;
  159. unsigned long kicktime = _millis()+100000;
  160. unsigned int usb_printing_counter;
  161. int8_t lcd_change_fil_state = 0;
  162. unsigned long pause_time = 0;
  163. unsigned long start_pause_print = _millis();
  164. unsigned long t_fan_rising_edge = _millis();
  165. LongTimer safetyTimer;
  166. static LongTimer crashDetTimer;
  167. //unsigned long load_filament_time;
  168. bool mesh_bed_leveling_flag = false;
  169. bool mesh_bed_run_from_menu = false;
  170. bool prusa_sd_card_upload = false;
  171. unsigned int status_number = 0;
  172. unsigned long total_filament_used;
  173. unsigned int heating_status;
  174. unsigned int heating_status_counter;
  175. bool loading_flag = false;
  176. char snmm_filaments_used = 0;
  177. bool fan_state[2];
  178. int fan_edge_counter[2];
  179. int fan_speed[2];
  180. char dir_names[3][9];
  181. bool sortAlpha = false;
  182. float extruder_multiplier[EXTRUDERS] = {1.0
  183. #if EXTRUDERS > 1
  184. , 1.0
  185. #if EXTRUDERS > 2
  186. , 1.0
  187. #endif
  188. #endif
  189. };
  190. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  191. //shortcuts for more readable code
  192. #define _x current_position[X_AXIS]
  193. #define _y current_position[Y_AXIS]
  194. #define _z current_position[Z_AXIS]
  195. #define _e current_position[E_AXIS]
  196. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  197. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  198. bool axis_known_position[3] = {false, false, false};
  199. // Extruder offset
  200. #if EXTRUDERS > 1
  201. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  202. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  203. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  204. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  205. #endif
  206. };
  207. #endif
  208. uint8_t active_extruder = 0;
  209. int fanSpeed=0;
  210. #ifdef FWRETRACT
  211. bool retracted[EXTRUDERS]={false
  212. #if EXTRUDERS > 1
  213. , false
  214. #if EXTRUDERS > 2
  215. , false
  216. #endif
  217. #endif
  218. };
  219. bool retracted_swap[EXTRUDERS]={false
  220. #if EXTRUDERS > 1
  221. , false
  222. #if EXTRUDERS > 2
  223. , false
  224. #endif
  225. #endif
  226. };
  227. float retract_length_swap = RETRACT_LENGTH_SWAP;
  228. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  229. #endif
  230. #ifdef PS_DEFAULT_OFF
  231. bool powersupply = false;
  232. #else
  233. bool powersupply = true;
  234. #endif
  235. bool cancel_heatup = false ;
  236. int8_t busy_state = NOT_BUSY;
  237. static long prev_busy_signal_ms = -1;
  238. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  239. const char errormagic[] PROGMEM = "Error:";
  240. const char echomagic[] PROGMEM = "echo:";
  241. bool no_response = false;
  242. uint8_t important_status;
  243. uint8_t saved_filament_type;
  244. #define SAVED_TARGET_UNSET (X_MIN_POS-1)
  245. float saved_target[NUM_AXIS] = {SAVED_TARGET_UNSET, 0, 0, 0};
  246. // save/restore printing in case that mmu was not responding
  247. bool mmu_print_saved = false;
  248. // storing estimated time to end of print counted by slicer
  249. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  250. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  251. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  252. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  253. //===========================================================================
  254. //=============================Private Variables=============================
  255. //===========================================================================
  256. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  257. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  258. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  259. // For tracing an arc
  260. static float offset[3] = {0.0, 0.0, 0.0};
  261. // Current feedrate
  262. float feedrate = 1500.0;
  263. // Feedrate for the next move
  264. static float next_feedrate;
  265. // Original feedrate saved during homing moves
  266. static float saved_feedrate;
  267. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  268. //static float tt = 0;
  269. //static float bt = 0;
  270. //Inactivity shutdown variables
  271. static unsigned long previous_millis_cmd = 0;
  272. unsigned long max_inactive_time = 0;
  273. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  274. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  275. unsigned long starttime=0;
  276. unsigned long stoptime=0;
  277. unsigned long _usb_timer = 0;
  278. bool Stopped=false;
  279. #if NUM_SERVOS > 0
  280. Servo servos[NUM_SERVOS];
  281. #endif
  282. bool target_direction;
  283. //Insert variables if CHDK is defined
  284. #ifdef CHDK
  285. unsigned long chdkHigh = 0;
  286. boolean chdkActive = false;
  287. #endif
  288. //! @name RAM save/restore printing
  289. //! @{
  290. bool saved_printing = false; //!< Print is paused and saved in RAM
  291. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  292. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  293. static float saved_pos[4] = { 0, 0, 0, 0 };
  294. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  295. static int saved_feedmultiply2 = 0;
  296. static uint8_t saved_active_extruder = 0;
  297. static float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  298. static bool saved_extruder_relative_mode = false;
  299. static int saved_fanSpeed = 0; //!< Print fan speed
  300. //! @}
  301. static int saved_feedmultiply_mm = 100;
  302. #ifdef AUTO_REPORT_TEMPERATURES
  303. static LongTimer auto_report_temp_timer;
  304. static uint8_t auto_report_temp_period = 0;
  305. #endif //AUTO_REPORT_TEMPERATURES
  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 gcode_M105(uint8_t extruder);
  315. static void temp_compensation_start();
  316. static void temp_compensation_apply();
  317. static bool get_PRUSA_SN(char* SN);
  318. uint16_t gcode_in_progress = 0;
  319. uint16_t mcode_in_progress = 0;
  320. void serial_echopair_P(const char *s_P, float v)
  321. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  322. void serial_echopair_P(const char *s_P, double v)
  323. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  324. void serial_echopair_P(const char *s_P, unsigned long v)
  325. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  326. /*FORCE_INLINE*/ void serialprintPGM(const char *str)
  327. {
  328. #if 0
  329. char ch=pgm_read_byte(str);
  330. while(ch)
  331. {
  332. MYSERIAL.write(ch);
  333. ch=pgm_read_byte(++str);
  334. }
  335. #else
  336. // hmm, same size as the above version, the compiler did a good job optimizing the above
  337. while( uint8_t ch = pgm_read_byte(str) ){
  338. MYSERIAL.write((char)ch);
  339. ++str;
  340. }
  341. #endif
  342. }
  343. #ifdef SDSUPPORT
  344. #include "SdFatUtil.h"
  345. int freeMemory() { return SdFatUtil::FreeRam(); }
  346. #else
  347. extern "C" {
  348. extern unsigned int __bss_end;
  349. extern unsigned int __heap_start;
  350. extern void *__brkval;
  351. int freeMemory() {
  352. int free_memory;
  353. if ((int)__brkval == 0)
  354. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  355. else
  356. free_memory = ((int)&free_memory) - ((int)__brkval);
  357. return free_memory;
  358. }
  359. }
  360. #endif //!SDSUPPORT
  361. void setup_killpin()
  362. {
  363. #if defined(KILL_PIN) && KILL_PIN > -1
  364. SET_INPUT(KILL_PIN);
  365. WRITE(KILL_PIN,HIGH);
  366. #endif
  367. }
  368. // Set home pin
  369. void setup_homepin(void)
  370. {
  371. #if defined(HOME_PIN) && HOME_PIN > -1
  372. SET_INPUT(HOME_PIN);
  373. WRITE(HOME_PIN,HIGH);
  374. #endif
  375. }
  376. void setup_photpin()
  377. {
  378. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  379. SET_OUTPUT(PHOTOGRAPH_PIN);
  380. WRITE(PHOTOGRAPH_PIN, LOW);
  381. #endif
  382. }
  383. void setup_powerhold()
  384. {
  385. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  386. SET_OUTPUT(SUICIDE_PIN);
  387. WRITE(SUICIDE_PIN, HIGH);
  388. #endif
  389. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  390. SET_OUTPUT(PS_ON_PIN);
  391. #if defined(PS_DEFAULT_OFF)
  392. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  393. #else
  394. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  395. #endif
  396. #endif
  397. }
  398. void suicide()
  399. {
  400. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  401. SET_OUTPUT(SUICIDE_PIN);
  402. WRITE(SUICIDE_PIN, LOW);
  403. #endif
  404. }
  405. void servo_init()
  406. {
  407. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  408. servos[0].attach(SERVO0_PIN);
  409. #endif
  410. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  411. servos[1].attach(SERVO1_PIN);
  412. #endif
  413. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  414. servos[2].attach(SERVO2_PIN);
  415. #endif
  416. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  417. servos[3].attach(SERVO3_PIN);
  418. #endif
  419. #if (NUM_SERVOS >= 5)
  420. #error "TODO: enter initalisation code for more servos"
  421. #endif
  422. }
  423. bool fans_check_enabled = true;
  424. #ifdef TMC2130
  425. void crashdet_stop_and_save_print()
  426. {
  427. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  428. }
  429. void crashdet_restore_print_and_continue()
  430. {
  431. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  432. // babystep_apply();
  433. }
  434. void crashdet_stop_and_save_print2()
  435. {
  436. cli();
  437. planner_abort_hard(); //abort printing
  438. cmdqueue_reset(); //empty cmdqueue
  439. card.sdprinting = false;
  440. card.closefile();
  441. // Reset and re-enable the stepper timer just before the global interrupts are enabled.
  442. st_reset_timer();
  443. sei();
  444. }
  445. void crashdet_detected(uint8_t mask)
  446. {
  447. st_synchronize();
  448. static uint8_t crashDet_counter = 0;
  449. bool automatic_recovery_after_crash = true;
  450. if (crashDet_counter++ == 0) {
  451. crashDetTimer.start();
  452. }
  453. else if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)){
  454. crashDetTimer.stop();
  455. crashDet_counter = 0;
  456. }
  457. else if(crashDet_counter == CRASHDET_COUNTER_MAX){
  458. automatic_recovery_after_crash = false;
  459. crashDetTimer.stop();
  460. crashDet_counter = 0;
  461. }
  462. else {
  463. crashDetTimer.start();
  464. }
  465. lcd_update_enable(true);
  466. lcd_clear();
  467. lcd_update(2);
  468. if (mask & X_AXIS_MASK)
  469. {
  470. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  471. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  472. }
  473. if (mask & Y_AXIS_MASK)
  474. {
  475. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  476. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  477. }
  478. lcd_update_enable(true);
  479. lcd_update(2);
  480. lcd_setstatuspgm(_T(MSG_CRASH_DETECTED));
  481. gcode_G28(true, true, false); //home X and Y
  482. st_synchronize();
  483. if (automatic_recovery_after_crash) {
  484. enquecommand_P(PSTR("CRASH_RECOVER"));
  485. }else{
  486. setTargetHotend(0, active_extruder);
  487. bool yesno = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Crash detected. Resume print?"), false);
  488. lcd_update_enable(true);
  489. if (yesno)
  490. {
  491. enquecommand_P(PSTR("CRASH_RECOVER"));
  492. }
  493. else
  494. {
  495. enquecommand_P(PSTR("CRASH_CANCEL"));
  496. }
  497. }
  498. }
  499. void crashdet_recover()
  500. {
  501. crashdet_restore_print_and_continue();
  502. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  503. }
  504. void crashdet_cancel()
  505. {
  506. saved_printing = false;
  507. tmc2130_sg_stop_on_crash = true;
  508. if (saved_printing_type == PRINTING_TYPE_SD) {
  509. lcd_print_stop();
  510. }else if(saved_printing_type == PRINTING_TYPE_USB){
  511. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  512. cmdqueue_reset();
  513. }
  514. }
  515. #endif //TMC2130
  516. void failstats_reset_print()
  517. {
  518. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  519. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  520. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  521. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  522. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  523. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  524. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  525. fsensor_softfail = 0;
  526. #endif
  527. }
  528. void softReset()
  529. {
  530. cli();
  531. wdt_enable(WDTO_15MS);
  532. while(1);
  533. }
  534. #ifdef MESH_BED_LEVELING
  535. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  536. #endif
  537. // Factory reset function
  538. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  539. // Level input parameter sets depth of reset
  540. int er_progress = 0;
  541. static void factory_reset(char level)
  542. {
  543. lcd_clear();
  544. switch (level) {
  545. // Level 0: Language reset
  546. case 0:
  547. Sound_MakeCustom(100,0,false);
  548. lang_reset();
  549. break;
  550. //Level 1: Reset statistics
  551. case 1:
  552. Sound_MakeCustom(100,0,false);
  553. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  554. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  555. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  556. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  557. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  558. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  559. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  560. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  561. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  562. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  563. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  564. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  565. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  566. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  567. lcd_menu_statistics();
  568. break;
  569. // Level 2: Prepare for shipping
  570. case 2:
  571. //lcd_puts_P(PSTR("Factory RESET"));
  572. //lcd_puts_at_P(1,2,PSTR("Shipping prep"));
  573. // Force language selection at the next boot up.
  574. lang_reset();
  575. // Force the "Follow calibration flow" message at the next boot up.
  576. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  577. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  578. farm_no = 0;
  579. farm_mode = false;
  580. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  581. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  582. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  583. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  584. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  585. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  586. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  587. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  588. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  589. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  590. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  591. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  592. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  593. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  594. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  595. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  596. #ifdef FILAMENT_SENSOR
  597. fsensor_enable();
  598. fsensor_autoload_set(true);
  599. #endif //FILAMENT_SENSOR
  600. Sound_MakeCustom(100,0,false);
  601. //_delay_ms(2000);
  602. break;
  603. // Level 3: erase everything, whole EEPROM will be set to 0xFF
  604. case 3:
  605. lcd_puts_P(PSTR("Factory RESET"));
  606. lcd_puts_at_P(1, 2, PSTR("ERASING all data"));
  607. Sound_MakeCustom(100,0,false);
  608. er_progress = 0;
  609. lcd_puts_at_P(3, 3, PSTR(" "));
  610. lcd_set_cursor(3, 3);
  611. lcd_print(er_progress);
  612. // Erase EEPROM
  613. for (int i = 0; i < 4096; i++) {
  614. eeprom_update_byte((uint8_t*)i, 0xFF);
  615. if (i % 41 == 0) {
  616. er_progress++;
  617. lcd_puts_at_P(3, 3, PSTR(" "));
  618. lcd_set_cursor(3, 3);
  619. lcd_print(er_progress);
  620. lcd_puts_P(PSTR("%"));
  621. }
  622. }
  623. softReset();
  624. break;
  625. case 4:
  626. bowden_menu();
  627. break;
  628. default:
  629. break;
  630. }
  631. }
  632. extern "C" {
  633. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  634. }
  635. int uart_putchar(char c, FILE *)
  636. {
  637. MYSERIAL.write(c);
  638. return 0;
  639. }
  640. void lcd_splash()
  641. {
  642. lcd_clear(); // clears display and homes screen
  643. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  644. }
  645. void factory_reset()
  646. {
  647. KEEPALIVE_STATE(PAUSED_FOR_USER);
  648. if (!READ(BTN_ENC))
  649. {
  650. _delay_ms(1000);
  651. if (!READ(BTN_ENC))
  652. {
  653. lcd_clear();
  654. lcd_puts_P(PSTR("Factory RESET"));
  655. SET_OUTPUT(BEEPER);
  656. if(eSoundMode!=e_SOUND_MODE_SILENT)
  657. WRITE(BEEPER, HIGH);
  658. while (!READ(BTN_ENC));
  659. WRITE(BEEPER, LOW);
  660. _delay_ms(2000);
  661. char level = reset_menu();
  662. factory_reset(level);
  663. switch (level) {
  664. case 0: _delay_ms(0); break;
  665. case 1: _delay_ms(0); break;
  666. case 2: _delay_ms(0); break;
  667. case 3: _delay_ms(0); break;
  668. }
  669. }
  670. }
  671. KEEPALIVE_STATE(IN_HANDLER);
  672. }
  673. void show_fw_version_warnings() {
  674. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  675. switch (FW_DEV_VERSION) {
  676. 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
  677. 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
  678. case(FW_VERSION_DEVEL):
  679. case(FW_VERSION_DEBUG):
  680. lcd_update_enable(false);
  681. lcd_clear();
  682. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  683. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  684. #else
  685. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  686. #endif
  687. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  688. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  689. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  690. lcd_wait_for_click();
  691. break;
  692. // 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
  693. }
  694. lcd_update_enable(true);
  695. }
  696. //! @brief try to check if firmware is on right type of printer
  697. static void check_if_fw_is_on_right_printer(){
  698. #ifdef FILAMENT_SENSOR
  699. if((PRINTER_TYPE == PRINTER_MK3) || (PRINTER_TYPE == PRINTER_MK3S)){
  700. #ifdef IR_SENSOR
  701. swi2c_init();
  702. const uint8_t pat9125_detected = swi2c_readByte_A8(PAT9125_I2C_ADDR,0x00,NULL);
  703. if (pat9125_detected){
  704. lcd_show_fullscreen_message_and_wait_P(_i("MK3S firmware detected on MK3 printer"));}////c=20 r=3
  705. #endif //IR_SENSOR
  706. #ifdef PAT9125
  707. //will return 1 only if IR can detect filament in bondtech extruder so this may fail even when we have IR sensor
  708. const uint8_t ir_detected = !READ(IR_SENSOR_PIN);
  709. if (ir_detected){
  710. lcd_show_fullscreen_message_and_wait_P(_i("MK3 firmware detected on MK3S printer"));}////c=20 r=3
  711. #endif //PAT9125
  712. }
  713. #endif //FILAMENT_SENSOR
  714. }
  715. uint8_t check_printer_version()
  716. {
  717. uint8_t version_changed = 0;
  718. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  719. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  720. if (printer_type != PRINTER_TYPE) {
  721. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  722. else version_changed |= 0b10;
  723. }
  724. if (motherboard != MOTHERBOARD) {
  725. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  726. else version_changed |= 0b01;
  727. }
  728. return version_changed;
  729. }
  730. #ifdef BOOTAPP
  731. #include "bootapp.h" //bootloader support
  732. #endif //BOOTAPP
  733. #if (LANG_MODE != 0) //secondary language support
  734. #ifdef W25X20CL
  735. // language update from external flash
  736. #define LANGBOOT_BLOCKSIZE 0x1000u
  737. #define LANGBOOT_RAMBUFFER 0x0800
  738. void update_sec_lang_from_external_flash()
  739. {
  740. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  741. {
  742. uint8_t lang = boot_reserved >> 4;
  743. uint8_t state = boot_reserved & 0xf;
  744. lang_table_header_t header;
  745. uint32_t src_addr;
  746. if (lang_get_header(lang, &header, &src_addr))
  747. {
  748. lcd_puts_at_P(1,3,PSTR("Language update."));
  749. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  750. _delay(100);
  751. boot_reserved = (state + 1) | (lang << 4);
  752. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  753. {
  754. cli();
  755. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  756. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  757. w25x20cl_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  758. if (state == 0)
  759. {
  760. //TODO - check header integrity
  761. }
  762. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  763. }
  764. else
  765. {
  766. //TODO - check sec lang data integrity
  767. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  768. }
  769. }
  770. }
  771. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  772. }
  773. #ifdef DEBUG_W25X20CL
  774. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  775. {
  776. lang_table_header_t header;
  777. uint8_t count = 0;
  778. uint32_t addr = 0x00000;
  779. while (1)
  780. {
  781. printf_P(_n("LANGTABLE%d:"), count);
  782. w25x20cl_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  783. if (header.magic != LANG_MAGIC)
  784. {
  785. printf_P(_n("NG!\n"));
  786. break;
  787. }
  788. printf_P(_n("OK\n"));
  789. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  790. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  791. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  792. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  793. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  794. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  795. addr += header.size;
  796. codes[count] = header.code;
  797. count ++;
  798. }
  799. return count;
  800. }
  801. void list_sec_lang_from_external_flash()
  802. {
  803. uint16_t codes[8];
  804. uint8_t count = lang_xflash_enum_codes(codes);
  805. printf_P(_n("XFlash lang count = %hhd\n"), count);
  806. }
  807. #endif //DEBUG_W25X20CL
  808. #endif //W25X20CL
  809. #endif //(LANG_MODE != 0)
  810. static void w25x20cl_err_msg()
  811. {
  812. lcd_clear();
  813. lcd_puts_P(_n("External SPI flash\nW25X20CL is not res-\nponding. Language\nswitch unavailable."));
  814. }
  815. // "Setup" function is called by the Arduino framework on startup.
  816. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  817. // are initialized by the main() routine provided by the Arduino framework.
  818. void setup()
  819. {
  820. mmu_init();
  821. ultralcd_init();
  822. spi_init();
  823. lcd_splash();
  824. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  825. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  826. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  827. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  828. MYSERIAL.begin(BAUDRATE);
  829. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  830. stdout = uartout;
  831. #ifdef W25X20CL
  832. bool w25x20cl_success = w25x20cl_init();
  833. uint8_t optiboot_status = 1;
  834. if (w25x20cl_success)
  835. {
  836. optiboot_status = optiboot_w25x20cl_enter();
  837. #if (LANG_MODE != 0) //secondary language support
  838. update_sec_lang_from_external_flash();
  839. #endif //(LANG_MODE != 0)
  840. }
  841. else
  842. {
  843. w25x20cl_err_msg();
  844. }
  845. #else
  846. const bool w25x20cl_success = true;
  847. #endif //W25X20CL
  848. setup_killpin();
  849. setup_powerhold();
  850. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  851. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  852. if ((farm_mode == 0xFF && farm_no == 0) || ((uint16_t)farm_no == 0xFFFF))
  853. 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
  854. if ((uint16_t)farm_no == 0xFFFF) farm_no = 0;
  855. if (farm_mode)
  856. {
  857. no_response = true; //we need confirmation by recieving PRUSA thx
  858. important_status = 8;
  859. prusa_statistics(8);
  860. selectedSerialPort = 1;
  861. MYSERIAL.begin(BAUDRATE);
  862. #ifdef TMC2130
  863. //increased extruder current (PFW363)
  864. tmc2130_current_h[E_AXIS] = 36;
  865. tmc2130_current_r[E_AXIS] = 36;
  866. #endif //TMC2130
  867. #ifdef FILAMENT_SENSOR
  868. //disabled filament autoload (PFW360)
  869. fsensor_autoload_set(false);
  870. #endif //FILAMENT_SENSOR
  871. // ~ FanCheck -> on
  872. if(!(eeprom_read_byte((uint8_t*)EEPROM_FAN_CHECK_ENABLED)))
  873. eeprom_update_byte((unsigned char *)EEPROM_FAN_CHECK_ENABLED,true);
  874. }
  875. //saved EEPROM SN is not valid. Try to retrieve it.
  876. //SN is valid only if it is NULL terminated. Any other character means either uninitialized or corrupted
  877. if (eeprom_read_byte((uint8_t*)EEPROM_PRUSA_SN + 19))
  878. {
  879. char SN[20];
  880. if (get_PRUSA_SN(SN))
  881. {
  882. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  883. puts_P(PSTR("SN updated"));
  884. }
  885. else
  886. puts_P(PSTR("SN update failed"));
  887. }
  888. #ifndef W25X20CL
  889. SERIAL_PROTOCOLLNPGM("start");
  890. #else
  891. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  892. SERIAL_PROTOCOLLNPGM("start");
  893. #endif
  894. SERIAL_ECHO_START;
  895. printf_P(PSTR(" " FW_VERSION_FULL "\n"));
  896. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  897. #ifdef DEBUG_SEC_LANG
  898. lang_table_header_t header;
  899. uint32_t src_addr = 0x00000;
  900. if (lang_get_header(1, &header, &src_addr))
  901. {
  902. //this is comparsion of some printing-methods regarding to flash space usage and code size/readability
  903. #define LT_PRINT_TEST 2
  904. // flash usage
  905. // total p.test
  906. //0 252718 t+c text code
  907. //1 253142 424 170 254
  908. //2 253040 322 164 158
  909. //3 253248 530 135 395
  910. #if (LT_PRINT_TEST==1) //not optimized printf
  911. printf_P(_n(" _src_addr = 0x%08lx\n"), src_addr);
  912. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  913. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  914. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  915. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  916. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  917. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  918. #elif (LT_PRINT_TEST==2) //optimized printf
  919. printf_P(
  920. _n(
  921. " _src_addr = 0x%08lx\n"
  922. " _lt_magic = 0x%08lx %S\n"
  923. " _lt_size = 0x%04x (%d)\n"
  924. " _lt_count = 0x%04x (%d)\n"
  925. " _lt_chsum = 0x%04x\n"
  926. " _lt_code = 0x%04x (%c%c)\n"
  927. " _lt_resv1 = 0x%08lx\n"
  928. ),
  929. src_addr,
  930. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  931. header.size, header.size,
  932. header.count, header.count,
  933. header.checksum,
  934. header.code, header.code >> 8, header.code & 0xff,
  935. header.signature
  936. );
  937. #elif (LT_PRINT_TEST==3) //arduino print/println (leading zeros not solved)
  938. MYSERIAL.print(" _src_addr = 0x");
  939. MYSERIAL.println(src_addr, 16);
  940. MYSERIAL.print(" _lt_magic = 0x");
  941. MYSERIAL.print(header.magic, 16);
  942. MYSERIAL.println((header.magic==LANG_MAGIC)?" OK":" NA");
  943. MYSERIAL.print(" _lt_size = 0x");
  944. MYSERIAL.print(header.size, 16);
  945. MYSERIAL.print(" (");
  946. MYSERIAL.print(header.size, 10);
  947. MYSERIAL.println(")");
  948. MYSERIAL.print(" _lt_count = 0x");
  949. MYSERIAL.print(header.count, 16);
  950. MYSERIAL.print(" (");
  951. MYSERIAL.print(header.count, 10);
  952. MYSERIAL.println(")");
  953. MYSERIAL.print(" _lt_chsum = 0x");
  954. MYSERIAL.println(header.checksum, 16);
  955. MYSERIAL.print(" _lt_code = 0x");
  956. MYSERIAL.print(header.code, 16);
  957. MYSERIAL.print(" (");
  958. MYSERIAL.print((char)(header.code >> 8), 0);
  959. MYSERIAL.print((char)(header.code & 0xff), 0);
  960. MYSERIAL.println(")");
  961. MYSERIAL.print(" _lt_resv1 = 0x");
  962. MYSERIAL.println(header.signature, 16);
  963. #endif //(LT_PRINT_TEST==)
  964. #undef LT_PRINT_TEST
  965. #if 0
  966. w25x20cl_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  967. for (uint16_t i = 0; i < 1024; i++)
  968. {
  969. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  970. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  971. if ((i % 16) == 15) putchar('\n');
  972. }
  973. #endif
  974. uint16_t sum = 0;
  975. for (uint16_t i = 0; i < header.size; i++)
  976. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  977. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  978. sum -= header.checksum; //subtract checksum
  979. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  980. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  981. if (sum == header.checksum)
  982. printf_P(_n("Checksum OK\n"), sum);
  983. else
  984. printf_P(_n("Checksum NG\n"), sum);
  985. }
  986. else
  987. printf_P(_n("lang_get_header failed!\n"));
  988. #if 0
  989. for (uint16_t i = 0; i < 1024*10; i++)
  990. {
  991. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  992. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  993. if ((i % 16) == 15) putchar('\n');
  994. }
  995. #endif
  996. #if 0
  997. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  998. for (int i = 0; i < 4096; ++i) {
  999. int b = eeprom_read_byte((unsigned char*)i);
  1000. if (b != 255) {
  1001. SERIAL_ECHO(i);
  1002. SERIAL_ECHO(":");
  1003. SERIAL_ECHO(b);
  1004. SERIAL_ECHOLN("");
  1005. }
  1006. }
  1007. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  1008. #endif
  1009. #endif //DEBUG_SEC_LANG
  1010. // Check startup - does nothing if bootloader sets MCUSR to 0
  1011. byte mcu = MCUSR;
  1012. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  1013. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  1014. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  1015. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1016. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1017. if (mcu & 1) puts_P(MSG_POWERUP);
  1018. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1019. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1020. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1021. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1022. MCUSR = 0;
  1023. //SERIAL_ECHORPGM(MSG_MARLIN);
  1024. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1025. #ifdef STRING_VERSION_CONFIG_H
  1026. #ifdef STRING_CONFIG_H_AUTHOR
  1027. SERIAL_ECHO_START;
  1028. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1029. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1030. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1031. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1032. SERIAL_ECHOPGM("Compiled: ");
  1033. SERIAL_ECHOLNPGM(__DATE__);
  1034. #endif
  1035. #endif
  1036. SERIAL_ECHO_START;
  1037. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1038. SERIAL_ECHO(freeMemory());
  1039. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1040. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1041. //lcd_update_enable(false); // why do we need this?? - andre
  1042. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1043. bool previous_settings_retrieved = false;
  1044. uint8_t hw_changed = check_printer_version();
  1045. 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
  1046. previous_settings_retrieved = Config_RetrieveSettings();
  1047. }
  1048. else { //printer version was changed so use default settings
  1049. Config_ResetDefault();
  1050. }
  1051. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  1052. tp_init(); // Initialize temperature loop
  1053. if (w25x20cl_success) lcd_splash(); // we need to do this again, because tp_init() kills lcd
  1054. else
  1055. {
  1056. w25x20cl_err_msg();
  1057. printf_P(_n("W25X20CL not responding.\n"));
  1058. }
  1059. #ifdef EXTRUDER_ALTFAN_DETECT
  1060. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1061. if (extruder_altfan_detect())
  1062. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1063. else
  1064. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1065. #endif //EXTRUDER_ALTFAN_DETECT
  1066. plan_init(); // Initialize planner;
  1067. factory_reset();
  1068. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1069. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1070. {
  1071. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1072. // where all the EEPROM entries are set to 0x0ff.
  1073. // Once a firmware boots up, it forces at least a language selection, which changes
  1074. // EEPROM_LANG to number lower than 0x0ff.
  1075. // 1) Set a high power mode.
  1076. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1077. #ifdef TMC2130
  1078. tmc2130_mode = TMC2130_MODE_NORMAL;
  1079. #endif //TMC2130
  1080. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1081. }
  1082. lcd_encoder_diff=0;
  1083. #ifdef TMC2130
  1084. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1085. if (silentMode == 0xff) silentMode = 0;
  1086. tmc2130_mode = TMC2130_MODE_NORMAL;
  1087. if (lcd_crash_detect_enabled() && !farm_mode)
  1088. {
  1089. lcd_crash_detect_enable();
  1090. puts_P(_N("CrashDetect ENABLED!"));
  1091. }
  1092. else
  1093. {
  1094. lcd_crash_detect_disable();
  1095. puts_P(_N("CrashDetect DISABLED"));
  1096. }
  1097. #ifdef TMC2130_LINEARITY_CORRECTION
  1098. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1099. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1100. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1101. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1102. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1103. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1104. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1105. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1106. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1107. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1108. #endif //TMC2130_LINEARITY_CORRECTION
  1109. #ifdef TMC2130_VARIABLE_RESOLUTION
  1110. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1111. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1112. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1113. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1114. #else //TMC2130_VARIABLE_RESOLUTION
  1115. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1116. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1117. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1118. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1119. #endif //TMC2130_VARIABLE_RESOLUTION
  1120. #endif //TMC2130
  1121. st_init(); // Initialize stepper, this enables interrupts!
  1122. #ifdef TMC2130
  1123. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1124. update_mode_profile();
  1125. tmc2130_init();
  1126. #endif //TMC2130
  1127. #ifdef PSU_Delta
  1128. init_force_z(); // ! important for correct Z-axis initialization
  1129. #endif // PSU_Delta
  1130. setup_photpin();
  1131. servo_init();
  1132. // Reset the machine correction matrix.
  1133. // It does not make sense to load the correction matrix until the machine is homed.
  1134. world2machine_reset();
  1135. // Initialize current_position accounting for software endstops to
  1136. // avoid unexpected initial shifts on the first move
  1137. clamp_to_software_endstops(current_position);
  1138. plan_set_position_curposXYZE();
  1139. #ifdef FILAMENT_SENSOR
  1140. fsensor_init();
  1141. #endif //FILAMENT_SENSOR
  1142. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1143. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1144. #endif
  1145. setup_homepin();
  1146. #if defined(Z_AXIS_ALWAYS_ON)
  1147. enable_z();
  1148. #endif
  1149. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  1150. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  1151. 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
  1152. if (farm_no == static_cast<int>(0xFFFF)) farm_no = 0;
  1153. if (farm_mode)
  1154. {
  1155. prusa_statistics(8);
  1156. }
  1157. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1158. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1159. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1160. // but this times out if a blocking dialog is shown in setup().
  1161. card.initsd();
  1162. #ifdef DEBUG_SD_SPEED_TEST
  1163. if (card.cardOK)
  1164. {
  1165. uint8_t* buff = (uint8_t*)block_buffer;
  1166. uint32_t block = 0;
  1167. uint32_t sumr = 0;
  1168. uint32_t sumw = 0;
  1169. for (int i = 0; i < 1024; i++)
  1170. {
  1171. uint32_t u = _micros();
  1172. bool res = card.card.readBlock(i, buff);
  1173. u = _micros() - u;
  1174. if (res)
  1175. {
  1176. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1177. sumr += u;
  1178. u = _micros();
  1179. res = card.card.writeBlock(i, buff);
  1180. u = _micros() - u;
  1181. if (res)
  1182. {
  1183. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1184. sumw += u;
  1185. }
  1186. else
  1187. {
  1188. printf_P(PSTR("writeBlock %4d error\n"), i);
  1189. break;
  1190. }
  1191. }
  1192. else
  1193. {
  1194. printf_P(PSTR("readBlock %4d error\n"), i);
  1195. break;
  1196. }
  1197. }
  1198. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1199. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1200. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1201. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1202. }
  1203. else
  1204. printf_P(PSTR("Card NG!\n"));
  1205. #endif //DEBUG_SD_SPEED_TEST
  1206. eeprom_init();
  1207. #ifdef SNMM
  1208. if (eeprom_read_dword((uint32_t*)EEPROM_BOWDEN_LENGTH) == 0x0ffffffff) { //bowden length used for SNMM
  1209. int _z = BOWDEN_LENGTH;
  1210. for(int i = 0; i<4; i++) EEPROM_save_B(EEPROM_BOWDEN_LENGTH + i * 2, &_z);
  1211. }
  1212. #endif
  1213. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1214. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1215. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1216. #if (LANG_MODE != 0) //secondary language support
  1217. #ifdef DEBUG_W25X20CL
  1218. W25X20CL_SPI_ENTER();
  1219. uint8_t uid[8]; // 64bit unique id
  1220. w25x20cl_rd_uid(uid);
  1221. puts_P(_n("W25X20CL UID="));
  1222. for (uint8_t i = 0; i < 8; i ++)
  1223. printf_P(PSTR("%02hhx"), uid[i]);
  1224. putchar('\n');
  1225. list_sec_lang_from_external_flash();
  1226. #endif //DEBUG_W25X20CL
  1227. // lang_reset();
  1228. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1229. lcd_language();
  1230. #ifdef DEBUG_SEC_LANG
  1231. uint16_t sec_lang_code = lang_get_code(1);
  1232. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1233. 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);
  1234. lang_print_sec_lang(uartout);
  1235. #endif //DEBUG_SEC_LANG
  1236. #endif //(LANG_MODE != 0)
  1237. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1238. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1239. }
  1240. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1241. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1242. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1243. int16_t z_shift = 0;
  1244. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  1245. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1246. }
  1247. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1248. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1249. }
  1250. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1251. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1252. }
  1253. //mbl_mode_init();
  1254. mbl_settings_init();
  1255. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1256. if (SilentModeMenu_MMU == 255) {
  1257. SilentModeMenu_MMU = 1;
  1258. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1259. }
  1260. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1261. setup_fan_interrupt();
  1262. #endif //DEBUG_DISABLE_FANCHECK
  1263. #ifdef PAT9125
  1264. fsensor_setup_interrupt();
  1265. #endif //PAT9125
  1266. for (int i = 0; i<4; i++) EEPROM_read_B(EEPROM_BOWDEN_LENGTH + i * 2, &bowden_length[i]);
  1267. #ifndef DEBUG_DISABLE_STARTMSGS
  1268. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1269. if (!farm_mode) {
  1270. check_if_fw_is_on_right_printer();
  1271. show_fw_version_warnings();
  1272. }
  1273. switch (hw_changed) {
  1274. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1275. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1276. case(0b01):
  1277. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1278. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1279. break;
  1280. case(0b10):
  1281. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1282. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1283. break;
  1284. case(0b11):
  1285. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1286. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1287. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1288. break;
  1289. default: break; //no change, show no message
  1290. }
  1291. if (!previous_settings_retrieved) {
  1292. 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=5
  1293. Config_StoreSettings();
  1294. }
  1295. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 1) {
  1296. lcd_wizard(WizState::Run);
  1297. }
  1298. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1299. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1300. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1301. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1302. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1303. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1304. // Show the message.
  1305. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1306. }
  1307. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1308. // Show the message.
  1309. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1310. lcd_update_enable(true);
  1311. }
  1312. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1313. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1314. lcd_update_enable(true);
  1315. }
  1316. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1317. // Show the message.
  1318. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1319. }
  1320. }
  1321. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1322. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1323. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1324. update_current_firmware_version_to_eeprom();
  1325. lcd_selftest();
  1326. }
  1327. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1328. KEEPALIVE_STATE(IN_PROCESS);
  1329. #endif //DEBUG_DISABLE_STARTMSGS
  1330. lcd_update_enable(true);
  1331. lcd_clear();
  1332. lcd_update(2);
  1333. // Store the currently running firmware into an eeprom,
  1334. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1335. update_current_firmware_version_to_eeprom();
  1336. #ifdef TMC2130
  1337. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1338. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1339. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1340. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1341. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1342. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1343. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1344. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1345. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1346. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1347. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1348. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1349. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1350. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1351. #endif //TMC2130
  1352. #ifdef UVLO_SUPPORT
  1353. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1354. /*
  1355. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1356. else {
  1357. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1358. lcd_update_enable(true);
  1359. lcd_update(2);
  1360. lcd_setstatuspgm(_T(WELCOME_MSG));
  1361. }
  1362. */
  1363. manage_heater(); // Update temperatures
  1364. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1365. 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));
  1366. #endif
  1367. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1368. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1369. puts_P(_N("Automatic recovery!"));
  1370. #endif
  1371. recover_print(1);
  1372. }
  1373. else{
  1374. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1375. puts_P(_N("Normal recovery!"));
  1376. #endif
  1377. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1378. else {
  1379. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1380. lcd_update_enable(true);
  1381. lcd_update(2);
  1382. lcd_setstatuspgm(_T(WELCOME_MSG));
  1383. }
  1384. }
  1385. }
  1386. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1387. // the entire state machine initialized.
  1388. setup_uvlo_interrupt();
  1389. #endif //UVLO_SUPPORT
  1390. fCheckModeInit();
  1391. fSetMmuMode(mmu_enabled);
  1392. KEEPALIVE_STATE(NOT_BUSY);
  1393. #ifdef WATCHDOG
  1394. wdt_enable(WDTO_4S);
  1395. #endif //WATCHDOG
  1396. }
  1397. void trace();
  1398. #define CHUNK_SIZE 64 // bytes
  1399. #define SAFETY_MARGIN 1
  1400. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  1401. int chunkHead = 0;
  1402. void serial_read_stream() {
  1403. setAllTargetHotends(0);
  1404. setTargetBed(0);
  1405. lcd_clear();
  1406. lcd_puts_P(PSTR(" Upload in progress"));
  1407. // first wait for how many bytes we will receive
  1408. uint32_t bytesToReceive;
  1409. // receive the four bytes
  1410. char bytesToReceiveBuffer[4];
  1411. for (int i=0; i<4; i++) {
  1412. int data;
  1413. while ((data = MYSERIAL.read()) == -1) {};
  1414. bytesToReceiveBuffer[i] = data;
  1415. }
  1416. // make it a uint32
  1417. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  1418. // we're ready, notify the sender
  1419. MYSERIAL.write('+');
  1420. // lock in the routine
  1421. uint32_t receivedBytes = 0;
  1422. while (prusa_sd_card_upload) {
  1423. int i;
  1424. for (i=0; i<CHUNK_SIZE; i++) {
  1425. int data;
  1426. // check if we're not done
  1427. if (receivedBytes == bytesToReceive) {
  1428. break;
  1429. }
  1430. // read the next byte
  1431. while ((data = MYSERIAL.read()) == -1) {};
  1432. receivedBytes++;
  1433. // save it to the chunk
  1434. chunk[i] = data;
  1435. }
  1436. // write the chunk to SD
  1437. card.write_command_no_newline(&chunk[0]);
  1438. // notify the sender we're ready for more data
  1439. MYSERIAL.write('+');
  1440. // for safety
  1441. manage_heater();
  1442. // check if we're done
  1443. if(receivedBytes == bytesToReceive) {
  1444. trace(); // beep
  1445. card.closefile();
  1446. prusa_sd_card_upload = false;
  1447. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1448. }
  1449. }
  1450. }
  1451. /**
  1452. * Output a "busy" message at regular intervals
  1453. * while the machine is not accepting commands.
  1454. */
  1455. void host_keepalive() {
  1456. #ifndef HOST_KEEPALIVE_FEATURE
  1457. return;
  1458. #endif //HOST_KEEPALIVE_FEATURE
  1459. if (farm_mode) return;
  1460. long ms = _millis();
  1461. #ifdef AUTO_REPORT_TEMPERATURES
  1462. if (auto_report_temp_timer.running())
  1463. {
  1464. if (auto_report_temp_timer.expired(auto_report_temp_period * 1000ul))
  1465. {
  1466. gcode_M105(active_extruder);
  1467. auto_report_temp_timer.start();
  1468. }
  1469. }
  1470. #endif //AUTO_REPORT_TEMPERATURES
  1471. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1472. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1473. switch (busy_state) {
  1474. case IN_HANDLER:
  1475. case IN_PROCESS:
  1476. SERIAL_ECHO_START;
  1477. SERIAL_ECHOLNPGM("busy: processing");
  1478. break;
  1479. case PAUSED_FOR_USER:
  1480. SERIAL_ECHO_START;
  1481. SERIAL_ECHOLNPGM("busy: paused for user");
  1482. break;
  1483. case PAUSED_FOR_INPUT:
  1484. SERIAL_ECHO_START;
  1485. SERIAL_ECHOLNPGM("busy: paused for input");
  1486. break;
  1487. default:
  1488. break;
  1489. }
  1490. }
  1491. prev_busy_signal_ms = ms;
  1492. }
  1493. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1494. // Before loop(), the setup() function is called by the main() routine.
  1495. void loop()
  1496. {
  1497. KEEPALIVE_STATE(NOT_BUSY);
  1498. if ((usb_printing_counter > 0) && ((_millis()-_usb_timer) > 1000))
  1499. {
  1500. is_usb_printing = true;
  1501. usb_printing_counter--;
  1502. _usb_timer = _millis();
  1503. }
  1504. if (usb_printing_counter == 0)
  1505. {
  1506. is_usb_printing = false;
  1507. }
  1508. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1509. {
  1510. is_usb_printing = true;
  1511. }
  1512. #ifdef FANCHECK
  1513. if (fan_check_error && isPrintPaused)
  1514. {
  1515. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1516. 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.
  1517. }
  1518. #endif
  1519. if (prusa_sd_card_upload)
  1520. {
  1521. //we read byte-by byte
  1522. serial_read_stream();
  1523. }
  1524. else
  1525. {
  1526. get_command();
  1527. #ifdef SDSUPPORT
  1528. card.checkautostart(false);
  1529. #endif
  1530. if(buflen)
  1531. {
  1532. cmdbuffer_front_already_processed = false;
  1533. #ifdef SDSUPPORT
  1534. if(card.saving)
  1535. {
  1536. // Saving a G-code file onto an SD-card is in progress.
  1537. // Saving starts with M28, saving until M29 is seen.
  1538. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1539. card.write_command(CMDBUFFER_CURRENT_STRING);
  1540. if(card.logging)
  1541. process_commands();
  1542. else
  1543. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1544. } else {
  1545. card.closefile();
  1546. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1547. }
  1548. } else {
  1549. process_commands();
  1550. }
  1551. #else
  1552. process_commands();
  1553. #endif //SDSUPPORT
  1554. if (! cmdbuffer_front_already_processed && buflen)
  1555. {
  1556. // ptr points to the start of the block currently being processed.
  1557. // The first character in the block is the block type.
  1558. char *ptr = cmdbuffer + bufindr;
  1559. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1560. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1561. union {
  1562. struct {
  1563. char lo;
  1564. char hi;
  1565. } lohi;
  1566. uint16_t value;
  1567. } sdlen;
  1568. sdlen.value = 0;
  1569. {
  1570. // This block locks the interrupts globally for 3.25 us,
  1571. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1572. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1573. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1574. cli();
  1575. // Reset the command to something, which will be ignored by the power panic routine,
  1576. // so this buffer length will not be counted twice.
  1577. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1578. // Extract the current buffer length.
  1579. sdlen.lohi.lo = *ptr ++;
  1580. sdlen.lohi.hi = *ptr;
  1581. // and pass it to the planner queue.
  1582. planner_add_sd_length(sdlen.value);
  1583. sei();
  1584. }
  1585. }
  1586. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1587. cli();
  1588. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1589. // and one for each command to previous block in the planner queue.
  1590. planner_add_sd_length(1);
  1591. sei();
  1592. }
  1593. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1594. // this block's SD card length will not be counted twice as its command type has been replaced
  1595. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1596. cmdqueue_pop_front();
  1597. }
  1598. host_keepalive();
  1599. }
  1600. }
  1601. //check heater every n milliseconds
  1602. manage_heater();
  1603. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1604. checkHitEndstops();
  1605. lcd_update(0);
  1606. #ifdef TMC2130
  1607. tmc2130_check_overtemp();
  1608. if (tmc2130_sg_crash)
  1609. {
  1610. uint8_t crash = tmc2130_sg_crash;
  1611. tmc2130_sg_crash = 0;
  1612. // crashdet_stop_and_save_print();
  1613. switch (crash)
  1614. {
  1615. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1616. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1617. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1618. }
  1619. }
  1620. #endif //TMC2130
  1621. mmu_loop();
  1622. }
  1623. #define DEFINE_PGM_READ_ANY(type, reader) \
  1624. static inline type pgm_read_any(const type *p) \
  1625. { return pgm_read_##reader##_near(p); }
  1626. DEFINE_PGM_READ_ANY(float, float);
  1627. DEFINE_PGM_READ_ANY(signed char, byte);
  1628. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1629. static const PROGMEM type array##_P[3] = \
  1630. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1631. static inline type array(int axis) \
  1632. { return pgm_read_any(&array##_P[axis]); } \
  1633. type array##_ext(int axis) \
  1634. { return pgm_read_any(&array##_P[axis]); }
  1635. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1636. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1637. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1638. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1639. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1640. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1641. static void axis_is_at_home(int axis) {
  1642. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1643. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1644. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1645. }
  1646. //! @return original feedmultiply
  1647. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1648. saved_feedrate = feedrate;
  1649. int l_feedmultiply = feedmultiply;
  1650. feedmultiply = 100;
  1651. previous_millis_cmd = _millis();
  1652. enable_endstops(enable_endstops_now);
  1653. return l_feedmultiply;
  1654. }
  1655. //! @param original_feedmultiply feedmultiply to restore
  1656. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1657. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1658. enable_endstops(false);
  1659. #endif
  1660. feedrate = saved_feedrate;
  1661. feedmultiply = original_feedmultiply;
  1662. previous_millis_cmd = _millis();
  1663. }
  1664. #ifdef ENABLE_AUTO_BED_LEVELING
  1665. #ifdef AUTO_BED_LEVELING_GRID
  1666. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1667. {
  1668. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1669. planeNormal.debug("planeNormal");
  1670. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1671. //bedLevel.debug("bedLevel");
  1672. //plan_bed_level_matrix.debug("bed level before");
  1673. //vector_3 uncorrected_position = plan_get_position_mm();
  1674. //uncorrected_position.debug("position before");
  1675. vector_3 corrected_position = plan_get_position();
  1676. // corrected_position.debug("position after");
  1677. current_position[X_AXIS] = corrected_position.x;
  1678. current_position[Y_AXIS] = corrected_position.y;
  1679. current_position[Z_AXIS] = corrected_position.z;
  1680. // put the bed at 0 so we don't go below it.
  1681. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1682. plan_set_position_curposXYZE();
  1683. }
  1684. #else // not AUTO_BED_LEVELING_GRID
  1685. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1686. plan_bed_level_matrix.set_to_identity();
  1687. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1688. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1689. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1690. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1691. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1692. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1693. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1694. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1695. vector_3 corrected_position = plan_get_position();
  1696. current_position[X_AXIS] = corrected_position.x;
  1697. current_position[Y_AXIS] = corrected_position.y;
  1698. current_position[Z_AXIS] = corrected_position.z;
  1699. // put the bed at 0 so we don't go below it.
  1700. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1701. plan_set_position_curposXYZE();
  1702. }
  1703. #endif // AUTO_BED_LEVELING_GRID
  1704. static void run_z_probe() {
  1705. plan_bed_level_matrix.set_to_identity();
  1706. feedrate = homing_feedrate[Z_AXIS];
  1707. // move down until you find the bed
  1708. float zPosition = -10;
  1709. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1710. st_synchronize();
  1711. // we have to let the planner know where we are right now as it is not where we said to go.
  1712. zPosition = st_get_position_mm(Z_AXIS);
  1713. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1714. // move up the retract distance
  1715. zPosition += home_retract_mm(Z_AXIS);
  1716. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1717. st_synchronize();
  1718. // move back down slowly to find bed
  1719. feedrate = homing_feedrate[Z_AXIS]/4;
  1720. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1721. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1722. st_synchronize();
  1723. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1724. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1725. plan_set_position_curposXYZE();
  1726. }
  1727. static void do_blocking_move_to(float x, float y, float z) {
  1728. float oldFeedRate = feedrate;
  1729. feedrate = homing_feedrate[Z_AXIS];
  1730. current_position[Z_AXIS] = z;
  1731. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1732. st_synchronize();
  1733. feedrate = XY_TRAVEL_SPEED;
  1734. current_position[X_AXIS] = x;
  1735. current_position[Y_AXIS] = y;
  1736. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1737. st_synchronize();
  1738. feedrate = oldFeedRate;
  1739. }
  1740. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1741. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1742. }
  1743. /// Probe bed height at position (x,y), returns the measured z value
  1744. static float probe_pt(float x, float y, float z_before) {
  1745. // move to right place
  1746. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1747. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1748. run_z_probe();
  1749. float measured_z = current_position[Z_AXIS];
  1750. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1751. SERIAL_PROTOCOLPGM(" x: ");
  1752. SERIAL_PROTOCOL(x);
  1753. SERIAL_PROTOCOLPGM(" y: ");
  1754. SERIAL_PROTOCOL(y);
  1755. SERIAL_PROTOCOLPGM(" z: ");
  1756. SERIAL_PROTOCOL(measured_z);
  1757. SERIAL_PROTOCOLPGM("\n");
  1758. return measured_z;
  1759. }
  1760. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1761. #ifdef LIN_ADVANCE
  1762. /**
  1763. * M900: Set and/or Get advance K factor
  1764. *
  1765. * K<factor> Set advance K factor
  1766. */
  1767. inline void gcode_M900() {
  1768. float newK = code_seen('K') ? code_value_float() : -2;
  1769. #ifdef LA_NOCOMPAT
  1770. if (newK >= 0 && newK < LA_K_MAX)
  1771. extruder_advance_K = newK;
  1772. else
  1773. SERIAL_ECHOLNPGM("K out of allowed range!");
  1774. #else
  1775. if (newK == 0)
  1776. {
  1777. extruder_advance_K = 0;
  1778. la10c_reset();
  1779. }
  1780. else
  1781. {
  1782. newK = la10c_value(newK);
  1783. if (newK < 0)
  1784. SERIAL_ECHOLNPGM("K out of allowed range!");
  1785. else
  1786. extruder_advance_K = newK;
  1787. }
  1788. #endif
  1789. SERIAL_ECHO_START;
  1790. SERIAL_ECHOPGM("Advance K=");
  1791. SERIAL_ECHOLN(extruder_advance_K);
  1792. }
  1793. #endif // LIN_ADVANCE
  1794. bool check_commands() {
  1795. bool end_command_found = false;
  1796. while (buflen)
  1797. {
  1798. if ((code_seen("M84")) || (code_seen("M 84"))) end_command_found = true;
  1799. if (!cmdbuffer_front_already_processed)
  1800. cmdqueue_pop_front();
  1801. cmdbuffer_front_already_processed = false;
  1802. }
  1803. return end_command_found;
  1804. }
  1805. // raise_z_above: slowly raise Z to the requested height
  1806. //
  1807. // contrarily to a simple move, this function will carefully plan a move
  1808. // when the current Z position is unknown. In such cases, stallguard is
  1809. // enabled and will prevent prolonged pushing against the Z tops
  1810. void raise_z_above(float target, bool plan)
  1811. {
  1812. if (current_position[Z_AXIS] >= target)
  1813. return;
  1814. // Z needs raising
  1815. current_position[Z_AXIS] = target;
  1816. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1817. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1818. #else
  1819. bool z_min_endstop = false;
  1820. #endif
  1821. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1822. {
  1823. // current position is known or very low, it's safe to raise Z
  1824. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1825. return;
  1826. }
  1827. // ensure Z is powered in normal mode to overcome initial load
  1828. enable_z();
  1829. st_synchronize();
  1830. // rely on crashguard to limit damage
  1831. bool z_endstop_enabled = enable_z_endstop(true);
  1832. #ifdef TMC2130
  1833. tmc2130_home_enter(Z_AXIS_MASK);
  1834. #endif //TMC2130
  1835. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1836. st_synchronize();
  1837. #ifdef TMC2130
  1838. if (endstop_z_hit_on_purpose())
  1839. {
  1840. // not necessarily exact, but will avoid further vertical moves
  1841. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1842. plan_set_position_curposXYZE();
  1843. }
  1844. tmc2130_home_exit();
  1845. #endif //TMC2130
  1846. enable_z_endstop(z_endstop_enabled);
  1847. }
  1848. #ifdef TMC2130
  1849. bool calibrate_z_auto()
  1850. {
  1851. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1852. lcd_clear();
  1853. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1854. bool endstops_enabled = enable_endstops(true);
  1855. int axis_up_dir = -home_dir(Z_AXIS);
  1856. tmc2130_home_enter(Z_AXIS_MASK);
  1857. current_position[Z_AXIS] = 0;
  1858. plan_set_position_curposXYZE();
  1859. set_destination_to_current();
  1860. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1861. feedrate = homing_feedrate[Z_AXIS];
  1862. plan_buffer_line_destinationXYZE(feedrate / 60);
  1863. st_synchronize();
  1864. // current_position[axis] = 0;
  1865. // plan_set_position_curposXYZE();
  1866. tmc2130_home_exit();
  1867. enable_endstops(false);
  1868. current_position[Z_AXIS] = 0;
  1869. plan_set_position_curposXYZE();
  1870. set_destination_to_current();
  1871. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1872. feedrate = homing_feedrate[Z_AXIS] / 2;
  1873. plan_buffer_line_destinationXYZE(feedrate / 60);
  1874. st_synchronize();
  1875. enable_endstops(endstops_enabled);
  1876. if (PRINTER_TYPE == PRINTER_MK3) {
  1877. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1878. }
  1879. else {
  1880. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1881. }
  1882. plan_set_position_curposXYZE();
  1883. return true;
  1884. }
  1885. #endif //TMC2130
  1886. #ifdef TMC2130
  1887. static void check_Z_crash(void)
  1888. {
  1889. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1890. FORCE_HIGH_POWER_END;
  1891. current_position[Z_AXIS] = 0;
  1892. plan_set_position_curposXYZE();
  1893. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1894. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1895. st_synchronize();
  1896. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1897. }
  1898. }
  1899. #endif //TMC2130
  1900. #ifdef TMC2130
  1901. void homeaxis(int axis, uint8_t cnt, uint8_t* pstep)
  1902. #else
  1903. void homeaxis(int axis, uint8_t cnt)
  1904. #endif //TMC2130
  1905. {
  1906. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1907. #define HOMEAXIS_DO(LETTER) \
  1908. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1909. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1910. {
  1911. int axis_home_dir = home_dir(axis);
  1912. feedrate = homing_feedrate[axis];
  1913. #ifdef TMC2130
  1914. tmc2130_home_enter(X_AXIS_MASK << axis);
  1915. #endif //TMC2130
  1916. // Move away a bit, so that the print head does not touch the end position,
  1917. // and the following movement to endstop has a chance to achieve the required velocity
  1918. // for the stall guard to work.
  1919. current_position[axis] = 0;
  1920. plan_set_position_curposXYZE();
  1921. set_destination_to_current();
  1922. // destination[axis] = 11.f;
  1923. destination[axis] = -3.f * axis_home_dir;
  1924. plan_buffer_line_destinationXYZE(feedrate/60);
  1925. st_synchronize();
  1926. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1927. endstops_hit_on_purpose();
  1928. enable_endstops(false);
  1929. current_position[axis] = 0;
  1930. plan_set_position_curposXYZE();
  1931. destination[axis] = 1. * axis_home_dir;
  1932. plan_buffer_line_destinationXYZE(feedrate/60);
  1933. st_synchronize();
  1934. // Now continue to move up to the left end stop with the collision detection enabled.
  1935. enable_endstops(true);
  1936. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1937. plan_buffer_line_destinationXYZE(feedrate/60);
  1938. st_synchronize();
  1939. for (uint8_t i = 0; i < cnt; i++)
  1940. {
  1941. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1942. endstops_hit_on_purpose();
  1943. enable_endstops(false);
  1944. current_position[axis] = 0;
  1945. plan_set_position_curposXYZE();
  1946. destination[axis] = -10.f * axis_home_dir;
  1947. plan_buffer_line_destinationXYZE(feedrate/60);
  1948. st_synchronize();
  1949. endstops_hit_on_purpose();
  1950. // Now move left up to the collision, this time with a repeatable velocity.
  1951. enable_endstops(true);
  1952. destination[axis] = 11.f * axis_home_dir;
  1953. #ifdef TMC2130
  1954. feedrate = homing_feedrate[axis];
  1955. #else //TMC2130
  1956. feedrate = homing_feedrate[axis] / 2;
  1957. #endif //TMC2130
  1958. plan_buffer_line_destinationXYZE(feedrate/60);
  1959. st_synchronize();
  1960. #ifdef TMC2130
  1961. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1962. if (pstep) pstep[i] = mscnt >> 4;
  1963. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1964. #endif //TMC2130
  1965. }
  1966. endstops_hit_on_purpose();
  1967. enable_endstops(false);
  1968. #ifdef TMC2130
  1969. uint8_t orig = tmc2130_home_origin[axis];
  1970. uint8_t back = tmc2130_home_bsteps[axis];
  1971. if (tmc2130_home_enabled && (orig <= 63))
  1972. {
  1973. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1974. if (back > 0)
  1975. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1976. }
  1977. else
  1978. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1979. tmc2130_home_exit();
  1980. #endif //TMC2130
  1981. axis_is_at_home(axis);
  1982. axis_known_position[axis] = true;
  1983. // Move from minimum
  1984. #ifdef TMC2130
  1985. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1986. #else //TMC2130
  1987. float dist = - axis_home_dir * 0.01f * 64;
  1988. #endif //TMC2130
  1989. current_position[axis] -= dist;
  1990. plan_set_position_curposXYZE();
  1991. current_position[axis] += dist;
  1992. destination[axis] = current_position[axis];
  1993. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1994. st_synchronize();
  1995. feedrate = 0.0;
  1996. }
  1997. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1998. {
  1999. #ifdef TMC2130
  2000. FORCE_HIGH_POWER_START;
  2001. #endif
  2002. int axis_home_dir = home_dir(axis);
  2003. current_position[axis] = 0;
  2004. plan_set_position_curposXYZE();
  2005. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  2006. feedrate = homing_feedrate[axis];
  2007. plan_buffer_line_destinationXYZE(feedrate/60);
  2008. st_synchronize();
  2009. #ifdef TMC2130
  2010. check_Z_crash();
  2011. #endif //TMC2130
  2012. current_position[axis] = 0;
  2013. plan_set_position_curposXYZE();
  2014. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  2015. plan_buffer_line_destinationXYZE(feedrate/60);
  2016. st_synchronize();
  2017. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  2018. feedrate = homing_feedrate[axis]/2 ;
  2019. plan_buffer_line_destinationXYZE(feedrate/60);
  2020. st_synchronize();
  2021. #ifdef TMC2130
  2022. check_Z_crash();
  2023. #endif //TMC2130
  2024. axis_is_at_home(axis);
  2025. destination[axis] = current_position[axis];
  2026. feedrate = 0.0;
  2027. endstops_hit_on_purpose();
  2028. axis_known_position[axis] = true;
  2029. #ifdef TMC2130
  2030. FORCE_HIGH_POWER_END;
  2031. #endif
  2032. }
  2033. enable_endstops(endstops_enabled);
  2034. }
  2035. /**/
  2036. void home_xy()
  2037. {
  2038. set_destination_to_current();
  2039. homeaxis(X_AXIS);
  2040. homeaxis(Y_AXIS);
  2041. plan_set_position_curposXYZE();
  2042. endstops_hit_on_purpose();
  2043. }
  2044. void refresh_cmd_timeout(void)
  2045. {
  2046. previous_millis_cmd = _millis();
  2047. }
  2048. #ifdef FWRETRACT
  2049. void retract(bool retracting, bool swapretract = false) {
  2050. if(retracting && !retracted[active_extruder]) {
  2051. destination[X_AXIS]=current_position[X_AXIS];
  2052. destination[Y_AXIS]=current_position[Y_AXIS];
  2053. destination[Z_AXIS]=current_position[Z_AXIS];
  2054. destination[E_AXIS]=current_position[E_AXIS];
  2055. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2056. plan_set_e_position(current_position[E_AXIS]);
  2057. float oldFeedrate = feedrate;
  2058. feedrate=cs.retract_feedrate*60;
  2059. retracted[active_extruder]=true;
  2060. prepare_move();
  2061. current_position[Z_AXIS]-=cs.retract_zlift;
  2062. plan_set_position_curposXYZE();
  2063. prepare_move();
  2064. feedrate = oldFeedrate;
  2065. } else if(!retracting && retracted[active_extruder]) {
  2066. destination[X_AXIS]=current_position[X_AXIS];
  2067. destination[Y_AXIS]=current_position[Y_AXIS];
  2068. destination[Z_AXIS]=current_position[Z_AXIS];
  2069. destination[E_AXIS]=current_position[E_AXIS];
  2070. current_position[Z_AXIS]+=cs.retract_zlift;
  2071. plan_set_position_curposXYZE();
  2072. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2073. plan_set_e_position(current_position[E_AXIS]);
  2074. float oldFeedrate = feedrate;
  2075. feedrate=cs.retract_recover_feedrate*60;
  2076. retracted[active_extruder]=false;
  2077. prepare_move();
  2078. feedrate = oldFeedrate;
  2079. }
  2080. } //retract
  2081. #endif //FWRETRACT
  2082. void trace() {
  2083. Sound_MakeCustom(25,440,true);
  2084. }
  2085. /*
  2086. void ramming() {
  2087. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  2088. if (current_temperature[0] < 230) {
  2089. //PLA
  2090. max_feedrate[E_AXIS] = 50;
  2091. //current_position[E_AXIS] -= 8;
  2092. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2093. //current_position[E_AXIS] += 8;
  2094. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2095. current_position[E_AXIS] += 5.4;
  2096. plan_buffer_line_curposXYZE(2800 / 60, active_extruder);
  2097. current_position[E_AXIS] += 3.2;
  2098. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  2099. current_position[E_AXIS] += 3;
  2100. plan_buffer_line_curposXYZE(3400 / 60, active_extruder);
  2101. st_synchronize();
  2102. max_feedrate[E_AXIS] = 80;
  2103. current_position[E_AXIS] -= 82;
  2104. plan_buffer_line_curposXYZE(9500 / 60, active_extruder);
  2105. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2106. current_position[E_AXIS] -= 20;
  2107. plan_buffer_line_curposXYZE(1200 / 60, active_extruder);
  2108. current_position[E_AXIS] += 5;
  2109. plan_buffer_line_curposXYZE(400 / 60, active_extruder);
  2110. current_position[E_AXIS] += 5;
  2111. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2112. current_position[E_AXIS] -= 10;
  2113. st_synchronize();
  2114. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2115. current_position[E_AXIS] += 10;
  2116. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2117. current_position[E_AXIS] -= 10;
  2118. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2119. current_position[E_AXIS] += 10;
  2120. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2121. current_position[E_AXIS] -= 10;
  2122. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2123. st_synchronize();
  2124. }
  2125. else {
  2126. //ABS
  2127. max_feedrate[E_AXIS] = 50;
  2128. //current_position[E_AXIS] -= 8;
  2129. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2130. //current_position[E_AXIS] += 8;
  2131. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2132. current_position[E_AXIS] += 3.1;
  2133. plan_buffer_line_curposXYZE(2000 / 60, active_extruder);
  2134. current_position[E_AXIS] += 3.1;
  2135. plan_buffer_line_curposXYZE(2500 / 60, active_extruder);
  2136. current_position[E_AXIS] += 4;
  2137. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  2138. st_synchronize();
  2139. //current_position[X_AXIS] += 23; //delay
  2140. //plan_buffer_line_curposXYZE(600/60, active_extruder); //delay
  2141. //current_position[X_AXIS] -= 23; //delay
  2142. //plan_buffer_line_curposXYZE(600/60, active_extruder); //delay
  2143. _delay(4700);
  2144. max_feedrate[E_AXIS] = 80;
  2145. current_position[E_AXIS] -= 92;
  2146. plan_buffer_line_curposXYZE(9900 / 60, active_extruder);
  2147. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2148. current_position[E_AXIS] -= 5;
  2149. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2150. current_position[E_AXIS] += 5;
  2151. plan_buffer_line_curposXYZE(400 / 60, active_extruder);
  2152. current_position[E_AXIS] -= 5;
  2153. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2154. st_synchronize();
  2155. current_position[E_AXIS] += 5;
  2156. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2157. current_position[E_AXIS] -= 5;
  2158. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2159. current_position[E_AXIS] += 5;
  2160. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2161. current_position[E_AXIS] -= 5;
  2162. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2163. st_synchronize();
  2164. }
  2165. }
  2166. */
  2167. #ifdef TMC2130
  2168. void force_high_power_mode(bool start_high_power_section) {
  2169. #ifdef PSU_Delta
  2170. if (start_high_power_section == true) enable_force_z();
  2171. #endif //PSU_Delta
  2172. uint8_t silent;
  2173. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2174. if (silent == 1) {
  2175. //we are in silent mode, set to normal mode to enable crash detection
  2176. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2177. st_synchronize();
  2178. cli();
  2179. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2180. update_mode_profile();
  2181. tmc2130_init();
  2182. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2183. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2184. st_reset_timer();
  2185. sei();
  2186. }
  2187. }
  2188. #endif //TMC2130
  2189. void gcode_M105(uint8_t extruder)
  2190. {
  2191. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2192. SERIAL_PROTOCOLPGM("T:");
  2193. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2194. SERIAL_PROTOCOLPGM(" /");
  2195. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2196. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2197. SERIAL_PROTOCOLPGM(" B:");
  2198. SERIAL_PROTOCOL_F(degBed(),1);
  2199. SERIAL_PROTOCOLPGM(" /");
  2200. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2201. #endif //TEMP_BED_PIN
  2202. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2203. SERIAL_PROTOCOLPGM(" T");
  2204. SERIAL_PROTOCOL(cur_extruder);
  2205. SERIAL_PROTOCOL(':');
  2206. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2207. SERIAL_PROTOCOLPGM(" /");
  2208. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2209. }
  2210. #else
  2211. SERIAL_ERROR_START;
  2212. SERIAL_ERRORLNRPGM(_i("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2213. #endif
  2214. SERIAL_PROTOCOLPGM(" @:");
  2215. #ifdef EXTRUDER_WATTS
  2216. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2217. SERIAL_PROTOCOLPGM("W");
  2218. #else
  2219. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2220. #endif
  2221. SERIAL_PROTOCOLPGM(" B@:");
  2222. #ifdef BED_WATTS
  2223. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2224. SERIAL_PROTOCOLPGM("W");
  2225. #else
  2226. SERIAL_PROTOCOL(getHeaterPower(-1));
  2227. #endif
  2228. #ifdef PINDA_THERMISTOR
  2229. SERIAL_PROTOCOLPGM(" P:");
  2230. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2231. #endif //PINDA_THERMISTOR
  2232. #ifdef AMBIENT_THERMISTOR
  2233. SERIAL_PROTOCOLPGM(" A:");
  2234. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2235. #endif //AMBIENT_THERMISTOR
  2236. #ifdef SHOW_TEMP_ADC_VALUES
  2237. {
  2238. float raw = 0.0;
  2239. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2240. SERIAL_PROTOCOLPGM(" ADC B:");
  2241. SERIAL_PROTOCOL_F(degBed(),1);
  2242. SERIAL_PROTOCOLPGM("C->");
  2243. raw = rawBedTemp();
  2244. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2245. SERIAL_PROTOCOLPGM(" Rb->");
  2246. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2247. SERIAL_PROTOCOLPGM(" Rxb->");
  2248. SERIAL_PROTOCOL_F(raw, 5);
  2249. #endif
  2250. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2251. SERIAL_PROTOCOLPGM(" T");
  2252. SERIAL_PROTOCOL(cur_extruder);
  2253. SERIAL_PROTOCOLPGM(":");
  2254. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2255. SERIAL_PROTOCOLPGM("C->");
  2256. raw = rawHotendTemp(cur_extruder);
  2257. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2258. SERIAL_PROTOCOLPGM(" Rt");
  2259. SERIAL_PROTOCOL(cur_extruder);
  2260. SERIAL_PROTOCOLPGM("->");
  2261. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2262. SERIAL_PROTOCOLPGM(" Rx");
  2263. SERIAL_PROTOCOL(cur_extruder);
  2264. SERIAL_PROTOCOLPGM("->");
  2265. SERIAL_PROTOCOL_F(raw, 5);
  2266. }
  2267. }
  2268. #endif
  2269. SERIAL_PROTOCOLLN("");
  2270. }
  2271. #ifdef TMC2130
  2272. 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)
  2273. #else
  2274. 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)
  2275. #endif //TMC2130
  2276. {
  2277. st_synchronize();
  2278. #if 0
  2279. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2280. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2281. #endif
  2282. // Flag for the display update routine and to disable the print cancelation during homing.
  2283. homing_flag = true;
  2284. // Which axes should be homed?
  2285. bool home_x = home_x_axis;
  2286. bool home_y = home_y_axis;
  2287. bool home_z = home_z_axis;
  2288. // Either all X,Y,Z codes are present, or none of them.
  2289. bool home_all_axes = home_x == home_y && home_x == home_z;
  2290. if (home_all_axes)
  2291. // No X/Y/Z code provided means to home all axes.
  2292. home_x = home_y = home_z = true;
  2293. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2294. if (home_all_axes) {
  2295. raise_z_above(MESH_HOME_Z_SEARCH);
  2296. st_synchronize();
  2297. }
  2298. #ifdef ENABLE_AUTO_BED_LEVELING
  2299. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2300. #endif //ENABLE_AUTO_BED_LEVELING
  2301. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2302. // the planner will not perform any adjustments in the XY plane.
  2303. // Wait for the motors to stop and update the current position with the absolute values.
  2304. world2machine_revert_to_uncorrected();
  2305. // For mesh bed leveling deactivate the matrix temporarily.
  2306. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2307. // in a single axis only.
  2308. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2309. #ifdef MESH_BED_LEVELING
  2310. uint8_t mbl_was_active = mbl.active;
  2311. mbl.active = 0;
  2312. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2313. #endif
  2314. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2315. // consumed during the first movements following this statement.
  2316. if (home_z)
  2317. babystep_undo();
  2318. saved_feedrate = feedrate;
  2319. int l_feedmultiply = feedmultiply;
  2320. feedmultiply = 100;
  2321. previous_millis_cmd = _millis();
  2322. enable_endstops(true);
  2323. memcpy(destination, current_position, sizeof(destination));
  2324. feedrate = 0.0;
  2325. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2326. if(home_z)
  2327. homeaxis(Z_AXIS);
  2328. #endif
  2329. #ifdef QUICK_HOME
  2330. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2331. if(home_x && home_y) //first diagonal move
  2332. {
  2333. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2334. int x_axis_home_dir = home_dir(X_AXIS);
  2335. plan_set_position_curposXYZE();
  2336. 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);
  2337. feedrate = homing_feedrate[X_AXIS];
  2338. if(homing_feedrate[Y_AXIS]<feedrate)
  2339. feedrate = homing_feedrate[Y_AXIS];
  2340. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2341. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2342. } else {
  2343. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2344. }
  2345. plan_buffer_line_destinationXYZE(feedrate/60);
  2346. st_synchronize();
  2347. axis_is_at_home(X_AXIS);
  2348. axis_is_at_home(Y_AXIS);
  2349. plan_set_position_curposXYZE();
  2350. destination[X_AXIS] = current_position[X_AXIS];
  2351. destination[Y_AXIS] = current_position[Y_AXIS];
  2352. plan_buffer_line_destinationXYZE(feedrate/60);
  2353. feedrate = 0.0;
  2354. st_synchronize();
  2355. endstops_hit_on_purpose();
  2356. current_position[X_AXIS] = destination[X_AXIS];
  2357. current_position[Y_AXIS] = destination[Y_AXIS];
  2358. current_position[Z_AXIS] = destination[Z_AXIS];
  2359. }
  2360. #endif /* QUICK_HOME */
  2361. #ifdef TMC2130
  2362. if(home_x)
  2363. {
  2364. if (!calib)
  2365. homeaxis(X_AXIS);
  2366. else
  2367. tmc2130_home_calibrate(X_AXIS);
  2368. }
  2369. if(home_y)
  2370. {
  2371. if (!calib)
  2372. homeaxis(Y_AXIS);
  2373. else
  2374. tmc2130_home_calibrate(Y_AXIS);
  2375. }
  2376. #else //TMC2130
  2377. if(home_x) homeaxis(X_AXIS);
  2378. if(home_y) homeaxis(Y_AXIS);
  2379. #endif //TMC2130
  2380. if(home_x_axis && home_x_value != 0)
  2381. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2382. if(home_y_axis && home_y_value != 0)
  2383. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2384. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2385. #ifndef Z_SAFE_HOMING
  2386. if(home_z) {
  2387. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2388. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2389. st_synchronize();
  2390. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2391. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP)) // If Mesh bed leveling, move X&Y to safe position for home
  2392. raise_z_above(MESH_HOME_Z_SEARCH);
  2393. st_synchronize();
  2394. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2395. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2396. // 1st mesh bed leveling measurement point, corrected.
  2397. world2machine_initialize();
  2398. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2399. world2machine_reset();
  2400. if (destination[Y_AXIS] < Y_MIN_POS)
  2401. destination[Y_AXIS] = Y_MIN_POS;
  2402. feedrate = homing_feedrate[X_AXIS] / 20;
  2403. enable_endstops(false);
  2404. #ifdef DEBUG_BUILD
  2405. SERIAL_ECHOLNPGM("plan_set_position()");
  2406. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2407. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2408. #endif
  2409. plan_set_position_curposXYZE();
  2410. #ifdef DEBUG_BUILD
  2411. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2412. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2413. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2414. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2415. #endif
  2416. plan_buffer_line_destinationXYZE(feedrate);
  2417. st_synchronize();
  2418. current_position[X_AXIS] = destination[X_AXIS];
  2419. current_position[Y_AXIS] = destination[Y_AXIS];
  2420. enable_endstops(true);
  2421. endstops_hit_on_purpose();
  2422. homeaxis(Z_AXIS);
  2423. #else // MESH_BED_LEVELING
  2424. homeaxis(Z_AXIS);
  2425. #endif // MESH_BED_LEVELING
  2426. }
  2427. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2428. if(home_all_axes) {
  2429. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2430. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2431. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2432. feedrate = XY_TRAVEL_SPEED/60;
  2433. current_position[Z_AXIS] = 0;
  2434. plan_set_position_curposXYZE();
  2435. plan_buffer_line_destinationXYZE(feedrate);
  2436. st_synchronize();
  2437. current_position[X_AXIS] = destination[X_AXIS];
  2438. current_position[Y_AXIS] = destination[Y_AXIS];
  2439. homeaxis(Z_AXIS);
  2440. }
  2441. // Let's see if X and Y are homed and probe is inside bed area.
  2442. if(home_z) {
  2443. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2444. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2445. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2446. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2447. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2448. current_position[Z_AXIS] = 0;
  2449. plan_set_position_curposXYZE();
  2450. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2451. feedrate = max_feedrate[Z_AXIS];
  2452. plan_buffer_line_destinationXYZE(feedrate);
  2453. st_synchronize();
  2454. homeaxis(Z_AXIS);
  2455. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2456. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2457. SERIAL_ECHO_START;
  2458. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2459. } else {
  2460. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2461. SERIAL_ECHO_START;
  2462. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2463. }
  2464. }
  2465. #endif // Z_SAFE_HOMING
  2466. #endif // Z_HOME_DIR < 0
  2467. if(home_z_axis && home_z_value != 0)
  2468. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2469. #ifdef ENABLE_AUTO_BED_LEVELING
  2470. if(home_z)
  2471. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2472. #endif
  2473. // Set the planner and stepper routine positions.
  2474. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2475. // contains the machine coordinates.
  2476. plan_set_position_curposXYZE();
  2477. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  2478. enable_endstops(false);
  2479. #endif
  2480. feedrate = saved_feedrate;
  2481. feedmultiply = l_feedmultiply;
  2482. previous_millis_cmd = _millis();
  2483. endstops_hit_on_purpose();
  2484. #ifndef MESH_BED_LEVELING
  2485. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2486. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2487. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2488. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2489. lcd_adjust_z();
  2490. #endif
  2491. // Load the machine correction matrix
  2492. world2machine_initialize();
  2493. // and correct the current_position XY axes to match the transformed coordinate system.
  2494. world2machine_update_current();
  2495. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP))
  2496. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2497. {
  2498. if (! home_z && mbl_was_active) {
  2499. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2500. mbl.active = true;
  2501. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2502. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2503. }
  2504. }
  2505. else
  2506. {
  2507. st_synchronize();
  2508. homing_flag = false;
  2509. }
  2510. #endif
  2511. if (farm_mode) { prusa_statistics(20); };
  2512. homing_flag = false;
  2513. #if 0
  2514. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2515. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2516. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2517. #endif
  2518. }
  2519. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2520. {
  2521. #ifdef TMC2130
  2522. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2523. #else
  2524. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2525. #endif //TMC2130
  2526. }
  2527. void adjust_bed_reset()
  2528. {
  2529. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2530. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2531. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2532. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2533. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2534. }
  2535. //! @brief Calibrate XYZ
  2536. //! @param onlyZ if true, calibrate only Z axis
  2537. //! @param verbosity_level
  2538. //! @retval true Succeeded
  2539. //! @retval false Failed
  2540. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2541. {
  2542. bool final_result = false;
  2543. #ifdef TMC2130
  2544. FORCE_HIGH_POWER_START;
  2545. #endif // TMC2130
  2546. FORCE_BL_ON_START;
  2547. // Only Z calibration?
  2548. if (!onlyZ)
  2549. {
  2550. setTargetBed(0);
  2551. setAllTargetHotends(0);
  2552. adjust_bed_reset(); //reset bed level correction
  2553. }
  2554. // Disable the default update procedure of the display. We will do a modal dialog.
  2555. lcd_update_enable(false);
  2556. // Let the planner use the uncorrected coordinates.
  2557. mbl.reset();
  2558. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2559. // the planner will not perform any adjustments in the XY plane.
  2560. // Wait for the motors to stop and update the current position with the absolute values.
  2561. world2machine_revert_to_uncorrected();
  2562. // Reset the baby step value applied without moving the axes.
  2563. babystep_reset();
  2564. // Mark all axes as in a need for homing.
  2565. memset(axis_known_position, 0, sizeof(axis_known_position));
  2566. // Home in the XY plane.
  2567. //set_destination_to_current();
  2568. int l_feedmultiply = setup_for_endstop_move();
  2569. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2570. home_xy();
  2571. enable_endstops(false);
  2572. current_position[X_AXIS] += 5;
  2573. current_position[Y_AXIS] += 5;
  2574. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2575. st_synchronize();
  2576. // Let the user move the Z axes up to the end stoppers.
  2577. #ifdef TMC2130
  2578. if (calibrate_z_auto())
  2579. {
  2580. #else //TMC2130
  2581. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2582. {
  2583. #endif //TMC2130
  2584. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2585. if(onlyZ){
  2586. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2587. lcd_set_cursor(0, 3);
  2588. lcd_print(1);
  2589. lcd_puts_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE2));
  2590. }else{
  2591. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2592. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2593. lcd_set_cursor(0, 2);
  2594. lcd_print(1);
  2595. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2596. }
  2597. refresh_cmd_timeout();
  2598. #ifndef STEEL_SHEET
  2599. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2600. {
  2601. lcd_wait_for_cool_down();
  2602. }
  2603. #endif //STEEL_SHEET
  2604. if(!onlyZ)
  2605. {
  2606. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2607. #ifdef STEEL_SHEET
  2608. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2609. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2610. #endif //STEEL_SHEET
  2611. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2612. KEEPALIVE_STATE(IN_HANDLER);
  2613. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2614. lcd_set_cursor(0, 2);
  2615. lcd_print(1);
  2616. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2617. }
  2618. bool endstops_enabled = enable_endstops(false);
  2619. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2620. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2621. st_synchronize();
  2622. // Move the print head close to the bed.
  2623. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2624. enable_endstops(true);
  2625. #ifdef TMC2130
  2626. tmc2130_home_enter(Z_AXIS_MASK);
  2627. #endif //TMC2130
  2628. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2629. st_synchronize();
  2630. #ifdef TMC2130
  2631. tmc2130_home_exit();
  2632. #endif //TMC2130
  2633. enable_endstops(endstops_enabled);
  2634. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2635. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2636. {
  2637. if (onlyZ)
  2638. {
  2639. clean_up_after_endstop_move(l_feedmultiply);
  2640. // Z only calibration.
  2641. // Load the machine correction matrix
  2642. world2machine_initialize();
  2643. // and correct the current_position to match the transformed coordinate system.
  2644. world2machine_update_current();
  2645. //FIXME
  2646. bool result = sample_mesh_and_store_reference();
  2647. if (result)
  2648. {
  2649. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2650. // Shipped, the nozzle height has been set already. The user can start printing now.
  2651. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2652. final_result = true;
  2653. // babystep_apply();
  2654. }
  2655. }
  2656. else
  2657. {
  2658. // Reset the baby step value and the baby step applied flag.
  2659. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2660. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2661. // Complete XYZ calibration.
  2662. uint8_t point_too_far_mask = 0;
  2663. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2664. clean_up_after_endstop_move(l_feedmultiply);
  2665. // Print head up.
  2666. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2667. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2668. st_synchronize();
  2669. //#ifndef NEW_XYZCAL
  2670. if (result >= 0)
  2671. {
  2672. #ifdef HEATBED_V2
  2673. sample_z();
  2674. #else //HEATBED_V2
  2675. point_too_far_mask = 0;
  2676. // Second half: The fine adjustment.
  2677. // Let the planner use the uncorrected coordinates.
  2678. mbl.reset();
  2679. world2machine_reset();
  2680. // Home in the XY plane.
  2681. int l_feedmultiply = setup_for_endstop_move();
  2682. home_xy();
  2683. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2684. clean_up_after_endstop_move(l_feedmultiply);
  2685. // Print head up.
  2686. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2687. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2688. st_synchronize();
  2689. // if (result >= 0) babystep_apply();
  2690. #endif //HEATBED_V2
  2691. }
  2692. //#endif //NEW_XYZCAL
  2693. lcd_update_enable(true);
  2694. lcd_update(2);
  2695. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2696. if (result >= 0)
  2697. {
  2698. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2699. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2700. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2701. final_result = true;
  2702. }
  2703. }
  2704. #ifdef TMC2130
  2705. tmc2130_home_exit();
  2706. #endif
  2707. }
  2708. else
  2709. {
  2710. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2711. final_result = false;
  2712. }
  2713. }
  2714. else
  2715. {
  2716. // Timeouted.
  2717. }
  2718. lcd_update_enable(true);
  2719. #ifdef TMC2130
  2720. FORCE_HIGH_POWER_END;
  2721. #endif // TMC2130
  2722. FORCE_BL_ON_END;
  2723. return final_result;
  2724. }
  2725. void gcode_M114()
  2726. {
  2727. SERIAL_PROTOCOLPGM("X:");
  2728. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2729. SERIAL_PROTOCOLPGM(" Y:");
  2730. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2731. SERIAL_PROTOCOLPGM(" Z:");
  2732. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2733. SERIAL_PROTOCOLPGM(" E:");
  2734. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2735. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2736. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2737. SERIAL_PROTOCOLPGM(" Y:");
  2738. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2739. SERIAL_PROTOCOLPGM(" Z:");
  2740. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2741. SERIAL_PROTOCOLPGM(" E:");
  2742. SERIAL_PROTOCOL(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  2743. SERIAL_PROTOCOLLN("");
  2744. }
  2745. //! extracted code to compute z_shift for M600 in case of filament change operation
  2746. //! requested from fsensors.
  2747. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  2748. //! unlike the previous implementation, which was adding 25mm even when the head was
  2749. //! printing at e.g. 24mm height.
  2750. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  2751. //! the printout.
  2752. //! This function is templated to enable fast change of computation data type.
  2753. //! @return new z_shift value
  2754. template<typename T>
  2755. static T gcode_M600_filament_change_z_shift()
  2756. {
  2757. #ifdef FILAMENTCHANGE_ZADD
  2758. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  2759. // avoid floating point arithmetics when not necessary - results in shorter code
  2760. T ztmp = T( current_position[Z_AXIS] );
  2761. T z_shift = 0;
  2762. if(ztmp < T(25)){
  2763. z_shift = T(25) - ztmp; // make sure to be at least 25mm above the heat bed
  2764. }
  2765. return z_shift + T(FILAMENTCHANGE_ZADD); // always move above printout
  2766. #else
  2767. return T(0);
  2768. #endif
  2769. }
  2770. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  2771. {
  2772. st_synchronize();
  2773. float lastpos[4];
  2774. if (farm_mode)
  2775. {
  2776. prusa_statistics(22);
  2777. }
  2778. //First backup current position and settings
  2779. int feedmultiplyBckp = feedmultiply;
  2780. float HotendTempBckp = degTargetHotend(active_extruder);
  2781. int fanSpeedBckp = fanSpeed;
  2782. lastpos[X_AXIS] = current_position[X_AXIS];
  2783. lastpos[Y_AXIS] = current_position[Y_AXIS];
  2784. lastpos[Z_AXIS] = current_position[Z_AXIS];
  2785. lastpos[E_AXIS] = current_position[E_AXIS];
  2786. //Retract E
  2787. current_position[E_AXIS] += e_shift;
  2788. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  2789. st_synchronize();
  2790. //Lift Z
  2791. current_position[Z_AXIS] += z_shift;
  2792. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED);
  2793. st_synchronize();
  2794. //Move XY to side
  2795. current_position[X_AXIS] = x_position;
  2796. current_position[Y_AXIS] = y_position;
  2797. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  2798. st_synchronize();
  2799. //Beep, manage nozzle heater and wait for user to start unload filament
  2800. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  2801. lcd_change_fil_state = 0;
  2802. // Unload filament
  2803. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  2804. else unload_filament(); //unload filament for single material (used also in M702)
  2805. //finish moves
  2806. st_synchronize();
  2807. if (!mmu_enabled)
  2808. {
  2809. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2810. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"),
  2811. false, true); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  2812. if (lcd_change_fil_state == 0)
  2813. {
  2814. lcd_clear();
  2815. lcd_set_cursor(0, 2);
  2816. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2817. current_position[X_AXIS] -= 100;
  2818. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  2819. st_synchronize();
  2820. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=4
  2821. }
  2822. }
  2823. if (mmu_enabled)
  2824. {
  2825. if (!automatic) {
  2826. 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
  2827. mmu_M600_wait_and_beep();
  2828. if (saved_printing) {
  2829. lcd_clear();
  2830. lcd_set_cursor(0, 2);
  2831. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2832. mmu_command(MmuCmd::R0);
  2833. manage_response(false, false);
  2834. }
  2835. }
  2836. mmu_M600_load_filament(automatic, HotendTempBckp);
  2837. }
  2838. else
  2839. M600_load_filament();
  2840. if (!automatic) M600_check_state(HotendTempBckp);
  2841. lcd_update_enable(true);
  2842. //Not let's go back to print
  2843. fanSpeed = fanSpeedBckp;
  2844. //Feed a little of filament to stabilize pressure
  2845. if (!automatic)
  2846. {
  2847. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  2848. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  2849. }
  2850. //Move XY back
  2851. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  2852. FILAMENTCHANGE_XYFEED, active_extruder);
  2853. st_synchronize();
  2854. //Move Z back
  2855. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  2856. FILAMENTCHANGE_ZFEED, active_extruder);
  2857. st_synchronize();
  2858. //Set E position to original
  2859. plan_set_e_position(lastpos[E_AXIS]);
  2860. memcpy(current_position, lastpos, sizeof(lastpos));
  2861. memcpy(destination, current_position, sizeof(current_position));
  2862. //Recover feed rate
  2863. feedmultiply = feedmultiplyBckp;
  2864. char cmd[9];
  2865. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  2866. enquecommand(cmd);
  2867. #ifdef IR_SENSOR
  2868. //this will set fsensor_watch_autoload to correct value and prevent possible M701 gcode enqueuing when M600 is finished
  2869. fsensor_check_autoload();
  2870. #endif //IR_SENSOR
  2871. lcd_setstatuspgm(_T(WELCOME_MSG));
  2872. custom_message_type = CustomMsg::Status;
  2873. }
  2874. void gcode_M701()
  2875. {
  2876. printf_P(PSTR("gcode_M701 begin\n"));
  2877. if (farm_mode)
  2878. {
  2879. prusa_statistics(22);
  2880. }
  2881. if (mmu_enabled)
  2882. {
  2883. extr_adj(tmp_extruder);//loads current extruder
  2884. mmu_extruder = tmp_extruder;
  2885. }
  2886. else
  2887. {
  2888. enable_z();
  2889. custom_message_type = CustomMsg::FilamentLoading;
  2890. #ifdef FSENSOR_QUALITY
  2891. fsensor_oq_meassure_start(40);
  2892. #endif //FSENSOR_QUALITY
  2893. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  2894. current_position[E_AXIS] += 40;
  2895. plan_buffer_line_curposXYZE(400 / 60); //fast sequence
  2896. st_synchronize();
  2897. raise_z_above(MIN_Z_FOR_LOAD, false);
  2898. current_position[E_AXIS] += 30;
  2899. plan_buffer_line_curposXYZE(400 / 60); //fast sequence
  2900. load_filament_final_feed(); //slow sequence
  2901. st_synchronize();
  2902. Sound_MakeCustom(50,500,false);
  2903. if (!farm_mode && loading_flag) {
  2904. lcd_load_filament_color_check();
  2905. }
  2906. lcd_update_enable(true);
  2907. lcd_update(2);
  2908. lcd_setstatuspgm(_T(WELCOME_MSG));
  2909. disable_z();
  2910. loading_flag = false;
  2911. custom_message_type = CustomMsg::Status;
  2912. #ifdef FSENSOR_QUALITY
  2913. fsensor_oq_meassure_stop();
  2914. if (!fsensor_oq_result())
  2915. {
  2916. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  2917. lcd_update_enable(true);
  2918. lcd_update(2);
  2919. if (disable)
  2920. fsensor_disable();
  2921. }
  2922. #endif //FSENSOR_QUALITY
  2923. }
  2924. }
  2925. /**
  2926. * @brief Get serial number from 32U2 processor
  2927. *
  2928. * Typical format of S/N is:CZPX0917X003XC13518
  2929. *
  2930. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  2931. * reply is stored in *SN.
  2932. * Operation takes typically 23 ms. If the retransmit is not finished until 100 ms,
  2933. * it is interrupted, so less, or no characters are retransmitted, the function returns false
  2934. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  2935. * In that case the value that is stored in the EEPROM should be used instead.
  2936. *
  2937. * @return 1 on success
  2938. * @return 0 on general failure
  2939. */
  2940. static bool get_PRUSA_SN(char* SN)
  2941. {
  2942. uint8_t selectedSerialPort_bak = selectedSerialPort;
  2943. selectedSerialPort = 0;
  2944. SERIAL_ECHOLNRPGM(PSTR(";S"));
  2945. uint8_t numbersRead = 0;
  2946. ShortTimer timeout;
  2947. timeout.start();
  2948. while (numbersRead < 19) {
  2949. if (MSerial.available() > 0) {
  2950. SN[numbersRead] = MSerial.read();
  2951. numbersRead++;
  2952. }
  2953. if (timeout.expired(100u)) break;
  2954. }
  2955. SN[numbersRead] = 0;
  2956. selectedSerialPort = selectedSerialPort_bak;
  2957. return (numbersRead == 19);
  2958. }
  2959. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  2960. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  2961. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  2962. //! it may even interfere with other functions of the printer! You have been warned!
  2963. //! The test idea is to measure the time necessary to charge the capacitor.
  2964. //! So the algorithm is as follows:
  2965. //! 1. Set TACH_1 pin to INPUT mode and LOW
  2966. //! 2. Wait a few ms
  2967. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  2968. //! Repeat 1.-3. several times
  2969. //! Good RAMBo's times are in the range of approx. 260-320 us
  2970. //! Bad RAMBo's times are approx. 260-1200 us
  2971. //! So basically we are interested in maximum time, the minima are mostly the same.
  2972. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  2973. static void gcode_PRUSA_BadRAMBoFanTest(){
  2974. //printf_P(PSTR("Enter fan pin test\n"));
  2975. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  2976. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  2977. unsigned long tach1max = 0;
  2978. uint8_t tach1cntr = 0;
  2979. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  2980. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  2981. SET_OUTPUT(TACH_1);
  2982. WRITE(TACH_1, LOW);
  2983. _delay(20); // the delay may be lower
  2984. unsigned long tachMeasure = _micros();
  2985. cli();
  2986. SET_INPUT(TACH_1);
  2987. // just wait brutally in an endless cycle until we reach HIGH
  2988. // if this becomes a problem it may be improved to non-endless cycle
  2989. while( READ(TACH_1) == 0 ) ;
  2990. sei();
  2991. tachMeasure = _micros() - tachMeasure;
  2992. if( tach1max < tachMeasure )
  2993. tach1max = tachMeasure;
  2994. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  2995. }
  2996. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  2997. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  2998. if( tach1max > 500 ){
  2999. // bad RAMBo
  3000. SERIAL_PROTOCOLLNPGM("BAD");
  3001. } else {
  3002. SERIAL_PROTOCOLLNPGM("OK");
  3003. }
  3004. // cleanup after the test function
  3005. SET_INPUT(TACH_1);
  3006. WRITE(TACH_1, HIGH);
  3007. #endif
  3008. }
  3009. // G92 - Set current position to coordinates given
  3010. static void gcode_G92()
  3011. {
  3012. bool codes[NUM_AXIS];
  3013. float values[NUM_AXIS];
  3014. // Check which axes need to be set
  3015. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3016. {
  3017. codes[i] = code_seen(axis_codes[i]);
  3018. if(codes[i])
  3019. values[i] = code_value();
  3020. }
  3021. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3022. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3023. {
  3024. // As a special optimization, when _just_ clearing the E position
  3025. // we schedule a flag asynchronously along with the next block to
  3026. // reset the starting E position instead of stopping the planner
  3027. current_position[E_AXIS] = 0;
  3028. plan_reset_next_e();
  3029. }
  3030. else
  3031. {
  3032. // In any other case we're forced to synchronize
  3033. st_synchronize();
  3034. for(uint8_t i = 0; i < 3; ++i)
  3035. {
  3036. if(codes[i])
  3037. current_position[i] = values[i] + cs.add_homing[i];
  3038. }
  3039. if(codes[E_AXIS])
  3040. current_position[E_AXIS] = values[E_AXIS];
  3041. // Set all at once
  3042. plan_set_position_curposXYZE();
  3043. }
  3044. }
  3045. #ifdef EXTENDED_CAPABILITIES_REPORT
  3046. static void cap_line(const char* name, bool ena = false) {
  3047. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3048. }
  3049. static void extended_capabilities_report()
  3050. {
  3051. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT_TEMPERATURES));
  3052. //@todo
  3053. }
  3054. #endif //EXTENDED_CAPABILITIES_REPORT
  3055. #ifdef BACKLASH_X
  3056. extern uint8_t st_backlash_x;
  3057. #endif //BACKLASH_X
  3058. #ifdef BACKLASH_Y
  3059. extern uint8_t st_backlash_y;
  3060. #endif //BACKLASH_Y
  3061. //! \ingroup marlin_main
  3062. //! @brief Parse and process commands
  3063. //!
  3064. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3065. //!
  3066. //!
  3067. //! Implemented Codes
  3068. //! -------------------
  3069. //!
  3070. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3071. //!
  3072. //!@n PRUSA CODES
  3073. //!@n P F - Returns FW versions
  3074. //!@n P R - Returns revision of printer
  3075. //!
  3076. //!@n G0 -> G1
  3077. //!@n G1 - Coordinated Movement X Y Z E
  3078. //!@n G2 - CW ARC
  3079. //!@n G3 - CCW ARC
  3080. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3081. //!@n G10 - retract filament according to settings of M207
  3082. //!@n G11 - retract recover filament according to settings of M208
  3083. //!@n G28 - Home all Axes
  3084. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3085. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3086. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3087. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3088. //!@n G80 - Automatic mesh bed leveling
  3089. //!@n G81 - Print bed profile
  3090. //!@n G90 - Use Absolute Coordinates
  3091. //!@n G91 - Use Relative Coordinates
  3092. //!@n G92 - Set current position to coordinates given
  3093. //!
  3094. //!@n M Codes
  3095. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3096. //!@n M1 - Same as M0
  3097. //!@n M17 - Enable/Power all stepper motors
  3098. //!@n M18 - Disable all stepper motors; same as M84
  3099. //!@n M20 - List SD card
  3100. //!@n M21 - Init SD card
  3101. //!@n M22 - Release SD card
  3102. //!@n M23 - Select SD file (M23 filename.g)
  3103. //!@n M24 - Start/resume SD print
  3104. //!@n M25 - Pause SD print
  3105. //!@n M26 - Set SD position in bytes (M26 S12345)
  3106. //!@n M27 - Report SD print status
  3107. //!@n M28 - Start SD write (M28 filename.g)
  3108. //!@n M29 - Stop SD write
  3109. //!@n M30 - Delete file from SD (M30 filename.g)
  3110. //!@n M31 - Output time since last M109 or SD card start to serial
  3111. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3112. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3113. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3114. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3115. //!@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.
  3116. //!@n M73 - Show percent done and print time remaining
  3117. //!@n M80 - Turn on Power Supply
  3118. //!@n M81 - Turn off Power Supply
  3119. //!@n M82 - Set E codes absolute (default)
  3120. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3121. //!@n M84 - Disable steppers until next move,
  3122. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3123. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3124. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3125. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3126. //!@n M104 - Set extruder target temp
  3127. //!@n M105 - Read current temp
  3128. //!@n M106 - Fan on
  3129. //!@n M107 - Fan off
  3130. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3131. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3132. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3133. //!@n M112 - Emergency stop
  3134. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3135. //!@n M114 - Output current position to serial port
  3136. //!@n M115 - Capabilities string
  3137. //!@n M117 - display message
  3138. //!@n M119 - Output Endstop status to serial port
  3139. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3140. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3141. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3142. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3143. //!@n M140 - Set bed target temp
  3144. //!@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.
  3145. //!@n M155 - Automatically send temperatures
  3146. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3147. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3148. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3149. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3150. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3151. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3152. //!@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
  3153. //!@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
  3154. //!@n M206 - set additional homing offset
  3155. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3156. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3157. //!@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.
  3158. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3159. //!@n M220 S<factor in percent>- set speed factor override percentage
  3160. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3161. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3162. //!@n M240 - Trigger a camera to take a photograph
  3163. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3164. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3165. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3166. //!@n M301 - Set PID parameters P I and D
  3167. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3168. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3169. //!@n M304 - Set bed PID parameters P I and D
  3170. //!@n M400 - Finish all moves
  3171. //!@n M401 - Lower z-probe if present
  3172. //!@n M402 - Raise z-probe if present
  3173. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3174. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3175. //!@n M406 - Turn off Filament Sensor extrusion control
  3176. //!@n M407 - Displays measured filament diameter
  3177. //!@n M500 - stores parameters in EEPROM
  3178. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3179. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3180. //!@n M503 - print the current settings (from memory not from EEPROM)
  3181. //!@n M509 - force language selection on next restart
  3182. //!@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)
  3183. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3184. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3185. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3186. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3187. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3188. //!@n M907 - Set digital trimpot motor current using axis codes.
  3189. //!@n M908 - Control digital trimpot directly.
  3190. //!@n M350 - Set microstepping mode.
  3191. //!@n M351 - Toggle MS1 MS2 pins directly.
  3192. //!
  3193. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3194. //!@n M999 - Restart after being stopped by error
  3195. //! <br><br>
  3196. /** @defgroup marlin_main Marlin main */
  3197. /** \ingroup GCodes */
  3198. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3199. /**
  3200. They are shown in order of appearance in the code.
  3201. There are reasons why some G Codes aren't in numerical order.
  3202. */
  3203. void process_commands()
  3204. {
  3205. #ifdef FANCHECK
  3206. if(fan_check_error == EFCE_DETECTED){
  3207. fan_check_error = EFCE_REPORTED;
  3208. // SERIAL_PROTOCOLLNRPGM(MSG_OCTOPRINT_PAUSED);
  3209. lcd_pause_print();
  3210. cmdqueue_serial_disabled = true;
  3211. }
  3212. #endif
  3213. if (!buflen) return; //empty command
  3214. #ifdef FILAMENT_RUNOUT_SUPPORT
  3215. SET_INPUT(FR_SENS);
  3216. #endif
  3217. #ifdef CMDBUFFER_DEBUG
  3218. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3219. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3220. SERIAL_ECHOLNPGM("");
  3221. SERIAL_ECHOPGM("In cmdqueue: ");
  3222. SERIAL_ECHO(buflen);
  3223. SERIAL_ECHOLNPGM("");
  3224. #endif /* CMDBUFFER_DEBUG */
  3225. unsigned long codenum; //throw away variable
  3226. char *starpos = NULL;
  3227. #ifdef ENABLE_AUTO_BED_LEVELING
  3228. float x_tmp, y_tmp, z_tmp, real_z;
  3229. #endif
  3230. // PRUSA GCODES
  3231. KEEPALIVE_STATE(IN_HANDLER);
  3232. #ifdef SNMM
  3233. float tmp_motor[3] = DEFAULT_PWM_MOTOR_CURRENT;
  3234. float tmp_motor_loud[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  3235. int8_t SilentMode;
  3236. #endif
  3237. /*!
  3238. ---------------------------------------------------------------------------------
  3239. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3240. This causes the given message to be shown in the status line on an attached LCD.
  3241. It is processed early as to allow printing messages that contain G, M, N or T.
  3242. ---------------------------------------------------------------------------------
  3243. ### Special internal commands
  3244. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3245. They are processed early as the commands are complex (strings).
  3246. These are only available on the MK3(S) as these require TMC2130 drivers:
  3247. - CRASH DETECTED
  3248. - CRASH RECOVER
  3249. - CRASH_CANCEL
  3250. - TMC_SET_WAVE
  3251. - TMC_SET_STEP
  3252. - TMC_SET_CHOP
  3253. */
  3254. if (code_seen("M117")) { //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3255. starpos = (strchr(strchr_pointer + 5, '*'));
  3256. if (starpos != NULL)
  3257. *(starpos) = '\0';
  3258. lcd_setstatus(strchr_pointer + 5);
  3259. }
  3260. #ifdef TMC2130
  3261. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3262. {
  3263. // ### CRASH_DETECTED - TMC2130
  3264. // ---------------------------------
  3265. if(code_seen("CRASH_DETECTED"))
  3266. {
  3267. uint8_t mask = 0;
  3268. if (code_seen('X')) mask |= X_AXIS_MASK;
  3269. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3270. crashdet_detected(mask);
  3271. }
  3272. // ### CRASH_RECOVER - TMC2130
  3273. // ----------------------------------
  3274. else if(code_seen("CRASH_RECOVER"))
  3275. crashdet_recover();
  3276. // ### CRASH_CANCEL - TMC2130
  3277. // ----------------------------------
  3278. else if(code_seen("CRASH_CANCEL"))
  3279. crashdet_cancel();
  3280. }
  3281. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3282. {
  3283. // ### TMC_SET_WAVE_
  3284. // --------------------
  3285. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3286. {
  3287. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3288. axis = (axis == 'E')?3:(axis - 'X');
  3289. if (axis < 4)
  3290. {
  3291. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3292. tmc2130_set_wave(axis, 247, fac);
  3293. }
  3294. }
  3295. // ### TMC_SET_STEP_
  3296. // ------------------
  3297. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3298. {
  3299. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3300. axis = (axis == 'E')?3:(axis - 'X');
  3301. if (axis < 4)
  3302. {
  3303. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3304. uint16_t res = tmc2130_get_res(axis);
  3305. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3306. }
  3307. }
  3308. // ### TMC_SET_CHOP_
  3309. // -------------------
  3310. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3311. {
  3312. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3313. axis = (axis == 'E')?3:(axis - 'X');
  3314. if (axis < 4)
  3315. {
  3316. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3317. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3318. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3319. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3320. char* str_end = 0;
  3321. if (CMDBUFFER_CURRENT_STRING[14])
  3322. {
  3323. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3324. if (str_end && *str_end)
  3325. {
  3326. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3327. if (str_end && *str_end)
  3328. {
  3329. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3330. if (str_end && *str_end)
  3331. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3332. }
  3333. }
  3334. }
  3335. tmc2130_chopper_config[axis].toff = chop0;
  3336. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3337. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3338. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3339. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3340. //printf_P(_N("TMC_SET_CHOP_%c %hhd %hhd %hhd %hhd\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3341. }
  3342. }
  3343. }
  3344. #ifdef BACKLASH_X
  3345. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3346. {
  3347. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3348. st_backlash_x = bl;
  3349. printf_P(_N("st_backlash_x = %hhd\n"), st_backlash_x);
  3350. }
  3351. #endif //BACKLASH_X
  3352. #ifdef BACKLASH_Y
  3353. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3354. {
  3355. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3356. st_backlash_y = bl;
  3357. printf_P(_N("st_backlash_y = %hhd\n"), st_backlash_y);
  3358. }
  3359. #endif //BACKLASH_Y
  3360. #endif //TMC2130
  3361. else if(code_seen("PRUSA")){
  3362. /*!
  3363. ---------------------------------------------------------------------------------
  3364. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3365. Set of internal PRUSA commands
  3366. #### Usage
  3367. PRUSA [ Ping | PRN | FAN | fn | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | Beat | FR ]
  3368. #### Parameters
  3369. - `Ping`
  3370. - `PRN` - Prints revision of the printer
  3371. - `FAN` - Prints fan details
  3372. - `fn` - Prints farm no.
  3373. - `thx`
  3374. - `uvlo`
  3375. - `MMURES` - Reset MMU
  3376. - `RESET` - (Careful!)
  3377. - `fv` - ?
  3378. - `M28`
  3379. - `SN`
  3380. - `Fir` - Prints firmware version
  3381. - `Rev`- Prints filament size, elelectronics, nozzle type
  3382. - `Lang` - Reset the language
  3383. - `Lz`
  3384. - `Beat` - Kick farm link timer
  3385. - `FR` - Full factory reset
  3386. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3387. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3388. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3389. */
  3390. if (code_seen("Ping")) { // PRUSA Ping
  3391. if (farm_mode) {
  3392. PingTime = _millis();
  3393. //MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
  3394. }
  3395. }
  3396. else if (code_seen("PRN")) { // PRUSA PRN
  3397. printf_P(_N("%d"), status_number);
  3398. } else if( code_seen("FANPINTST") ){
  3399. gcode_PRUSA_BadRAMBoFanTest();
  3400. }else if (code_seen("FAN")) { // PRUSA FAN
  3401. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3402. }else if (code_seen("fn")) { // PRUSA fn
  3403. if (farm_mode) {
  3404. printf_P(_N("%d"), farm_no);
  3405. }
  3406. else {
  3407. puts_P(_N("Not in farm mode."));
  3408. }
  3409. }
  3410. else if (code_seen("thx")) // PRUSA thx
  3411. {
  3412. no_response = false;
  3413. }
  3414. else if (code_seen("uvlo")) // PRUSA uvlo
  3415. {
  3416. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3417. enquecommand_P(PSTR("M24"));
  3418. }
  3419. else if (code_seen("MMURES")) // PRUSA MMURES
  3420. {
  3421. mmu_reset();
  3422. }
  3423. else if (code_seen("RESET")) { // PRUSA RESET
  3424. // careful!
  3425. if (farm_mode) {
  3426. #if (defined(WATCHDOG) && (MOTHERBOARD == BOARD_EINSY_1_0a))
  3427. boot_app_magic = BOOT_APP_MAGIC;
  3428. boot_app_flags = BOOT_APP_FLG_RUN;
  3429. softReset();
  3430. #else //WATCHDOG
  3431. asm volatile("jmp 0x3E000");
  3432. #endif //WATCHDOG
  3433. }
  3434. else {
  3435. MYSERIAL.println("Not in farm mode.");
  3436. }
  3437. }else if (code_seen("fv")) { // PRUSA fv
  3438. // get file version
  3439. #ifdef SDSUPPORT
  3440. card.openFile(strchr_pointer + 3,true);
  3441. while (true) {
  3442. uint16_t readByte = card.get();
  3443. MYSERIAL.write(readByte);
  3444. if (readByte=='\n') {
  3445. break;
  3446. }
  3447. }
  3448. card.closefile();
  3449. #endif // SDSUPPORT
  3450. } else if (code_seen("M28")) { // PRUSA M28
  3451. trace();
  3452. prusa_sd_card_upload = true;
  3453. card.openFile(strchr_pointer+4,false);
  3454. } else if (code_seen("SN")) { // PRUSA SN
  3455. char SN[20];
  3456. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3457. if (SN[19])
  3458. puts_P(PSTR("SN invalid"));
  3459. else
  3460. puts(SN);
  3461. } else if(code_seen("Fir")){ // PRUSA Fir
  3462. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3463. } else if(code_seen("Rev")){ // PRUSA Rev
  3464. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3465. } else if(code_seen("Lang")) { // PRUSA Lang
  3466. lang_reset();
  3467. } else if(code_seen("Lz")) { // PRUSA Lz
  3468. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3469. } else if(code_seen("Beat")) { // PRUSA Beat
  3470. // Kick farm link timer
  3471. kicktime = _millis();
  3472. } else if(code_seen("FR")) { // PRUSA FR
  3473. // Factory full reset
  3474. factory_reset(0);
  3475. } else if(code_seen("MBL")) { // PRUSA MBL
  3476. // Change the MBL status without changing the logical Z position.
  3477. if(code_seen("V")) {
  3478. bool value = code_value_short();
  3479. st_synchronize();
  3480. if(value != mbl.active) {
  3481. mbl.active = value;
  3482. // Use plan_set_z_position to reset the physical values
  3483. plan_set_z_position(current_position[Z_AXIS]);
  3484. }
  3485. }
  3486. //-//
  3487. /*
  3488. } else if(code_seen("rrr")) {
  3489. MYSERIAL.println("=== checking ===");
  3490. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3491. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3492. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3493. MYSERIAL.println(farm_mode,DEC);
  3494. MYSERIAL.println(eCheckMode,DEC);
  3495. } else if(code_seen("www")) {
  3496. MYSERIAL.println("=== @ FF ===");
  3497. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3498. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3499. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3500. */
  3501. } else if (code_seen("nozzle")) { // PRUSA nozzle
  3502. uint16_t nDiameter;
  3503. if(code_seen('D'))
  3504. {
  3505. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3506. nozzle_diameter_check(nDiameter);
  3507. }
  3508. else if(code_seen("set") && farm_mode)
  3509. {
  3510. strchr_pointer++; // skip 1st char (~ 's')
  3511. strchr_pointer++; // skip 2nd char (~ 'e')
  3512. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3513. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3514. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3515. }
  3516. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3517. //-// !!! SupportMenu
  3518. /*
  3519. // musi byt PRED "PRUSA model"
  3520. } else if (code_seen("smodel")) { //! PRUSA smodel
  3521. size_t nOffset;
  3522. // ! -> "l"
  3523. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3524. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3525. if(*(strchr_pointer+1+nOffset))
  3526. printer_smodel_check(strchr_pointer);
  3527. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3528. } else if (code_seen("model")) { //! PRUSA model
  3529. uint16_t nPrinterModel;
  3530. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3531. nPrinterModel=(uint16_t)code_value_long();
  3532. if(nPrinterModel!=0)
  3533. printer_model_check(nPrinterModel);
  3534. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3535. } else if (code_seen("version")) { //! PRUSA version
  3536. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3537. while(*strchr_pointer==' ') // skip leading spaces
  3538. strchr_pointer++;
  3539. if(*strchr_pointer!=0)
  3540. fw_version_check(strchr_pointer);
  3541. else SERIAL_PROTOCOLLN(FW_VERSION);
  3542. } else if (code_seen("gcode")) { //! PRUSA gcode
  3543. uint16_t nGcodeLevel;
  3544. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3545. nGcodeLevel=(uint16_t)code_value_long();
  3546. if(nGcodeLevel!=0)
  3547. gcode_level_check(nGcodeLevel);
  3548. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3549. */
  3550. }
  3551. //else if (code_seen('Cal')) {
  3552. // lcd_calibration();
  3553. // }
  3554. }
  3555. // This prevents reading files with "^" in their names.
  3556. // Since it is unclear, if there is some usage of this construct,
  3557. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3558. // else if (code_seen('^')) {
  3559. // // nothing, this is a version line
  3560. // }
  3561. else if(code_seen('G'))
  3562. {
  3563. gcode_in_progress = (int)code_value();
  3564. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3565. switch (gcode_in_progress)
  3566. {
  3567. /*!
  3568. ---------------------------------------------------------------------------------
  3569. # G Codes
  3570. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3571. In Prusa Firmware G0 and G1 are the same.
  3572. #### Usage
  3573. G0 [ X | Y | Z | E | F | S ]
  3574. G1 [ X | Y | Z | E | F | S ]
  3575. #### Parameters
  3576. - `X` - The position to move to on the X axis
  3577. - `Y` - The position to move to on the Y axis
  3578. - `Z` - The position to move to on the Z axis
  3579. - `E` - The amount to extrude between the starting point and ending point
  3580. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3581. */
  3582. case 0: // G0 -> G1
  3583. case 1: // G1
  3584. if(Stopped == false) {
  3585. #ifdef FILAMENT_RUNOUT_SUPPORT
  3586. if(READ(FR_SENS)){
  3587. int feedmultiplyBckp=feedmultiply;
  3588. float target[4];
  3589. float lastpos[4];
  3590. target[X_AXIS]=current_position[X_AXIS];
  3591. target[Y_AXIS]=current_position[Y_AXIS];
  3592. target[Z_AXIS]=current_position[Z_AXIS];
  3593. target[E_AXIS]=current_position[E_AXIS];
  3594. lastpos[X_AXIS]=current_position[X_AXIS];
  3595. lastpos[Y_AXIS]=current_position[Y_AXIS];
  3596. lastpos[Z_AXIS]=current_position[Z_AXIS];
  3597. lastpos[E_AXIS]=current_position[E_AXIS];
  3598. //retract by E
  3599. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  3600. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3601. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  3602. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  3603. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  3604. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  3605. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  3606. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  3607. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3608. //finish moves
  3609. st_synchronize();
  3610. //disable extruder steppers so filament can be removed
  3611. disable_e0();
  3612. disable_e1();
  3613. disable_e2();
  3614. _delay(100);
  3615. //LCD_ALERTMESSAGEPGM(_T(MSG_FILAMENTCHANGE));
  3616. uint8_t cnt=0;
  3617. int counterBeep = 0;
  3618. lcd_wait_interact();
  3619. while(!lcd_clicked()){
  3620. cnt++;
  3621. manage_heater();
  3622. manage_inactivity(true);
  3623. //lcd_update(0);
  3624. if(cnt==0)
  3625. {
  3626. #if BEEPER > 0
  3627. if (counterBeep== 500){
  3628. counterBeep = 0;
  3629. }
  3630. SET_OUTPUT(BEEPER);
  3631. if (counterBeep== 0){
  3632. if(eSoundMode!=e_SOUND_MODE_SILENT)
  3633. WRITE(BEEPER,HIGH);
  3634. }
  3635. if (counterBeep== 20){
  3636. WRITE(BEEPER,LOW);
  3637. }
  3638. counterBeep++;
  3639. #else
  3640. #endif
  3641. }
  3642. }
  3643. WRITE(BEEPER,LOW);
  3644. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3645. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3646. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3647. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3648. lcd_change_fil_state = 0;
  3649. lcd_loading_filament();
  3650. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  3651. lcd_change_fil_state = 0;
  3652. lcd_alright();
  3653. switch(lcd_change_fil_state){
  3654. case 2:
  3655. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3656. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3657. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3658. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3659. lcd_loading_filament();
  3660. break;
  3661. case 3:
  3662. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3663. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3664. lcd_loading_color();
  3665. break;
  3666. default:
  3667. lcd_change_success();
  3668. break;
  3669. }
  3670. }
  3671. target[E_AXIS]+= 5;
  3672. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3673. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  3674. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3675. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  3676. //plan_set_e_position(current_position[E_AXIS]);
  3677. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  3678. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  3679. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  3680. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  3681. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  3682. plan_set_e_position(lastpos[E_AXIS]);
  3683. feedmultiply=feedmultiplyBckp;
  3684. char cmd[9];
  3685. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3686. enquecommand(cmd);
  3687. }
  3688. #endif
  3689. get_coordinates(); // For X Y Z E F
  3690. // When recovering from a previous print move, restore the originally
  3691. // calculated target position on the first USB/SD command. This accounts
  3692. // properly for relative moves
  3693. if ((saved_target[0] != SAVED_TARGET_UNSET) &&
  3694. ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  3695. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  3696. {
  3697. memcpy(destination, saved_target, sizeof(destination));
  3698. saved_target[0] = SAVED_TARGET_UNSET;
  3699. }
  3700. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3701. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3702. }
  3703. #ifdef FWRETRACT
  3704. if(cs.autoretract_enabled)
  3705. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3706. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3707. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3708. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3709. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3710. retract(!retracted[active_extruder]);
  3711. return;
  3712. }
  3713. }
  3714. #endif //FWRETRACT
  3715. prepare_move();
  3716. //ClearToSend();
  3717. }
  3718. break;
  3719. /*!
  3720. ### G2, G3 - Controlled Arc Move <a href="https://reprap.org/wiki/G-code#G2_.26_G3:_Controlled_Arc_Move">G2 & G3: Controlled Arc Move</a>
  3721. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3722. #### Usage
  3723. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3724. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3725. #### Parameters
  3726. - `X` - The position to move to on the X axis
  3727. - `Y` - The position to move to on the Y axis
  3728. - `I` - The point in X space from the current X position to maintain a constant distance from
  3729. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3730. - `E` - The amount to extrude between the starting point and ending point
  3731. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3732. */
  3733. case 2:
  3734. if(Stopped == false) {
  3735. get_arc_coordinates();
  3736. prepare_arc_move(true);
  3737. }
  3738. break;
  3739. // -------------------------------
  3740. case 3:
  3741. if(Stopped == false) {
  3742. get_arc_coordinates();
  3743. prepare_arc_move(false);
  3744. }
  3745. break;
  3746. /*!
  3747. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3748. Pause the machine for a period of time.
  3749. #### Usage
  3750. G4 [ P | S ]
  3751. #### Parameters
  3752. - `P` - Time to wait, in milliseconds
  3753. - `S` - Time to wait, in seconds
  3754. */
  3755. case 4:
  3756. codenum = 0;
  3757. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3758. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3759. if(codenum != 0) LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3760. st_synchronize();
  3761. codenum += _millis(); // keep track of when we started waiting
  3762. previous_millis_cmd = _millis();
  3763. while(_millis() < codenum) {
  3764. manage_heater();
  3765. manage_inactivity();
  3766. lcd_update(0);
  3767. }
  3768. break;
  3769. #ifdef FWRETRACT
  3770. /*!
  3771. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3772. Retracts filament according to settings of `M207`
  3773. */
  3774. case 10:
  3775. #if EXTRUDERS > 1
  3776. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3777. retract(true,retracted_swap[active_extruder]);
  3778. #else
  3779. retract(true);
  3780. #endif
  3781. break;
  3782. /*!
  3783. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3784. Unretracts/recovers filament according to settings of `M208`
  3785. */
  3786. case 11:
  3787. #if EXTRUDERS > 1
  3788. retract(false,retracted_swap[active_extruder]);
  3789. #else
  3790. retract(false);
  3791. #endif
  3792. break;
  3793. #endif //FWRETRACT
  3794. /*!
  3795. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  3796. Units are in millimeters. Prusa doesn't support inches.
  3797. */
  3798. case 21:
  3799. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  3800. /*!
  3801. ### G28 - Home all Axes one at a time <a href="https://reprap.org/wiki/G-code#G28:_Move_to_Origin_.28Home.29">G28: Move to Origin (Home)</a>
  3802. Using `G28` without any parameters will perfom homing of all axes AND mesh bed leveling, while `G28 W` will just home all axes (no mesh bed leveling).
  3803. #### Usage
  3804. G28 [ X | Y | Z | W | C ]
  3805. #### Parameters
  3806. - `X` - Flag to go back to the X axis origin
  3807. - `Y` - Flag to go back to the Y axis origin
  3808. - `Z` - Flag to go back to the Z axis origin
  3809. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  3810. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  3811. */
  3812. case 28:
  3813. {
  3814. long home_x_value = 0;
  3815. long home_y_value = 0;
  3816. long home_z_value = 0;
  3817. // Which axes should be homed?
  3818. bool home_x = code_seen(axis_codes[X_AXIS]);
  3819. home_x_value = code_value_long();
  3820. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3821. home_y_value = code_value_long();
  3822. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3823. home_z_value = code_value_long();
  3824. bool without_mbl = code_seen('W');
  3825. // calibrate?
  3826. #ifdef TMC2130
  3827. bool calib = code_seen('C');
  3828. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  3829. #else
  3830. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  3831. #endif //TMC2130
  3832. if ((home_x || home_y || without_mbl || home_z) == false) {
  3833. // Push the commands to the front of the message queue in the reverse order!
  3834. // There shall be always enough space reserved for these commands.
  3835. goto case_G80;
  3836. }
  3837. break;
  3838. }
  3839. #ifdef ENABLE_AUTO_BED_LEVELING
  3840. /*!
  3841. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  3842. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3843. See `G81`
  3844. */
  3845. case 29:
  3846. {
  3847. #if Z_MIN_PIN == -1
  3848. #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."
  3849. #endif
  3850. // Prevent user from running a G29 without first homing in X and Y
  3851. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  3852. {
  3853. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  3854. SERIAL_ECHO_START;
  3855. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  3856. break; // abort G29, since we don't know where we are
  3857. }
  3858. st_synchronize();
  3859. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  3860. //vector_3 corrected_position = plan_get_position_mm();
  3861. //corrected_position.debug("position before G29");
  3862. plan_bed_level_matrix.set_to_identity();
  3863. vector_3 uncorrected_position = plan_get_position();
  3864. //uncorrected_position.debug("position durring G29");
  3865. current_position[X_AXIS] = uncorrected_position.x;
  3866. current_position[Y_AXIS] = uncorrected_position.y;
  3867. current_position[Z_AXIS] = uncorrected_position.z;
  3868. plan_set_position_curposXYZE();
  3869. int l_feedmultiply = setup_for_endstop_move();
  3870. feedrate = homing_feedrate[Z_AXIS];
  3871. #ifdef AUTO_BED_LEVELING_GRID
  3872. // probe at the points of a lattice grid
  3873. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3874. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3875. // solve the plane equation ax + by + d = z
  3876. // A is the matrix with rows [x y 1] for all the probed points
  3877. // B is the vector of the Z positions
  3878. // 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
  3879. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3880. // "A" matrix of the linear system of equations
  3881. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  3882. // "B" vector of Z points
  3883. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  3884. int probePointCounter = 0;
  3885. bool zig = true;
  3886. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  3887. {
  3888. int xProbe, xInc;
  3889. if (zig)
  3890. {
  3891. xProbe = LEFT_PROBE_BED_POSITION;
  3892. //xEnd = RIGHT_PROBE_BED_POSITION;
  3893. xInc = xGridSpacing;
  3894. zig = false;
  3895. } else // zag
  3896. {
  3897. xProbe = RIGHT_PROBE_BED_POSITION;
  3898. //xEnd = LEFT_PROBE_BED_POSITION;
  3899. xInc = -xGridSpacing;
  3900. zig = true;
  3901. }
  3902. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  3903. {
  3904. float z_before;
  3905. if (probePointCounter == 0)
  3906. {
  3907. // raise before probing
  3908. z_before = Z_RAISE_BEFORE_PROBING;
  3909. } else
  3910. {
  3911. // raise extruder
  3912. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  3913. }
  3914. float measured_z = probe_pt(xProbe, yProbe, z_before);
  3915. eqnBVector[probePointCounter] = measured_z;
  3916. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  3917. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  3918. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  3919. probePointCounter++;
  3920. xProbe += xInc;
  3921. }
  3922. }
  3923. clean_up_after_endstop_move(l_feedmultiply);
  3924. // solve lsq problem
  3925. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  3926. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3927. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  3928. SERIAL_PROTOCOLPGM(" b: ");
  3929. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  3930. SERIAL_PROTOCOLPGM(" d: ");
  3931. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  3932. set_bed_level_equation_lsq(plane_equation_coefficients);
  3933. free(plane_equation_coefficients);
  3934. #else // AUTO_BED_LEVELING_GRID not defined
  3935. // Probe at 3 arbitrary points
  3936. // probe 1
  3937. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  3938. // probe 2
  3939. 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);
  3940. // probe 3
  3941. 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);
  3942. clean_up_after_endstop_move(l_feedmultiply);
  3943. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  3944. #endif // AUTO_BED_LEVELING_GRID
  3945. st_synchronize();
  3946. // The following code correct the Z height difference from z-probe position and hotend tip position.
  3947. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  3948. // When the bed is uneven, this height must be corrected.
  3949. 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)
  3950. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  3951. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3952. z_tmp = current_position[Z_AXIS];
  3953. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  3954. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  3955. plan_set_position_curposXYZE();
  3956. }
  3957. break;
  3958. #ifndef Z_PROBE_SLED
  3959. /*!
  3960. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  3961. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3962. */
  3963. case 30:
  3964. {
  3965. st_synchronize();
  3966. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3967. int l_feedmultiply = setup_for_endstop_move();
  3968. feedrate = homing_feedrate[Z_AXIS];
  3969. run_z_probe();
  3970. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  3971. SERIAL_PROTOCOLPGM(" X: ");
  3972. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3973. SERIAL_PROTOCOLPGM(" Y: ");
  3974. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3975. SERIAL_PROTOCOLPGM(" Z: ");
  3976. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3977. SERIAL_PROTOCOLPGM("\n");
  3978. clean_up_after_endstop_move(l_feedmultiply);
  3979. }
  3980. break;
  3981. #else
  3982. /*!
  3983. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  3984. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3985. */
  3986. case 31:
  3987. dock_sled(true);
  3988. break;
  3989. /*!
  3990. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  3991. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3992. */
  3993. case 32:
  3994. dock_sled(false);
  3995. break;
  3996. #endif // Z_PROBE_SLED
  3997. #endif // ENABLE_AUTO_BED_LEVELING
  3998. #ifdef MESH_BED_LEVELING
  3999. /*!
  4000. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4001. Sensor must be over the bed.
  4002. The maximum travel distance before an error is triggered is 10mm.
  4003. */
  4004. case 30:
  4005. {
  4006. st_synchronize();
  4007. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4008. int l_feedmultiply = setup_for_endstop_move();
  4009. feedrate = homing_feedrate[Z_AXIS];
  4010. find_bed_induction_sensor_point_z(-10.f, 3);
  4011. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4012. clean_up_after_endstop_move(l_feedmultiply);
  4013. }
  4014. break;
  4015. /*!
  4016. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4017. Show/print PINDA temperature interpolating.
  4018. */
  4019. case 75:
  4020. {
  4021. for (int i = 40; i <= 110; i++)
  4022. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4023. }
  4024. break;
  4025. /*!
  4026. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4027. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4028. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4029. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4030. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4031. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4032. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4033. #### Example
  4034. ```
  4035. G76
  4036. echo PINDA probe calibration start
  4037. echo start temperature: 35.0°
  4038. echo ...
  4039. echo PINDA temperature -- Z shift (mm): 0.---
  4040. ```
  4041. */
  4042. case 76:
  4043. {
  4044. #ifdef PINDA_THERMISTOR
  4045. if (!has_temperature_compensation())
  4046. {
  4047. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4048. break;
  4049. }
  4050. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4051. //we need to know accurate position of first calibration point
  4052. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4053. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first."));
  4054. break;
  4055. }
  4056. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4057. {
  4058. // We don't know where we are! HOME!
  4059. // Push the commands to the front of the message queue in the reverse order!
  4060. // There shall be always enough space reserved for these commands.
  4061. repeatcommand_front(); // repeat G76 with all its parameters
  4062. enquecommand_front_P((PSTR("G28 W0")));
  4063. break;
  4064. }
  4065. 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
  4066. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  4067. if (result)
  4068. {
  4069. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4070. plan_buffer_line_curposXYZE(3000 / 60);
  4071. current_position[Z_AXIS] = 50;
  4072. current_position[Y_AXIS] = 180;
  4073. plan_buffer_line_curposXYZE(3000 / 60);
  4074. st_synchronize();
  4075. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4076. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4077. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4078. plan_buffer_line_curposXYZE(3000 / 60);
  4079. st_synchronize();
  4080. gcode_G28(false, false, true);
  4081. }
  4082. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4083. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4084. current_position[Z_AXIS] = 100;
  4085. plan_buffer_line_curposXYZE(3000 / 60);
  4086. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4087. lcd_temp_cal_show_result(false);
  4088. break;
  4089. }
  4090. }
  4091. lcd_update_enable(true);
  4092. KEEPALIVE_STATE(NOT_BUSY); //no need to print busy messages as we print current temperatures periodicaly
  4093. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4094. float zero_z;
  4095. int z_shift = 0; //unit: steps
  4096. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4097. if (start_temp < 35) start_temp = 35;
  4098. if (start_temp < current_temperature_pinda) start_temp += 5;
  4099. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4100. // setTargetHotend(200, 0);
  4101. setTargetBed(70 + (start_temp - 30));
  4102. custom_message_type = CustomMsg::TempCal;
  4103. custom_message_state = 1;
  4104. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  4105. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4106. plan_buffer_line_curposXYZE(3000 / 60);
  4107. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4108. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4109. plan_buffer_line_curposXYZE(3000 / 60);
  4110. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4111. plan_buffer_line_curposXYZE(3000 / 60);
  4112. st_synchronize();
  4113. while (current_temperature_pinda < start_temp)
  4114. {
  4115. delay_keep_alive(1000);
  4116. serialecho_temperatures();
  4117. }
  4118. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4119. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4120. plan_buffer_line_curposXYZE(3000 / 60);
  4121. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4122. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4123. plan_buffer_line_curposXYZE(3000 / 60);
  4124. st_synchronize();
  4125. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4126. if (find_z_result == false) {
  4127. lcd_temp_cal_show_result(find_z_result);
  4128. break;
  4129. }
  4130. zero_z = current_position[Z_AXIS];
  4131. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4132. int i = -1; for (; i < 5; i++)
  4133. {
  4134. float temp = (40 + i * 5);
  4135. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4136. if (i >= 0) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  4137. if (start_temp <= temp) break;
  4138. }
  4139. for (i++; i < 5; i++)
  4140. {
  4141. float temp = (40 + i * 5);
  4142. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4143. custom_message_state = i + 2;
  4144. setTargetBed(50 + 10 * (temp - 30) / 5);
  4145. // setTargetHotend(255, 0);
  4146. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4147. plan_buffer_line_curposXYZE(3000 / 60);
  4148. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4149. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4150. plan_buffer_line_curposXYZE(3000 / 60);
  4151. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4152. plan_buffer_line_curposXYZE(3000 / 60);
  4153. st_synchronize();
  4154. while (current_temperature_pinda < temp)
  4155. {
  4156. delay_keep_alive(1000);
  4157. serialecho_temperatures();
  4158. }
  4159. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4160. plan_buffer_line_curposXYZE(3000 / 60);
  4161. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4162. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4163. plan_buffer_line_curposXYZE(3000 / 60);
  4164. st_synchronize();
  4165. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4166. if (find_z_result == false) {
  4167. lcd_temp_cal_show_result(find_z_result);
  4168. break;
  4169. }
  4170. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4171. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4172. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  4173. }
  4174. lcd_temp_cal_show_result(true);
  4175. #else //PINDA_THERMISTOR
  4176. setTargetBed(PINDA_MIN_T);
  4177. float zero_z;
  4178. int z_shift = 0; //unit: steps
  4179. int t_c; // temperature
  4180. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4181. // We don't know where we are! HOME!
  4182. // Push the commands to the front of the message queue in the reverse order!
  4183. // There shall be always enough space reserved for these commands.
  4184. repeatcommand_front(); // repeat G76 with all its parameters
  4185. enquecommand_front_P((PSTR("G28 W0")));
  4186. break;
  4187. }
  4188. puts_P(_N("PINDA probe calibration start"));
  4189. custom_message_type = CustomMsg::TempCal;
  4190. custom_message_state = 1;
  4191. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  4192. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4193. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4194. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4195. plan_buffer_line_curposXYZE(3000 / 60);
  4196. st_synchronize();
  4197. while (abs(degBed() - PINDA_MIN_T) > 1) {
  4198. delay_keep_alive(1000);
  4199. serialecho_temperatures();
  4200. }
  4201. //enquecommand_P(PSTR("M190 S50"));
  4202. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4203. delay_keep_alive(1000);
  4204. serialecho_temperatures();
  4205. }
  4206. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4207. current_position[Z_AXIS] = 5;
  4208. plan_buffer_line_curposXYZE(3000 / 60);
  4209. current_position[X_AXIS] = BED_X0;
  4210. current_position[Y_AXIS] = BED_Y0;
  4211. plan_buffer_line_curposXYZE(3000 / 60);
  4212. st_synchronize();
  4213. find_bed_induction_sensor_point_z(-1.f);
  4214. zero_z = current_position[Z_AXIS];
  4215. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4216. for (int i = 0; i<5; i++) {
  4217. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4218. custom_message_state = i + 2;
  4219. t_c = 60 + i * 10;
  4220. setTargetBed(t_c);
  4221. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4222. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4223. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4224. plan_buffer_line_curposXYZE(3000 / 60);
  4225. st_synchronize();
  4226. while (degBed() < t_c) {
  4227. delay_keep_alive(1000);
  4228. serialecho_temperatures();
  4229. }
  4230. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4231. delay_keep_alive(1000);
  4232. serialecho_temperatures();
  4233. }
  4234. current_position[Z_AXIS] = 5;
  4235. plan_buffer_line_curposXYZE(3000 / 60);
  4236. current_position[X_AXIS] = BED_X0;
  4237. current_position[Y_AXIS] = BED_Y0;
  4238. plan_buffer_line_curposXYZE(3000 / 60);
  4239. st_synchronize();
  4240. find_bed_induction_sensor_point_z(-1.f);
  4241. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4242. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4243. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i*2, &z_shift);
  4244. }
  4245. custom_message_type = CustomMsg::Status;
  4246. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4247. puts_P(_N("Temperature calibration done."));
  4248. disable_x();
  4249. disable_y();
  4250. disable_z();
  4251. disable_e0();
  4252. disable_e1();
  4253. disable_e2();
  4254. setTargetBed(0); //set bed target temperature back to 0
  4255. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TEMP_CALIBRATION_DONE));
  4256. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4257. lcd_update_enable(true);
  4258. lcd_update(2);
  4259. #endif //PINDA_THERMISTOR
  4260. }
  4261. break;
  4262. /*!
  4263. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4264. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4265. #### Usage
  4266. G80 [ N | R | V | L | R | F | B ]
  4267. #### Parameters
  4268. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4269. - `R` - Probe retries. Default 3 max. 10
  4270. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4271. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4272. #### Additional Parameters
  4273. - `L` - Left Bed Level correct value in um.
  4274. - `R` - Right Bed Level correct value in um.
  4275. - `F` - Front Bed Level correct value in um.
  4276. - `B` - Back Bed Level correct value in um.
  4277. */
  4278. /*
  4279. * Probes a grid and produces a mesh to compensate for variable bed height
  4280. * The S0 report the points as below
  4281. * +----> X-axis
  4282. * |
  4283. * |
  4284. * v Y-axis
  4285. */
  4286. case 80:
  4287. #ifdef MK1BP
  4288. break;
  4289. #endif //MK1BP
  4290. case_G80:
  4291. {
  4292. mesh_bed_leveling_flag = true;
  4293. #ifndef PINDA_THERMISTOR
  4294. static bool run = false; // thermistor-less PINDA temperature compensation is running
  4295. #endif // ndef PINDA_THERMISTOR
  4296. #ifdef SUPPORT_VERBOSITY
  4297. int8_t verbosity_level = 0;
  4298. if (code_seen('V')) {
  4299. // Just 'V' without a number counts as V1.
  4300. char c = strchr_pointer[1];
  4301. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4302. }
  4303. #endif //SUPPORT_VERBOSITY
  4304. // Firstly check if we know where we are
  4305. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4306. // We don't know where we are! HOME!
  4307. // Push the commands to the front of the message queue in the reverse order!
  4308. // There shall be always enough space reserved for these commands.
  4309. repeatcommand_front(); // repeat G80 with all its parameters
  4310. enquecommand_front_P((PSTR("G28 W0")));
  4311. break;
  4312. }
  4313. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  4314. if (code_seen('N')) {
  4315. nMeasPoints = code_value_uint8();
  4316. if (nMeasPoints != 7) {
  4317. nMeasPoints = 3;
  4318. }
  4319. }
  4320. else {
  4321. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  4322. }
  4323. uint8_t nProbeRetry = 3;
  4324. if (code_seen('R')) {
  4325. nProbeRetry = code_value_uint8();
  4326. if (nProbeRetry > 10) {
  4327. nProbeRetry = 10;
  4328. }
  4329. }
  4330. else {
  4331. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  4332. }
  4333. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  4334. #ifndef PINDA_THERMISTOR
  4335. if (run == false && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50)
  4336. {
  4337. temp_compensation_start();
  4338. run = true;
  4339. repeatcommand_front(); // repeat G80 with all its parameters
  4340. enquecommand_front_P((PSTR("G28 W0")));
  4341. break;
  4342. }
  4343. run = false;
  4344. #endif //PINDA_THERMISTOR
  4345. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  4346. CustomMsg custom_message_type_old = custom_message_type;
  4347. unsigned int custom_message_state_old = custom_message_state;
  4348. custom_message_type = CustomMsg::MeshBedLeveling;
  4349. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  4350. lcd_update(1);
  4351. mbl.reset(); //reset mesh bed leveling
  4352. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  4353. // consumed during the first movements following this statement.
  4354. babystep_undo();
  4355. // Cycle through all points and probe them
  4356. // First move up. During this first movement, the babystepping will be reverted.
  4357. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4358. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  4359. // The move to the first calibration point.
  4360. current_position[X_AXIS] = BED_X0;
  4361. current_position[Y_AXIS] = BED_Y0;
  4362. #ifdef SUPPORT_VERBOSITY
  4363. if (verbosity_level >= 1)
  4364. {
  4365. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4366. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  4367. }
  4368. #else //SUPPORT_VERBOSITY
  4369. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4370. #endif //SUPPORT_VERBOSITY
  4371. plan_buffer_line_curposXYZE(homing_feedrate[X_AXIS] / 30);
  4372. // Wait until the move is finished.
  4373. st_synchronize();
  4374. uint8_t mesh_point = 0; //index number of calibration point
  4375. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  4376. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  4377. 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)
  4378. #ifdef SUPPORT_VERBOSITY
  4379. if (verbosity_level >= 1) {
  4380. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  4381. }
  4382. #endif // SUPPORT_VERBOSITY
  4383. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  4384. while (mesh_point != nMeasPoints * nMeasPoints) {
  4385. // Get coords of a measuring point.
  4386. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  4387. uint8_t iy = mesh_point / nMeasPoints;
  4388. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  4389. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  4390. custom_message_state--;
  4391. mesh_point++;
  4392. continue; //skip
  4393. }*/
  4394. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  4395. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  4396. {
  4397. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  4398. }
  4399. float z0 = 0.f;
  4400. if (has_z && (mesh_point > 0)) {
  4401. uint16_t z_offset_u = 0;
  4402. if (nMeasPoints == 7) {
  4403. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  4404. }
  4405. else {
  4406. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  4407. }
  4408. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  4409. #ifdef SUPPORT_VERBOSITY
  4410. if (verbosity_level >= 1) {
  4411. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  4412. }
  4413. #endif // SUPPORT_VERBOSITY
  4414. }
  4415. // Move Z up to MESH_HOME_Z_SEARCH.
  4416. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4417. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  4418. float init_z_bckp = current_position[Z_AXIS];
  4419. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  4420. st_synchronize();
  4421. // Move to XY position of the sensor point.
  4422. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  4423. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  4424. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  4425. #ifdef SUPPORT_VERBOSITY
  4426. if (verbosity_level >= 1) {
  4427. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4428. SERIAL_PROTOCOL(mesh_point);
  4429. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  4430. }
  4431. #else //SUPPORT_VERBOSITY
  4432. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4433. #endif // SUPPORT_VERBOSITY
  4434. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  4435. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  4436. st_synchronize();
  4437. // Go down until endstop is hit
  4438. const float Z_CALIBRATION_THRESHOLD = 1.f;
  4439. 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
  4440. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  4441. break;
  4442. }
  4443. 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.
  4444. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  4445. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4446. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  4447. st_synchronize();
  4448. 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
  4449. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  4450. break;
  4451. }
  4452. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  4453. printf_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken.\n"));
  4454. break;
  4455. }
  4456. }
  4457. 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
  4458. printf_P(PSTR("Bed leveling failed. Sensor triggered too high.\n"));
  4459. break;
  4460. }
  4461. #ifdef SUPPORT_VERBOSITY
  4462. if (verbosity_level >= 10) {
  4463. SERIAL_ECHOPGM("X: ");
  4464. MYSERIAL.print(current_position[X_AXIS], 5);
  4465. SERIAL_ECHOLNPGM("");
  4466. SERIAL_ECHOPGM("Y: ");
  4467. MYSERIAL.print(current_position[Y_AXIS], 5);
  4468. SERIAL_PROTOCOLPGM("\n");
  4469. }
  4470. #endif // SUPPORT_VERBOSITY
  4471. float offset_z = 0;
  4472. #ifdef PINDA_THERMISTOR
  4473. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  4474. #endif //PINDA_THERMISTOR
  4475. // #ifdef SUPPORT_VERBOSITY
  4476. /* if (verbosity_level >= 1)
  4477. {
  4478. SERIAL_ECHOPGM("mesh bed leveling: ");
  4479. MYSERIAL.print(current_position[Z_AXIS], 5);
  4480. SERIAL_ECHOPGM(" offset: ");
  4481. MYSERIAL.print(offset_z, 5);
  4482. SERIAL_ECHOLNPGM("");
  4483. }*/
  4484. // #endif // SUPPORT_VERBOSITY
  4485. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  4486. custom_message_state--;
  4487. mesh_point++;
  4488. lcd_update(1);
  4489. }
  4490. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4491. #ifdef SUPPORT_VERBOSITY
  4492. if (verbosity_level >= 20) {
  4493. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  4494. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  4495. MYSERIAL.print(current_position[Z_AXIS], 5);
  4496. }
  4497. #endif // SUPPORT_VERBOSITY
  4498. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  4499. st_synchronize();
  4500. if (mesh_point != nMeasPoints * nMeasPoints) {
  4501. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  4502. bool bState;
  4503. do { // repeat until Z-leveling o.k.
  4504. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ..."));
  4505. #ifdef TMC2130
  4506. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  4507. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  4508. #else // TMC2130
  4509. lcd_wait_for_click_delay(0); // ~ no timeout
  4510. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  4511. #endif // TMC2130
  4512. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  4513. bState=enable_z_endstop(false);
  4514. current_position[Z_AXIS] -= 1;
  4515. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  4516. st_synchronize();
  4517. enable_z_endstop(true);
  4518. #ifdef TMC2130
  4519. tmc2130_home_enter(Z_AXIS_MASK);
  4520. #endif // TMC2130
  4521. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4522. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  4523. st_synchronize();
  4524. #ifdef TMC2130
  4525. tmc2130_home_exit();
  4526. #endif // TMC2130
  4527. enable_z_endstop(bState);
  4528. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  4529. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  4530. custom_message_type=CustomMsg::Status; // display / status-line recovery
  4531. lcd_update_enable(true); // display / status-line recovery
  4532. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  4533. repeatcommand_front(); // re-run (i.e. of "G80")
  4534. break;
  4535. }
  4536. clean_up_after_endstop_move(l_feedmultiply);
  4537. // SERIAL_ECHOLNPGM("clean up finished ");
  4538. #ifndef PINDA_THERMISTOR
  4539. if(temp_cal_active == true && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  4540. #endif
  4541. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  4542. // SERIAL_ECHOLNPGM("babystep applied");
  4543. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  4544. #ifdef SUPPORT_VERBOSITY
  4545. if (verbosity_level >= 1) {
  4546. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  4547. }
  4548. #endif // SUPPORT_VERBOSITY
  4549. for (uint8_t i = 0; i < 4; ++i) {
  4550. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  4551. long correction = 0;
  4552. if (code_seen(codes[i]))
  4553. correction = code_value_long();
  4554. else if (eeprom_bed_correction_valid) {
  4555. unsigned char *addr = (i < 2) ?
  4556. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  4557. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  4558. correction = eeprom_read_int8(addr);
  4559. }
  4560. if (correction == 0)
  4561. continue;
  4562. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  4563. SERIAL_ERROR_START;
  4564. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  4565. SERIAL_ECHO(correction);
  4566. SERIAL_ECHOLNPGM(" microns");
  4567. }
  4568. else {
  4569. float offset = float(correction) * 0.001f;
  4570. switch (i) {
  4571. case 0:
  4572. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4573. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  4574. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  4575. }
  4576. }
  4577. break;
  4578. case 1:
  4579. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4580. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  4581. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  4582. }
  4583. }
  4584. break;
  4585. case 2:
  4586. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4587. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4588. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  4589. }
  4590. }
  4591. break;
  4592. case 3:
  4593. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4594. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  4595. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  4596. }
  4597. }
  4598. break;
  4599. }
  4600. }
  4601. }
  4602. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  4603. if (nMeasPoints == 3) {
  4604. 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)
  4605. }
  4606. /*
  4607. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4608. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4609. SERIAL_PROTOCOLPGM(",");
  4610. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4611. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4612. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4613. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4614. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4615. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4616. SERIAL_PROTOCOLPGM(" ");
  4617. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4618. }
  4619. SERIAL_PROTOCOLPGM("\n");
  4620. }
  4621. */
  4622. if (nMeasPoints == 7 && magnet_elimination) {
  4623. mbl_interpolation(nMeasPoints);
  4624. }
  4625. /*
  4626. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4627. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4628. SERIAL_PROTOCOLPGM(",");
  4629. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4630. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4631. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4632. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4633. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4634. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4635. SERIAL_PROTOCOLPGM(" ");
  4636. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4637. }
  4638. SERIAL_PROTOCOLPGM("\n");
  4639. }
  4640. */
  4641. // SERIAL_ECHOLNPGM("Upsample finished");
  4642. mbl.active = 1; //activate mesh bed leveling
  4643. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  4644. go_home_with_z_lift();
  4645. // SERIAL_ECHOLNPGM("Go home finished");
  4646. //unretract (after PINDA preheat retraction)
  4647. if ((degHotend(active_extruder) > EXTRUDE_MINTEMP) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  4648. current_position[E_AXIS] += default_retraction;
  4649. plan_buffer_line_curposXYZE(400);
  4650. }
  4651. KEEPALIVE_STATE(NOT_BUSY);
  4652. // Restore custom message state
  4653. lcd_setstatuspgm(_T(WELCOME_MSG));
  4654. custom_message_type = custom_message_type_old;
  4655. custom_message_state = custom_message_state_old;
  4656. mesh_bed_leveling_flag = false;
  4657. mesh_bed_run_from_menu = false;
  4658. lcd_update(2);
  4659. }
  4660. break;
  4661. /*!
  4662. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4663. Prints mesh bed leveling status and bed profile if activated.
  4664. */
  4665. case 81:
  4666. if (mbl.active) {
  4667. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4668. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4669. SERIAL_PROTOCOL(',');
  4670. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4671. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4672. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4673. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4674. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4675. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4676. SERIAL_PROTOCOLPGM(" ");
  4677. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4678. }
  4679. SERIAL_PROTOCOLLN();
  4680. }
  4681. }
  4682. else
  4683. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4684. break;
  4685. #if 0
  4686. /*!
  4687. ### G82: Single Z probe at current location - Not active <a href="https://reprap.org/wiki/G-code#G82:_Single_Z_probe_at_current_location">G82: Single Z probe at current location</a>
  4688. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4689. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4690. */
  4691. case 82:
  4692. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4693. int l_feedmultiply = setup_for_endstop_move();
  4694. find_bed_induction_sensor_point_z();
  4695. clean_up_after_endstop_move(l_feedmultiply);
  4696. SERIAL_PROTOCOLPGM("Bed found at: ");
  4697. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4698. SERIAL_PROTOCOLPGM("\n");
  4699. break;
  4700. /*!
  4701. ### G83: Babystep in Z and store to EEPROM - Not active <a href="https://reprap.org/wiki/G-code#G83:_Babystep_in_Z_and_store_to_EEPROM">G83: Babystep in Z and store to EEPROM</a>
  4702. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4703. */
  4704. case 83:
  4705. {
  4706. int babystepz = code_seen('S') ? code_value() : 0;
  4707. int BabyPosition = code_seen('P') ? code_value() : 0;
  4708. if (babystepz != 0) {
  4709. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4710. // Is the axis indexed starting with zero or one?
  4711. if (BabyPosition > 4) {
  4712. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4713. }else{
  4714. // Save it to the eeprom
  4715. babystepLoadZ = babystepz;
  4716. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoadZ);
  4717. // adjust the Z
  4718. babystepsTodoZadd(babystepLoadZ);
  4719. }
  4720. }
  4721. }
  4722. break;
  4723. /*!
  4724. ### G84: UNDO Babystep Z (move Z axis back) - Not active <a href="https://reprap.org/wiki/G-code#G84:_UNDO_Babystep_Z_.28move_Z_axis_back.29">G84: UNDO Babystep Z (move Z axis back)</a>
  4725. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4726. */
  4727. case 84:
  4728. babystepsTodoZsubtract(babystepLoadZ);
  4729. // babystepLoadZ = 0;
  4730. break;
  4731. /*!
  4732. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4733. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4734. */
  4735. case 85:
  4736. lcd_pick_babystep();
  4737. break;
  4738. #endif
  4739. /*!
  4740. ### G86 - Disable babystep correction after home <a href="https://reprap.org/wiki/G-code#G86:_Disable_babystep_correction_after_home">G86: Disable babystep correction after home</a>
  4741. This G-code will be performed at the start of a calibration script.
  4742. (Prusa3D specific)
  4743. */
  4744. case 86:
  4745. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4746. break;
  4747. /*!
  4748. ### G87 - Enable babystep correction after home <a href="https://reprap.org/wiki/G-code#G87:_Enable_babystep_correction_after_home">G87: Enable babystep correction after home</a>
  4749. This G-code will be performed at the end of a calibration script.
  4750. (Prusa3D specific)
  4751. */
  4752. case 87:
  4753. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4754. break;
  4755. /*!
  4756. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4757. Currently has no effect.
  4758. */
  4759. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4760. case 88:
  4761. break;
  4762. #endif // ENABLE_MESH_BED_LEVELING
  4763. /*!
  4764. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4765. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4766. */
  4767. case 90: {
  4768. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4769. }
  4770. break;
  4771. /*!
  4772. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4773. All coordinates from now on are relative to the last position. E axis is left intact.
  4774. */
  4775. case 91: {
  4776. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4777. }
  4778. break;
  4779. /*!
  4780. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4781. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4782. If a parameter is omitted, that axis will not be affected.
  4783. If `X`, `Y`, or `Z` axis are specified, the move afterwards might stutter because of Mesh Bed Leveling. `E` axis is not affected if the target position is 0 (`G92 E0`).
  4784. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4785. #### Usage
  4786. G92 [ X | Y | Z | E ]
  4787. #### Parameters
  4788. - `X` - new X axis position
  4789. - `Y` - new Y axis position
  4790. - `Z` - new Z axis position
  4791. - `E` - new extruder position
  4792. */
  4793. case 92: {
  4794. gcode_G92();
  4795. }
  4796. break;
  4797. /*!
  4798. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4799. Enable Prusa-specific Farm functions and g-code.
  4800. See Internal Prusa commands.
  4801. */
  4802. case 98:
  4803. farm_mode = 1;
  4804. PingTime = _millis();
  4805. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4806. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  4807. SilentModeMenu = SILENT_MODE_OFF;
  4808. eeprom_update_byte((unsigned char *)EEPROM_SILENT, SilentModeMenu);
  4809. fCheckModeInit(); // alternatively invoke printer reset
  4810. break;
  4811. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4812. Disables Prusa-specific Farm functions and g-code.
  4813. */
  4814. case 99:
  4815. farm_mode = 0;
  4816. lcd_printer_connected();
  4817. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4818. lcd_update(2);
  4819. fCheckModeInit(); // alternatively invoke printer reset
  4820. break;
  4821. default:
  4822. printf_P(PSTR("Unknown G code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4823. }
  4824. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4825. gcode_in_progress = 0;
  4826. } // end if(code_seen('G'))
  4827. /*!
  4828. ### End of G-Codes
  4829. */
  4830. /*!
  4831. ---------------------------------------------------------------------------------
  4832. # M Commands
  4833. */
  4834. else if(code_seen('M'))
  4835. {
  4836. int index;
  4837. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4838. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4839. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4840. printf_P(PSTR("Invalid M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4841. } else
  4842. {
  4843. mcode_in_progress = (int)code_value();
  4844. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4845. switch(mcode_in_progress)
  4846. {
  4847. /*!
  4848. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  4849. */
  4850. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  4851. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  4852. {
  4853. char *src = strchr_pointer + 2;
  4854. codenum = 0;
  4855. bool hasP = false, hasS = false;
  4856. if (code_seen('P')) {
  4857. codenum = code_value(); // milliseconds to wait
  4858. hasP = codenum > 0;
  4859. }
  4860. if (code_seen('S')) {
  4861. codenum = code_value() * 1000; // seconds to wait
  4862. hasS = codenum > 0;
  4863. }
  4864. starpos = strchr(src, '*');
  4865. if (starpos != NULL) *(starpos) = '\0';
  4866. while (*src == ' ') ++src;
  4867. if (!hasP && !hasS && *src != '\0') {
  4868. lcd_setstatus(src);
  4869. } else {
  4870. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT
  4871. }
  4872. lcd_ignore_click(); //call lcd_ignore_click aslo for else ???
  4873. st_synchronize();
  4874. previous_millis_cmd = _millis();
  4875. if (codenum > 0){
  4876. codenum += _millis(); // keep track of when we started waiting
  4877. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4878. while(_millis() < codenum && !lcd_clicked()){
  4879. manage_heater();
  4880. manage_inactivity(true);
  4881. lcd_update(0);
  4882. }
  4883. KEEPALIVE_STATE(IN_HANDLER);
  4884. lcd_ignore_click(false);
  4885. }else{
  4886. marlin_wait_for_click();
  4887. }
  4888. if (IS_SD_PRINTING)
  4889. LCD_MESSAGERPGM(_T(MSG_RESUMING_PRINT));
  4890. else
  4891. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  4892. }
  4893. break;
  4894. /*!
  4895. ### M17 - Enable all axes <a href="https://reprap.org/wiki/G-code#M17:_Enable.2FPower_all_stepper_motors">M17: Enable/Power all stepper motors</a>
  4896. */
  4897. case 17:
  4898. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE
  4899. enable_x();
  4900. enable_y();
  4901. enable_z();
  4902. enable_e0();
  4903. enable_e1();
  4904. enable_e2();
  4905. break;
  4906. #ifdef SDSUPPORT
  4907. /*!
  4908. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4909. */
  4910. case 20:
  4911. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4912. card.ls();
  4913. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4914. break;
  4915. /*!
  4916. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4917. */
  4918. case 21:
  4919. card.initsd();
  4920. break;
  4921. /*!
  4922. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4923. */
  4924. case 22:
  4925. card.release();
  4926. break;
  4927. /*!
  4928. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4929. #### Usage
  4930. M23 [filename]
  4931. */
  4932. case 23:
  4933. starpos = (strchr(strchr_pointer + 4,'*'));
  4934. if(starpos!=NULL)
  4935. *(starpos)='\0';
  4936. card.openFile(strchr_pointer + 4,true);
  4937. break;
  4938. /*!
  4939. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4940. */
  4941. case 24:
  4942. if (isPrintPaused)
  4943. lcd_resume_print();
  4944. else
  4945. {
  4946. if (!card.get_sdpos())
  4947. {
  4948. // A new print has started from scratch, reset stats
  4949. failstats_reset_print();
  4950. #ifndef LA_NOCOMPAT
  4951. la10c_reset();
  4952. #endif
  4953. }
  4954. card.startFileprint();
  4955. starttime=_millis();
  4956. }
  4957. break;
  4958. /*!
  4959. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4960. Set position in SD card file to index in bytes.
  4961. This command is expected to be called after M23 and before M24.
  4962. Otherwise effect of this command is undefined.
  4963. #### Usage
  4964. M26 [ S ]
  4965. #### Parameters
  4966. - `S` - Index in bytes
  4967. */
  4968. case 26:
  4969. if(card.cardOK && code_seen('S')) {
  4970. long index = code_value_long();
  4971. card.setIndex(index);
  4972. // We don't disable interrupt during update of sdpos_atomic
  4973. // as we expect, that SD card print is not active in this moment
  4974. sdpos_atomic = index;
  4975. }
  4976. break;
  4977. /*!
  4978. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4979. */
  4980. case 27:
  4981. card.getStatus();
  4982. break;
  4983. /*!
  4984. ### M28 - Start SD write <a href="https://reprap.org/wiki/G-code#M28:_Begin_write_to_SD_card">M28: Begin write to SD card</a>
  4985. */
  4986. case 28:
  4987. starpos = (strchr(strchr_pointer + 4,'*'));
  4988. if(starpos != NULL){
  4989. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4990. strchr_pointer = strchr(npos,' ') + 1;
  4991. *(starpos) = '\0';
  4992. }
  4993. card.openFile(strchr_pointer+4,false);
  4994. break;
  4995. /*! ### M29 - Stop SD write <a href="https://reprap.org/wiki/G-code#M29:_Stop_writing_to_SD_card">M29: Stop writing to SD card</a>
  4996. Stops writing to the SD file signaling the end of the uploaded file. It is processed very early and it's not written to the card.
  4997. */
  4998. case 29:
  4999. //processed in write to file routine above
  5000. //card,saving = false;
  5001. break;
  5002. /*!
  5003. ### M30 - Delete file <a href="https://reprap.org/wiki/G-code#M30:_Delete_a_file_on_the_SD_card">M30: Delete a file on the SD card</a>
  5004. #### Usage
  5005. M30 [filename]
  5006. */
  5007. case 30:
  5008. if (card.cardOK){
  5009. card.closefile();
  5010. starpos = (strchr(strchr_pointer + 4,'*'));
  5011. if(starpos != NULL){
  5012. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  5013. strchr_pointer = strchr(npos,' ') + 1;
  5014. *(starpos) = '\0';
  5015. }
  5016. card.removeFile(strchr_pointer + 4);
  5017. }
  5018. break;
  5019. /*!
  5020. ### M32 - Select file and start SD print <a href="https://reprap.org/wiki/G-code#M32:_Select_file_and_start_SD_print">M32: Select file and start SD print</a>
  5021. @todo What are the parameters P and S for in M32?
  5022. */
  5023. case 32:
  5024. {
  5025. if(card.sdprinting) {
  5026. st_synchronize();
  5027. }
  5028. starpos = (strchr(strchr_pointer + 4,'*'));
  5029. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  5030. if(namestartpos==NULL)
  5031. {
  5032. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  5033. }
  5034. else
  5035. namestartpos++; //to skip the '!'
  5036. if(starpos!=NULL)
  5037. *(starpos)='\0';
  5038. bool call_procedure=(code_seen('P'));
  5039. if(strchr_pointer>namestartpos)
  5040. call_procedure=false; //false alert, 'P' found within filename
  5041. if( card.cardOK )
  5042. {
  5043. card.openFile(namestartpos,true,!call_procedure);
  5044. if(code_seen('S'))
  5045. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  5046. card.setIndex(code_value_long());
  5047. card.startFileprint();
  5048. if(!call_procedure)
  5049. {
  5050. if(!card.get_sdpos())
  5051. {
  5052. // A new print has started from scratch, reset stats
  5053. failstats_reset_print();
  5054. #ifndef LA_NOCOMPAT
  5055. la10c_reset();
  5056. #endif
  5057. }
  5058. starttime=_millis(); // procedure calls count as normal print time.
  5059. }
  5060. }
  5061. } break;
  5062. /*!
  5063. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  5064. #### Usage
  5065. M928 [filename]
  5066. */
  5067. case 928:
  5068. starpos = (strchr(strchr_pointer + 5,'*'));
  5069. if(starpos != NULL){
  5070. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  5071. strchr_pointer = strchr(npos,' ') + 1;
  5072. *(starpos) = '\0';
  5073. }
  5074. card.openLogFile(strchr_pointer+5);
  5075. break;
  5076. #endif //SDSUPPORT
  5077. /*!
  5078. ### M31 - Report current print time <a href="https://reprap.org/wiki/G-code#M31:_Output_time_since_last_M109_or_SD_card_start_to_serial">M31: Output time since last M109 or SD card start to serial</a>
  5079. */
  5080. case 31: //M31 take time since the start of the SD print or an M109 command
  5081. {
  5082. stoptime=_millis();
  5083. char time[30];
  5084. unsigned long t=(stoptime-starttime)/1000;
  5085. int sec,min;
  5086. min=t/60;
  5087. sec=t%60;
  5088. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  5089. SERIAL_ECHO_START;
  5090. SERIAL_ECHOLN(time);
  5091. lcd_setstatus(time);
  5092. autotempShutdown();
  5093. }
  5094. break;
  5095. /*!
  5096. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  5097. #### Usage
  5098. M42 [ P | S ]
  5099. #### Parameters
  5100. - `P` - Pin number.
  5101. - `S` - Pin value. If the pin is analog, values are from 0 to 255. If the pin is digital, values are from 0 to 1.
  5102. */
  5103. case 42:
  5104. if (code_seen('S'))
  5105. {
  5106. int pin_status = code_value();
  5107. int pin_number = LED_PIN;
  5108. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  5109. pin_number = code_value();
  5110. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  5111. {
  5112. if (sensitive_pins[i] == pin_number)
  5113. {
  5114. pin_number = -1;
  5115. break;
  5116. }
  5117. }
  5118. #if defined(FAN_PIN) && FAN_PIN > -1
  5119. if (pin_number == FAN_PIN)
  5120. fanSpeed = pin_status;
  5121. #endif
  5122. if (pin_number > -1)
  5123. {
  5124. pinMode(pin_number, OUTPUT);
  5125. digitalWrite(pin_number, pin_status);
  5126. analogWrite(pin_number, pin_status);
  5127. }
  5128. }
  5129. break;
  5130. /*!
  5131. ### M44 - Reset the bed skew and offset calibration <a href="https://reprap.org/wiki/G-code#M44:_Reset_the_bed_skew_and_offset_calibration">M44: Reset the bed skew and offset calibration</a>
  5132. */
  5133. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  5134. // Reset the baby step value and the baby step applied flag.
  5135. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  5136. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  5137. // Reset the skew and offset in both RAM and EEPROM.
  5138. reset_bed_offset_and_skew();
  5139. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5140. // the planner will not perform any adjustments in the XY plane.
  5141. // Wait for the motors to stop and update the current position with the absolute values.
  5142. world2machine_revert_to_uncorrected();
  5143. break;
  5144. /*!
  5145. ### M45 - Bed skew and offset with manual Z up <a href="https://reprap.org/wiki/G-code#M45:_Bed_skew_and_offset_with_manual_Z_up">M45: Bed skew and offset with manual Z up</a>
  5146. #### Usage
  5147. M45 [ V ]
  5148. #### Parameters
  5149. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  5150. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  5151. */
  5152. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  5153. {
  5154. int8_t verbosity_level = 0;
  5155. bool only_Z = code_seen('Z');
  5156. #ifdef SUPPORT_VERBOSITY
  5157. if (code_seen('V'))
  5158. {
  5159. // Just 'V' without a number counts as V1.
  5160. char c = strchr_pointer[1];
  5161. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5162. }
  5163. #endif //SUPPORT_VERBOSITY
  5164. gcode_M45(only_Z, verbosity_level);
  5165. }
  5166. break;
  5167. /*!
  5168. ### M46 - Show the assigned IP address <a href="https://reprap.org/wiki/G-code#M46:_Show_the_assigned_IP_address">M46: Show the assigned IP address.</a>
  5169. */
  5170. case 46:
  5171. {
  5172. // M46: Prusa3D: Show the assigned IP address.
  5173. if (card.ToshibaFlashAir_isEnabled()) {
  5174. uint8_t ip[4];
  5175. bool hasIP = card.ToshibaFlashAir_GetIP(ip);
  5176. if (hasIP) {
  5177. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  5178. SERIAL_PROTOCOL(int(ip[0]));
  5179. SERIAL_PROTOCOLPGM(".");
  5180. SERIAL_PROTOCOL(int(ip[1]));
  5181. SERIAL_PROTOCOLPGM(".");
  5182. SERIAL_PROTOCOL(int(ip[2]));
  5183. SERIAL_PROTOCOLPGM(".");
  5184. SERIAL_PROTOCOL(int(ip[3]));
  5185. SERIAL_PROTOCOLPGM("\n");
  5186. } else {
  5187. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  5188. }
  5189. } else {
  5190. SERIAL_PROTOCOLPGM("n/a\n");
  5191. }
  5192. break;
  5193. }
  5194. /*!
  5195. ### M47 - Show end stops dialog on the display <a href="https://reprap.org/wiki/G-code#M47:_Show_end_stops_dialog_on_the_display">M47: Show end stops dialog on the display</a>
  5196. */
  5197. case 47:
  5198. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5199. lcd_diag_show_end_stops();
  5200. KEEPALIVE_STATE(IN_HANDLER);
  5201. break;
  5202. #if 0
  5203. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5204. {
  5205. // Disable the default update procedure of the display. We will do a modal dialog.
  5206. lcd_update_enable(false);
  5207. // Let the planner use the uncorrected coordinates.
  5208. mbl.reset();
  5209. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5210. // the planner will not perform any adjustments in the XY plane.
  5211. // Wait for the motors to stop and update the current position with the absolute values.
  5212. world2machine_revert_to_uncorrected();
  5213. // Move the print head close to the bed.
  5214. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5215. 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);
  5216. st_synchronize();
  5217. // Home in the XY plane.
  5218. set_destination_to_current();
  5219. int l_feedmultiply = setup_for_endstop_move();
  5220. home_xy();
  5221. int8_t verbosity_level = 0;
  5222. if (code_seen('V')) {
  5223. // Just 'V' without a number counts as V1.
  5224. char c = strchr_pointer[1];
  5225. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5226. }
  5227. bool success = scan_bed_induction_points(verbosity_level);
  5228. clean_up_after_endstop_move(l_feedmultiply);
  5229. // Print head up.
  5230. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5231. 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);
  5232. st_synchronize();
  5233. lcd_update_enable(true);
  5234. break;
  5235. }
  5236. #endif
  5237. #ifdef ENABLE_AUTO_BED_LEVELING
  5238. #ifdef Z_PROBE_REPEATABILITY_TEST
  5239. /*!
  5240. ### M48 - Z-Probe repeatability measurement function <a href="https://reprap.org/wiki/G-code#M48:_Measure_Z-Probe_repeatability">M48: Measure Z-Probe repeatability</a>
  5241. This function assumes the bed has been homed. Specifically, that a G28 command as been issued prior to invoking the M48 Z-Probe repeatability measurement function. Any information generated by a prior G29 Bed leveling command will be lost and needs to be regenerated.
  5242. The number of samples will default to 10 if not specified. You can use upper or lower case letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital N for its communication protocol and will get horribly confused if you send it a capital N.
  5243. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5244. #### Usage
  5245. M48 [ n | X | Y | V | L ]
  5246. #### Parameters
  5247. - `n` - Number of samples. Valid values 4-50
  5248. - `X` - X position for samples
  5249. - `Y` - Y position for samples
  5250. - `V` - Verbose level. Valid values 1-4
  5251. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5252. */
  5253. case 48: // M48 Z-Probe repeatability
  5254. {
  5255. #if Z_MIN_PIN == -1
  5256. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5257. #endif
  5258. double sum=0.0;
  5259. double mean=0.0;
  5260. double sigma=0.0;
  5261. double sample_set[50];
  5262. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5263. double X_current, Y_current, Z_current;
  5264. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5265. if (code_seen('V') || code_seen('v')) {
  5266. verbose_level = code_value();
  5267. if (verbose_level<0 || verbose_level>4 ) {
  5268. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5269. goto Sigma_Exit;
  5270. }
  5271. }
  5272. if (verbose_level > 0) {
  5273. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5274. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5275. }
  5276. if (code_seen('n')) {
  5277. n_samples = code_value();
  5278. if (n_samples<4 || n_samples>50 ) {
  5279. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5280. goto Sigma_Exit;
  5281. }
  5282. }
  5283. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5284. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5285. Z_current = st_get_position_mm(Z_AXIS);
  5286. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5287. ext_position = st_get_position_mm(E_AXIS);
  5288. if (code_seen('X') || code_seen('x') ) {
  5289. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5290. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5291. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5292. goto Sigma_Exit;
  5293. }
  5294. }
  5295. if (code_seen('Y') || code_seen('y') ) {
  5296. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5297. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5298. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5299. goto Sigma_Exit;
  5300. }
  5301. }
  5302. if (code_seen('L') || code_seen('l') ) {
  5303. n_legs = code_value();
  5304. if ( n_legs==1 )
  5305. n_legs = 2;
  5306. if ( n_legs<0 || n_legs>15 ) {
  5307. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5308. goto Sigma_Exit;
  5309. }
  5310. }
  5311. //
  5312. // Do all the preliminary setup work. First raise the probe.
  5313. //
  5314. st_synchronize();
  5315. plan_bed_level_matrix.set_to_identity();
  5316. plan_buffer_line( X_current, Y_current, Z_start_location,
  5317. ext_position,
  5318. homing_feedrate[Z_AXIS]/60,
  5319. active_extruder);
  5320. st_synchronize();
  5321. //
  5322. // Now get everything to the specified probe point So we can safely do a probe to
  5323. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5324. // use that as a starting point for each probe.
  5325. //
  5326. if (verbose_level > 2)
  5327. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5328. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5329. ext_position,
  5330. homing_feedrate[X_AXIS]/60,
  5331. active_extruder);
  5332. st_synchronize();
  5333. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5334. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5335. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5336. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5337. //
  5338. // OK, do the inital probe to get us close to the bed.
  5339. // Then retrace the right amount and use that in subsequent probes
  5340. //
  5341. int l_feedmultiply = setup_for_endstop_move();
  5342. run_z_probe();
  5343. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5344. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5345. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5346. ext_position,
  5347. homing_feedrate[X_AXIS]/60,
  5348. active_extruder);
  5349. st_synchronize();
  5350. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5351. for( n=0; n<n_samples; n++) {
  5352. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5353. if ( n_legs) {
  5354. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5355. int rotational_direction, l;
  5356. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5357. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5358. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5359. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5360. //SERIAL_ECHOPAIR(" theta: ",theta);
  5361. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5362. //SERIAL_PROTOCOLLNPGM("");
  5363. for( l=0; l<n_legs-1; l++) {
  5364. if (rotational_direction==1)
  5365. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5366. else
  5367. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5368. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5369. if ( radius<0.0 )
  5370. radius = -radius;
  5371. X_current = X_probe_location + cos(theta) * radius;
  5372. Y_current = Y_probe_location + sin(theta) * radius;
  5373. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5374. X_current = X_MIN_POS;
  5375. if ( X_current>X_MAX_POS)
  5376. X_current = X_MAX_POS;
  5377. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5378. Y_current = Y_MIN_POS;
  5379. if ( Y_current>Y_MAX_POS)
  5380. Y_current = Y_MAX_POS;
  5381. if (verbose_level>3 ) {
  5382. SERIAL_ECHOPAIR("x: ", X_current);
  5383. SERIAL_ECHOPAIR("y: ", Y_current);
  5384. SERIAL_PROTOCOLLNPGM("");
  5385. }
  5386. do_blocking_move_to( X_current, Y_current, Z_current );
  5387. }
  5388. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5389. }
  5390. int l_feedmultiply = setup_for_endstop_move();
  5391. run_z_probe();
  5392. sample_set[n] = current_position[Z_AXIS];
  5393. //
  5394. // Get the current mean for the data points we have so far
  5395. //
  5396. sum=0.0;
  5397. for( j=0; j<=n; j++) {
  5398. sum = sum + sample_set[j];
  5399. }
  5400. mean = sum / (double (n+1));
  5401. //
  5402. // Now, use that mean to calculate the standard deviation for the
  5403. // data points we have so far
  5404. //
  5405. sum=0.0;
  5406. for( j=0; j<=n; j++) {
  5407. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5408. }
  5409. sigma = sqrt( sum / (double (n+1)) );
  5410. if (verbose_level > 1) {
  5411. SERIAL_PROTOCOL(n+1);
  5412. SERIAL_PROTOCOL(" of ");
  5413. SERIAL_PROTOCOL(n_samples);
  5414. SERIAL_PROTOCOLPGM(" z: ");
  5415. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5416. }
  5417. if (verbose_level > 2) {
  5418. SERIAL_PROTOCOL(" mean: ");
  5419. SERIAL_PROTOCOL_F(mean,6);
  5420. SERIAL_PROTOCOL(" sigma: ");
  5421. SERIAL_PROTOCOL_F(sigma,6);
  5422. }
  5423. if (verbose_level > 0)
  5424. SERIAL_PROTOCOLPGM("\n");
  5425. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5426. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5427. st_synchronize();
  5428. }
  5429. _delay(1000);
  5430. clean_up_after_endstop_move(l_feedmultiply);
  5431. // enable_endstops(true);
  5432. if (verbose_level > 0) {
  5433. SERIAL_PROTOCOLPGM("Mean: ");
  5434. SERIAL_PROTOCOL_F(mean, 6);
  5435. SERIAL_PROTOCOLPGM("\n");
  5436. }
  5437. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5438. SERIAL_PROTOCOL_F(sigma, 6);
  5439. SERIAL_PROTOCOLPGM("\n\n");
  5440. Sigma_Exit:
  5441. break;
  5442. }
  5443. #endif // Z_PROBE_REPEATABILITY_TEST
  5444. #endif // ENABLE_AUTO_BED_LEVELING
  5445. /*!
  5446. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5447. #### Usage
  5448. M73 [ P | R | Q | S ]
  5449. #### Parameters
  5450. - `P` - Percent in normal mode
  5451. - `R` - Time remaining in normal mode
  5452. - `Q` - Percent in silent mode
  5453. - `S` - Time in silent mode
  5454. */
  5455. case 73: //M73 show percent done and time remaining
  5456. if(code_seen('P')) print_percent_done_normal = code_value();
  5457. if(code_seen('R')) print_time_remaining_normal = code_value();
  5458. if(code_seen('Q')) print_percent_done_silent = code_value();
  5459. if(code_seen('S')) print_time_remaining_silent = code_value();
  5460. {
  5461. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %d; print time remaining in mins: %d\n");
  5462. printf_P(_msg_mode_done_remain, _N("NORMAL"), int(print_percent_done_normal), print_time_remaining_normal);
  5463. printf_P(_msg_mode_done_remain, _N("SILENT"), int(print_percent_done_silent), print_time_remaining_silent);
  5464. }
  5465. break;
  5466. /*!
  5467. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5468. #### Usage
  5469. M104 [ S ]
  5470. #### Parameters
  5471. - `S` - Target temperature
  5472. */
  5473. case 104: // M104
  5474. {
  5475. uint8_t extruder;
  5476. if(setTargetedHotend(104,extruder)){
  5477. break;
  5478. }
  5479. if (code_seen('S'))
  5480. {
  5481. setTargetHotendSafe(code_value(), extruder);
  5482. }
  5483. break;
  5484. }
  5485. /*!
  5486. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5487. It is processed much earlier as to bypass the cmdqueue.
  5488. */
  5489. case 112:
  5490. kill(MSG_M112_KILL, 3);
  5491. break;
  5492. /*!
  5493. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5494. #### Usage
  5495. M140 [ S ]
  5496. #### Parameters
  5497. - `S` - Target temperature
  5498. */
  5499. case 140:
  5500. if (code_seen('S')) setTargetBed(code_value());
  5501. break;
  5502. /*!
  5503. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5504. Prints temperatures:
  5505. - `T:` - Hotend (actual / target)
  5506. - `B:` - Bed (actual / target)
  5507. - `Tx:` - x Tool (actual / target)
  5508. - `@:` - Hotend power
  5509. - `B@:` - Bed power
  5510. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5511. - `A:` - Ambient actual (only MK3/s)
  5512. _Example:_
  5513. ok T:20.2 /0.0 B:19.1 /0.0 T0:20.2 /0.0 @:0 B@:0 P:19.8 A:26.4
  5514. */
  5515. case 105:
  5516. {
  5517. uint8_t extruder;
  5518. if(setTargetedHotend(105, extruder)){
  5519. break;
  5520. }
  5521. SERIAL_PROTOCOLPGM("ok ");
  5522. gcode_M105(extruder);
  5523. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5524. break;
  5525. }
  5526. #ifdef AUTO_REPORT_TEMPERATURES
  5527. /*!
  5528. ### M155 - Automatically send temperatures <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5529. #### Usage
  5530. M155 [ S ]
  5531. #### Parameters
  5532. - `S` - Set temperature autoreporting interval in seconds. 0 to disable. Maximum: 255
  5533. */
  5534. case 155:
  5535. {
  5536. if (code_seen('S'))
  5537. {
  5538. auto_report_temp_period = code_value_uint8();
  5539. if (auto_report_temp_period != 0)
  5540. auto_report_temp_timer.start();
  5541. else
  5542. auto_report_temp_timer.stop();
  5543. }
  5544. }
  5545. break;
  5546. #endif //AUTO_REPORT_TEMPERATURES
  5547. /*!
  5548. ### M109 - Wait for extruder temperature <a href="https://reprap.org/wiki/G-code#M109:_Set_Extruder_Temperature_and_Wait">M109: Set Extruder Temperature and Wait</a>
  5549. #### Usage
  5550. M104 [ B | R | S ]
  5551. #### Parameters (not mandatory)
  5552. - `S` - Set extruder temperature
  5553. - `R` - Set extruder temperature
  5554. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5555. Parameters S and R are treated identically.
  5556. Command always waits for both cool down and heat up.
  5557. If no parameters are supplied waits for previously set extruder temperature.
  5558. */
  5559. case 109:
  5560. {
  5561. uint8_t extruder;
  5562. if(setTargetedHotend(109, extruder)){
  5563. break;
  5564. }
  5565. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5566. heating_status = 1;
  5567. if (farm_mode) { prusa_statistics(1); };
  5568. #ifdef AUTOTEMP
  5569. autotemp_enabled=false;
  5570. #endif
  5571. if (code_seen('S')) {
  5572. setTargetHotendSafe(code_value(), extruder);
  5573. } else if (code_seen('R')) {
  5574. setTargetHotendSafe(code_value(), extruder);
  5575. }
  5576. #ifdef AUTOTEMP
  5577. if (code_seen('S')) autotemp_min=code_value();
  5578. if (code_seen('B')) autotemp_max=code_value();
  5579. if (code_seen('F'))
  5580. {
  5581. autotemp_factor=code_value();
  5582. autotemp_enabled=true;
  5583. }
  5584. #endif
  5585. codenum = _millis();
  5586. /* See if we are heating up or cooling down */
  5587. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5588. KEEPALIVE_STATE(NOT_BUSY);
  5589. cancel_heatup = false;
  5590. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5591. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5592. KEEPALIVE_STATE(IN_HANDLER);
  5593. heating_status = 2;
  5594. if (farm_mode) { prusa_statistics(2); };
  5595. //starttime=_millis();
  5596. previous_millis_cmd = _millis();
  5597. }
  5598. break;
  5599. /*!
  5600. ### M190 - Wait for bed temperature <a href="https://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp">M190: Wait for bed temperature to reach target temp</a>
  5601. #### Usage
  5602. M190 [ R | S ]
  5603. #### Parameters (not mandatory)
  5604. - `S` - Set extruder temperature and wait for heating
  5605. - `R` - Set extruder temperature and wait for heating or cooling
  5606. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5607. */
  5608. case 190:
  5609. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5610. {
  5611. bool CooldownNoWait = false;
  5612. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5613. heating_status = 3;
  5614. if (farm_mode) { prusa_statistics(1); };
  5615. if (code_seen('S'))
  5616. {
  5617. setTargetBed(code_value());
  5618. CooldownNoWait = true;
  5619. }
  5620. else if (code_seen('R'))
  5621. {
  5622. setTargetBed(code_value());
  5623. }
  5624. codenum = _millis();
  5625. cancel_heatup = false;
  5626. target_direction = isHeatingBed(); // true if heating, false if cooling
  5627. KEEPALIVE_STATE(NOT_BUSY);
  5628. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  5629. {
  5630. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5631. {
  5632. if (!farm_mode) {
  5633. float tt = degHotend(active_extruder);
  5634. SERIAL_PROTOCOLPGM("T:");
  5635. SERIAL_PROTOCOL(tt);
  5636. SERIAL_PROTOCOLPGM(" E:");
  5637. SERIAL_PROTOCOL((int)active_extruder);
  5638. SERIAL_PROTOCOLPGM(" B:");
  5639. SERIAL_PROTOCOL_F(degBed(), 1);
  5640. SERIAL_PROTOCOLLN("");
  5641. }
  5642. codenum = _millis();
  5643. }
  5644. manage_heater();
  5645. manage_inactivity();
  5646. lcd_update(0);
  5647. }
  5648. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5649. KEEPALIVE_STATE(IN_HANDLER);
  5650. heating_status = 4;
  5651. previous_millis_cmd = _millis();
  5652. }
  5653. #endif
  5654. break;
  5655. #if defined(FAN_PIN) && FAN_PIN > -1
  5656. /*!
  5657. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5658. #### Usage
  5659. M106 [ S ]
  5660. #### Parameters
  5661. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5662. */
  5663. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5664. if (code_seen('S')){
  5665. fanSpeed=constrain(code_value(),0,255);
  5666. }
  5667. else {
  5668. fanSpeed=255;
  5669. }
  5670. break;
  5671. /*!
  5672. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5673. */
  5674. case 107:
  5675. fanSpeed = 0;
  5676. break;
  5677. #endif //FAN_PIN
  5678. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5679. /*!
  5680. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5681. Only works if the firmware is compiled with PS_ON_PIN defined.
  5682. */
  5683. case 80:
  5684. SET_OUTPUT(PS_ON_PIN); //GND
  5685. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5686. // If you have a switch on suicide pin, this is useful
  5687. // if you want to start another print with suicide feature after
  5688. // a print without suicide...
  5689. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5690. SET_OUTPUT(SUICIDE_PIN);
  5691. WRITE(SUICIDE_PIN, HIGH);
  5692. #endif
  5693. powersupply = true;
  5694. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  5695. lcd_update(0);
  5696. break;
  5697. /*!
  5698. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5699. Only works if the firmware is compiled with PS_ON_PIN defined.
  5700. */
  5701. case 81:
  5702. disable_heater();
  5703. st_synchronize();
  5704. disable_e0();
  5705. disable_e1();
  5706. disable_e2();
  5707. finishAndDisableSteppers();
  5708. fanSpeed = 0;
  5709. _delay(1000); // Wait a little before to switch off
  5710. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5711. st_synchronize();
  5712. suicide();
  5713. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5714. SET_OUTPUT(PS_ON_PIN);
  5715. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5716. #endif
  5717. powersupply = false;
  5718. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5719. lcd_update(0);
  5720. break;
  5721. #endif
  5722. /*!
  5723. ### M82 - Set E axis to absolute mode <a href="https://reprap.org/wiki/G-code#M82:_Set_extruder_to_absolute_mode">M82: Set extruder to absolute mode</a>
  5724. Makes the extruder interpret extrusion as absolute positions.
  5725. */
  5726. case 82:
  5727. axis_relative_modes &= ~E_AXIS_MASK;
  5728. break;
  5729. /*!
  5730. ### M83 - Set E axis to relative mode <a href="https://reprap.org/wiki/G-code#M83:_Set_extruder_to_relative_mode">M83: Set extruder to relative mode</a>
  5731. Makes the extruder interpret extrusion values as relative positions.
  5732. */
  5733. case 83:
  5734. axis_relative_modes |= E_AXIS_MASK;
  5735. break;
  5736. /*!
  5737. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5738. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5739. This command can be used without any additional parameters. In that case all steppers are disabled.
  5740. The file completeness check uses this parameter to detect an incomplete file. It has to be present at the end of a file with no parameters.
  5741. M84 [ S | X | Y | Z | E ]
  5742. - `S` - Seconds
  5743. - `X` - X axis
  5744. - `Y` - Y axis
  5745. - `Z` - Z axis
  5746. - `E` - Exruder
  5747. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5748. Equal to M84 (compatibility)
  5749. */
  5750. case 18: //compatibility
  5751. case 84: // M84
  5752. if(code_seen('S')){
  5753. stepper_inactive_time = code_value() * 1000;
  5754. }
  5755. else
  5756. {
  5757. 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])));
  5758. if(all_axis)
  5759. {
  5760. st_synchronize();
  5761. disable_e0();
  5762. disable_e1();
  5763. disable_e2();
  5764. finishAndDisableSteppers();
  5765. }
  5766. else
  5767. {
  5768. st_synchronize();
  5769. if (code_seen('X')) disable_x();
  5770. if (code_seen('Y')) disable_y();
  5771. if (code_seen('Z')) disable_z();
  5772. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5773. if (code_seen('E')) {
  5774. disable_e0();
  5775. disable_e1();
  5776. disable_e2();
  5777. }
  5778. #endif
  5779. }
  5780. }
  5781. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  5782. print_time_remaining_init();
  5783. snmm_filaments_used = 0;
  5784. break;
  5785. /*!
  5786. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5787. #### Usage
  5788. M85 [ S ]
  5789. #### Parameters
  5790. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5791. */
  5792. case 85: // M85
  5793. if(code_seen('S')) {
  5794. max_inactive_time = code_value() * 1000;
  5795. }
  5796. break;
  5797. #ifdef SAFETYTIMER
  5798. /*!
  5799. ### M86 - Set safety timer expiration time <a href="https://reprap.org/wiki/G-code#M86:_Set_Safety_Timer_expiration_time">M86: Set Safety Timer expiration time</a>
  5800. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5801. #### Usage
  5802. M86 [ S ]
  5803. #### Parameters
  5804. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5805. */
  5806. case 86:
  5807. if (code_seen('S')) {
  5808. safetytimer_inactive_time = code_value() * 1000;
  5809. safetyTimer.start();
  5810. }
  5811. break;
  5812. #endif
  5813. /*!
  5814. ### M92 Set Axis steps-per-unit <a href="https://reprap.org/wiki/G-code#M92:_Set_axis_steps_per_unit">M92: Set axis_steps_per_unit</a>
  5815. Allows programming of steps per unit (usually mm) for motor drives. These values are reset to firmware defaults on power on, unless saved to EEPROM if available (M500 in Marlin)
  5816. #### Usage
  5817. M92 [ X | Y | Z | E ]
  5818. #### Parameters
  5819. - `X` - Steps per unit for the X drive
  5820. - `Y` - Steps per unit for the Y drive
  5821. - `Z` - Steps per unit for the Z drive
  5822. - `E` - Steps per unit for the extruder drive
  5823. */
  5824. case 92:
  5825. for(int8_t i=0; i < NUM_AXIS; i++)
  5826. {
  5827. if(code_seen(axis_codes[i]))
  5828. {
  5829. if(i == E_AXIS) { // E
  5830. float value = code_value();
  5831. if(value < 20.0) {
  5832. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5833. cs.max_jerk[E_AXIS] *= factor;
  5834. max_feedrate[i] *= factor;
  5835. axis_steps_per_sqr_second[i] *= factor;
  5836. }
  5837. cs.axis_steps_per_unit[i] = value;
  5838. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  5839. fsensor_set_axis_steps_per_unit(value);
  5840. #endif
  5841. }
  5842. else {
  5843. cs.axis_steps_per_unit[i] = code_value();
  5844. }
  5845. }
  5846. }
  5847. break;
  5848. /*!
  5849. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5850. Sets the line number in G-code
  5851. #### Usage
  5852. M110 [ N ]
  5853. #### Parameters
  5854. - `N` - Line number
  5855. */
  5856. case 110:
  5857. if (code_seen('N'))
  5858. gcode_LastN = code_value_long();
  5859. break;
  5860. /*!
  5861. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5862. During some lengthy processes, such as G29, Marlin may appear to the host to have “gone away.” The “host keepalive” feature will send messages to the host when Marlin is busy or waiting for user response so the host won’t try to reconnect (or disconnect).
  5863. #### Usage
  5864. M113 [ S ]
  5865. #### Parameters
  5866. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5867. */
  5868. case 113:
  5869. if (code_seen('S')) {
  5870. host_keepalive_interval = (uint8_t)code_value_short();
  5871. // NOMORE(host_keepalive_interval, 60);
  5872. }
  5873. else {
  5874. SERIAL_ECHO_START;
  5875. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5876. SERIAL_PROTOCOLLN("");
  5877. }
  5878. break;
  5879. /*!
  5880. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5881. Print the firmware info and capabilities
  5882. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5883. `M115 U` Checks the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware, it will pause the print for 30s and ask the user to upgrade the firmware.
  5884. _Examples:_
  5885. `M115` results:
  5886. `FIRMWARE_NAME:Prusa-Firmware 3.8.1 based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:1.0 MACHINE_TYPE:Prusa i3 MK3S EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000`
  5887. `M115 V` results:
  5888. `3.8.1`
  5889. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5890. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5891. #### Usage
  5892. M115 [ V | U ]
  5893. #### Parameters
  5894. - V - Report current installed firmware version
  5895. - U - Firmware version provided by G-code to be compared to current one.
  5896. */
  5897. case 115: // M115
  5898. if (code_seen('V')) {
  5899. // Report the Prusa version number.
  5900. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5901. } else if (code_seen('U')) {
  5902. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5903. // pause the print for 30s and ask the user to upgrade the firmware.
  5904. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5905. } else {
  5906. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5907. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5908. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5909. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5910. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5911. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5912. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5913. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5914. SERIAL_ECHOPGM(" UUID:");
  5915. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5916. #ifdef EXTENDED_CAPABILITIES_REPORT
  5917. extended_capabilities_report();
  5918. #endif //EXTENDED_CAPABILITIES_REPORT
  5919. }
  5920. break;
  5921. /*!
  5922. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5923. */
  5924. case 114:
  5925. gcode_M114();
  5926. break;
  5927. /*
  5928. M117 moved up to get the high priority
  5929. case 117: // M117 display message
  5930. starpos = (strchr(strchr_pointer + 5,'*'));
  5931. if(starpos!=NULL)
  5932. *(starpos)='\0';
  5933. lcd_setstatus(strchr_pointer + 5);
  5934. break;*/
  5935. /*!
  5936. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5937. */
  5938. case 120:
  5939. enable_endstops(false) ;
  5940. break;
  5941. /*!
  5942. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5943. */
  5944. case 121:
  5945. enable_endstops(true) ;
  5946. break;
  5947. /*!
  5948. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5949. Returns the current state of the configured X, Y, Z endstops. Takes into account any 'inverted endstop' settings, so one can confirm that the machine is interpreting the endstops correctly.
  5950. */
  5951. case 119:
  5952. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5953. SERIAL_PROTOCOLLN("");
  5954. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5955. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5956. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5957. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5958. }else{
  5959. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5960. }
  5961. SERIAL_PROTOCOLLN("");
  5962. #endif
  5963. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5964. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5965. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5966. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5967. }else{
  5968. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5969. }
  5970. SERIAL_PROTOCOLLN("");
  5971. #endif
  5972. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5973. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5974. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5975. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5976. }else{
  5977. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5978. }
  5979. SERIAL_PROTOCOLLN("");
  5980. #endif
  5981. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5982. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5983. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5984. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5985. }else{
  5986. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5987. }
  5988. SERIAL_PROTOCOLLN("");
  5989. #endif
  5990. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5991. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5992. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5993. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5994. }else{
  5995. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5996. }
  5997. SERIAL_PROTOCOLLN("");
  5998. #endif
  5999. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  6000. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  6001. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  6002. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  6003. }else{
  6004. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  6005. }
  6006. SERIAL_PROTOCOLLN("");
  6007. #endif
  6008. break;
  6009. //!@todo update for all axes, use for loop
  6010. #ifdef BLINKM
  6011. /*!
  6012. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  6013. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  6014. #### Usage
  6015. M150 [ R | U | B ]
  6016. #### Parameters
  6017. - `R` - Red color value
  6018. - `U` - Green color value. It is NOT `G`!
  6019. - `B` - Blue color value
  6020. */
  6021. case 150:
  6022. {
  6023. byte red;
  6024. byte grn;
  6025. byte blu;
  6026. if(code_seen('R')) red = code_value();
  6027. if(code_seen('U')) grn = code_value();
  6028. if(code_seen('B')) blu = code_value();
  6029. SendColors(red,grn,blu);
  6030. }
  6031. break;
  6032. #endif //BLINKM
  6033. /*!
  6034. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  6035. #### Usage
  6036. M200 [ D | T ]
  6037. #### Parameters
  6038. - `D` - Diameter in mm
  6039. - `T` - Number of extruder (MMUs)
  6040. */
  6041. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  6042. {
  6043. uint8_t extruder = active_extruder;
  6044. if(code_seen('T')) {
  6045. extruder = code_value();
  6046. if(extruder >= EXTRUDERS) {
  6047. SERIAL_ECHO_START;
  6048. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  6049. break;
  6050. }
  6051. }
  6052. if(code_seen('D')) {
  6053. float diameter = (float)code_value();
  6054. if (diameter == 0.0) {
  6055. // setting any extruder filament size disables volumetric on the assumption that
  6056. // slicers either generate in extruder values as cubic mm or as as filament feeds
  6057. // for all extruders
  6058. cs.volumetric_enabled = false;
  6059. } else {
  6060. cs.filament_size[extruder] = (float)code_value();
  6061. // make sure all extruders have some sane value for the filament size
  6062. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  6063. #if EXTRUDERS > 1
  6064. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  6065. #if EXTRUDERS > 2
  6066. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  6067. #endif
  6068. #endif
  6069. cs.volumetric_enabled = true;
  6070. }
  6071. } else {
  6072. //reserved for setting filament diameter via UFID or filament measuring device
  6073. break;
  6074. }
  6075. calculate_extruder_multipliers();
  6076. }
  6077. break;
  6078. /*!
  6079. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_printing_acceleration">M201: Set max printing acceleration</a>
  6080. For each axis individually.
  6081. */
  6082. case 201:
  6083. for (int8_t i = 0; i < NUM_AXIS; i++)
  6084. {
  6085. if (code_seen(axis_codes[i]))
  6086. {
  6087. unsigned long val = code_value();
  6088. #ifdef TMC2130
  6089. unsigned long val_silent = val;
  6090. if ((i == X_AXIS) || (i == Y_AXIS))
  6091. {
  6092. if (val > NORMAL_MAX_ACCEL_XY)
  6093. val = NORMAL_MAX_ACCEL_XY;
  6094. if (val_silent > SILENT_MAX_ACCEL_XY)
  6095. val_silent = SILENT_MAX_ACCEL_XY;
  6096. }
  6097. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  6098. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  6099. #else //TMC2130
  6100. max_acceleration_units_per_sq_second[i] = val;
  6101. #endif //TMC2130
  6102. }
  6103. }
  6104. // 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)
  6105. reset_acceleration_rates();
  6106. break;
  6107. #if 0 // Not used for Sprinter/grbl gen6
  6108. case 202: // M202
  6109. for(int8_t i=0; i < NUM_AXIS; i++) {
  6110. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  6111. }
  6112. break;
  6113. #endif
  6114. /*!
  6115. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  6116. For each axis individually.
  6117. */
  6118. case 203: // M203 max feedrate mm/sec
  6119. for (int8_t i = 0; i < NUM_AXIS; i++)
  6120. {
  6121. if (code_seen(axis_codes[i]))
  6122. {
  6123. float val = code_value();
  6124. #ifdef TMC2130
  6125. float val_silent = val;
  6126. if ((i == X_AXIS) || (i == Y_AXIS))
  6127. {
  6128. if (val > NORMAL_MAX_FEEDRATE_XY)
  6129. val = NORMAL_MAX_FEEDRATE_XY;
  6130. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  6131. val_silent = SILENT_MAX_FEEDRATE_XY;
  6132. }
  6133. cs.max_feedrate_normal[i] = val;
  6134. cs.max_feedrate_silent[i] = val_silent;
  6135. #else //TMC2130
  6136. max_feedrate[i] = val;
  6137. #endif //TMC2130
  6138. }
  6139. }
  6140. break;
  6141. /*!
  6142. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  6143. #### Old format:
  6144. ##### Usage
  6145. M204 [ S | T ]
  6146. ##### Parameters
  6147. - `S` - normal moves
  6148. - `T` - filmanent only moves
  6149. #### New format:
  6150. ##### Usage
  6151. M204 [ P | R | T ]
  6152. ##### Parameters
  6153. - `P` - printing moves
  6154. - `R` - filmanent only moves
  6155. - `T` - travel moves (as of now T is ignored)
  6156. */
  6157. case 204:
  6158. {
  6159. if(code_seen('S')) {
  6160. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6161. // and it is also generated by Slic3r to control acceleration per extrusion type
  6162. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6163. cs.acceleration = code_value();
  6164. // Interpret the T value as retract acceleration in the old Marlin format.
  6165. if(code_seen('T'))
  6166. cs.retract_acceleration = code_value();
  6167. } else {
  6168. // New acceleration format, compatible with the upstream Marlin.
  6169. if(code_seen('P'))
  6170. cs.acceleration = code_value();
  6171. if(code_seen('R'))
  6172. cs.retract_acceleration = code_value();
  6173. if(code_seen('T')) {
  6174. // Interpret the T value as the travel acceleration in the new Marlin format.
  6175. /*!
  6176. @todo Prusa3D firmware currently does not support travel acceleration value independent from the extruding acceleration value.
  6177. */
  6178. // travel_acceleration = code_value();
  6179. }
  6180. }
  6181. }
  6182. break;
  6183. /*!
  6184. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6185. Set some advanced settings related to movement.
  6186. #### Usage
  6187. M205 [ S | T | B | X | Y | Z | E ]
  6188. #### Parameters
  6189. - `S` - Minimum feedrate for print moves (unit/s)
  6190. - `T` - Minimum feedrate for travel moves (units/s)
  6191. - `B` - Minimum segment time (us)
  6192. - `X` - Maximum X jerk (units/s)
  6193. - `Y` - Maximum Y jerk (units/s)
  6194. - `Z` - Maximum Z jerk (units/s)
  6195. - `E` - Maximum E jerk (units/s)
  6196. */
  6197. case 205:
  6198. {
  6199. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6200. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6201. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6202. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6203. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6204. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6205. if(code_seen('E'))
  6206. {
  6207. float e = code_value();
  6208. #ifndef LA_NOCOMPAT
  6209. e = la10c_jerk(e);
  6210. #endif
  6211. cs.max_jerk[E_AXIS] = e;
  6212. }
  6213. if (cs.max_jerk[X_AXIS] > DEFAULT_XJERK) cs.max_jerk[X_AXIS] = DEFAULT_XJERK;
  6214. if (cs.max_jerk[Y_AXIS] > DEFAULT_YJERK) cs.max_jerk[Y_AXIS] = DEFAULT_YJERK;
  6215. }
  6216. break;
  6217. /*!
  6218. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6219. #### Usage
  6220. M206 [ X | Y | Z ]
  6221. #### Parameters
  6222. - `X` - X axis offset
  6223. - `Y` - Y axis offset
  6224. - `Z` - Z axis offset
  6225. */
  6226. case 206:
  6227. for(int8_t i=0; i < 3; i++)
  6228. {
  6229. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6230. }
  6231. break;
  6232. #ifdef FWRETRACT
  6233. /*!
  6234. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6235. #### Usage
  6236. M207 [ S | F | Z ]
  6237. #### Parameters
  6238. - `S` - positive length to retract, in mm
  6239. - `F` - retraction feedrate, in mm/min
  6240. - `Z` - additional zlift/hop
  6241. */
  6242. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6243. {
  6244. if(code_seen('S'))
  6245. {
  6246. cs.retract_length = code_value() ;
  6247. }
  6248. if(code_seen('F'))
  6249. {
  6250. cs.retract_feedrate = code_value()/60 ;
  6251. }
  6252. if(code_seen('Z'))
  6253. {
  6254. cs.retract_zlift = code_value() ;
  6255. }
  6256. }break;
  6257. /*!
  6258. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6259. #### Usage
  6260. M208 [ S | F ]
  6261. #### Parameters
  6262. - `S` - positive length surplus to the M207 Snnn, in mm
  6263. - `F` - feedrate, in mm/sec
  6264. */
  6265. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6266. {
  6267. if(code_seen('S'))
  6268. {
  6269. cs.retract_recover_length = code_value() ;
  6270. }
  6271. if(code_seen('F'))
  6272. {
  6273. cs.retract_recover_feedrate = code_value()/60 ;
  6274. }
  6275. }break;
  6276. /*!
  6277. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6278. This boolean value S 1=true or 0=false enables automatic retract detect if the slicer did not support G10/G11: every normal extrude-only move will be classified as retract depending on the direction.
  6279. #### Usage
  6280. M209 [ S ]
  6281. #### Parameters
  6282. - `S` - 1=true or 0=false
  6283. */
  6284. 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.
  6285. {
  6286. if(code_seen('S'))
  6287. {
  6288. int t= code_value() ;
  6289. switch(t)
  6290. {
  6291. case 0:
  6292. {
  6293. cs.autoretract_enabled=false;
  6294. retracted[0]=false;
  6295. #if EXTRUDERS > 1
  6296. retracted[1]=false;
  6297. #endif
  6298. #if EXTRUDERS > 2
  6299. retracted[2]=false;
  6300. #endif
  6301. }break;
  6302. case 1:
  6303. {
  6304. cs.autoretract_enabled=true;
  6305. retracted[0]=false;
  6306. #if EXTRUDERS > 1
  6307. retracted[1]=false;
  6308. #endif
  6309. #if EXTRUDERS > 2
  6310. retracted[2]=false;
  6311. #endif
  6312. }break;
  6313. default:
  6314. SERIAL_ECHO_START;
  6315. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6316. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6317. SERIAL_ECHOLNPGM("\"(1)");
  6318. }
  6319. }
  6320. }break;
  6321. #endif // FWRETRACT
  6322. #if EXTRUDERS > 1
  6323. /*!
  6324. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6325. In Prusa Firmware this G-code is only active if `EXTRUDERS` is higher then 1 in the source code. On Original i3 Prusa MK2/s MK2.5/s MK3/s it is not active.
  6326. #### Usage
  6327. M218 [ X | Y ]
  6328. #### Parameters
  6329. - `X` - X offset
  6330. - `Y` - Y offset
  6331. */
  6332. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6333. {
  6334. uint8_t extruder;
  6335. if(setTargetedHotend(218, extruder)){
  6336. break;
  6337. }
  6338. if(code_seen('X'))
  6339. {
  6340. extruder_offset[X_AXIS][extruder] = code_value();
  6341. }
  6342. if(code_seen('Y'))
  6343. {
  6344. extruder_offset[Y_AXIS][extruder] = code_value();
  6345. }
  6346. SERIAL_ECHO_START;
  6347. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6348. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6349. {
  6350. SERIAL_ECHO(" ");
  6351. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6352. SERIAL_ECHO(",");
  6353. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6354. }
  6355. SERIAL_ECHOLN("");
  6356. }break;
  6357. #endif
  6358. /*!
  6359. ### M220 Set feedrate percentage <a href="https://reprap.org/wiki/G-code#M220:_Set_speed_factor_override_percentage">M220: Set speed factor override percentage</a>
  6360. #### Usage
  6361. M220 [ B | S | R ]
  6362. #### Parameters
  6363. - `B` - Backup current speed factor
  6364. - `S` - Speed factor override percentage (0..100 or higher)
  6365. - `R` - Restore previous speed factor
  6366. */
  6367. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6368. {
  6369. bool codesWereSeen = false;
  6370. if (code_seen('B')) //backup current speed factor
  6371. {
  6372. saved_feedmultiply_mm = feedmultiply;
  6373. codesWereSeen = true;
  6374. }
  6375. if (code_seen('S'))
  6376. {
  6377. feedmultiply = code_value();
  6378. codesWereSeen = true;
  6379. }
  6380. if (code_seen('R')) //restore previous feedmultiply
  6381. {
  6382. feedmultiply = saved_feedmultiply_mm;
  6383. codesWereSeen = true;
  6384. }
  6385. if (!codesWereSeen)
  6386. {
  6387. printf_P(PSTR("%i%%\n"), feedmultiply);
  6388. }
  6389. }
  6390. break;
  6391. /*!
  6392. ### M221 - Set extrude factor override percentage <a href="https://reprap.org/wiki/G-code#M221:_Set_extrude_factor_override_percentage">M221: Set extrude factor override percentage</a>
  6393. #### Usage
  6394. M221 [ S | T ]
  6395. #### Parameters
  6396. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6397. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6398. */
  6399. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6400. {
  6401. if (code_seen('S'))
  6402. {
  6403. int tmp_code = code_value();
  6404. if (code_seen('T'))
  6405. {
  6406. uint8_t extruder;
  6407. if (setTargetedHotend(221, extruder))
  6408. break;
  6409. extruder_multiply[extruder] = tmp_code;
  6410. }
  6411. else
  6412. {
  6413. extrudemultiply = tmp_code ;
  6414. }
  6415. }
  6416. else
  6417. {
  6418. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6419. }
  6420. calculate_extruder_multipliers();
  6421. }
  6422. break;
  6423. /*!
  6424. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6425. Wait until the specified pin reaches the state required
  6426. #### Usage
  6427. M226 [ P | S ]
  6428. #### Parameters
  6429. - `P` - pin number
  6430. - `S` - pin state
  6431. */
  6432. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6433. {
  6434. if(code_seen('P')){
  6435. int pin_number = code_value(); // pin number
  6436. int pin_state = -1; // required pin state - default is inverted
  6437. if(code_seen('S')) pin_state = code_value(); // required pin state
  6438. if(pin_state >= -1 && pin_state <= 1){
  6439. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  6440. {
  6441. if (sensitive_pins[i] == pin_number)
  6442. {
  6443. pin_number = -1;
  6444. break;
  6445. }
  6446. }
  6447. if (pin_number > -1)
  6448. {
  6449. int target = LOW;
  6450. st_synchronize();
  6451. pinMode(pin_number, INPUT);
  6452. switch(pin_state){
  6453. case 1:
  6454. target = HIGH;
  6455. break;
  6456. case 0:
  6457. target = LOW;
  6458. break;
  6459. case -1:
  6460. target = !digitalRead(pin_number);
  6461. break;
  6462. }
  6463. while(digitalRead(pin_number) != target){
  6464. manage_heater();
  6465. manage_inactivity();
  6466. lcd_update(0);
  6467. }
  6468. }
  6469. }
  6470. }
  6471. }
  6472. break;
  6473. #if NUM_SERVOS > 0
  6474. /*!
  6475. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6476. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6477. #### Usage
  6478. M280 [ P | S ]
  6479. #### Parameters
  6480. - `P` - Servo index (id)
  6481. - `S` - Target position
  6482. */
  6483. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6484. {
  6485. int servo_index = -1;
  6486. int servo_position = 0;
  6487. if (code_seen('P'))
  6488. servo_index = code_value();
  6489. if (code_seen('S')) {
  6490. servo_position = code_value();
  6491. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6492. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6493. servos[servo_index].attach(0);
  6494. #endif
  6495. servos[servo_index].write(servo_position);
  6496. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6497. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6498. servos[servo_index].detach();
  6499. #endif
  6500. }
  6501. else {
  6502. SERIAL_ECHO_START;
  6503. SERIAL_ECHO("Servo ");
  6504. SERIAL_ECHO(servo_index);
  6505. SERIAL_ECHOLN(" out of range");
  6506. }
  6507. }
  6508. else if (servo_index >= 0) {
  6509. SERIAL_PROTOCOL(MSG_OK);
  6510. SERIAL_PROTOCOL(" Servo ");
  6511. SERIAL_PROTOCOL(servo_index);
  6512. SERIAL_PROTOCOL(": ");
  6513. SERIAL_PROTOCOL(servos[servo_index].read());
  6514. SERIAL_PROTOCOLLN("");
  6515. }
  6516. }
  6517. break;
  6518. #endif // NUM_SERVOS > 0
  6519. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6520. /*!
  6521. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6522. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6523. #### Usage
  6524. M300 [ S | P ]
  6525. #### Parameters
  6526. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6527. - `P` - duration in milliseconds
  6528. */
  6529. case 300: // M300
  6530. {
  6531. int beepS = code_seen('S') ? code_value() : 110;
  6532. int beepP = code_seen('P') ? code_value() : 1000;
  6533. if (beepS > 0)
  6534. {
  6535. #if BEEPER > 0
  6536. Sound_MakeCustom(beepP,beepS,false);
  6537. #endif
  6538. }
  6539. else
  6540. {
  6541. _delay(beepP);
  6542. }
  6543. }
  6544. break;
  6545. #endif // M300
  6546. #ifdef PIDTEMP
  6547. /*!
  6548. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6549. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6550. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6551. #### Usage
  6552. M301 [ P | I | D | C ]
  6553. #### Parameters
  6554. - `P` - proportional (Kp)
  6555. - `I` - integral (Ki)
  6556. - `D` - derivative (Kd)
  6557. - `C` - heating power=Kc*(e_speed0)
  6558. */
  6559. case 301:
  6560. {
  6561. if(code_seen('P')) cs.Kp = code_value();
  6562. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6563. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6564. #ifdef PID_ADD_EXTRUSION_RATE
  6565. if(code_seen('C')) Kc = code_value();
  6566. #endif
  6567. updatePID();
  6568. SERIAL_PROTOCOLRPGM(MSG_OK);
  6569. SERIAL_PROTOCOL(" p:");
  6570. SERIAL_PROTOCOL(cs.Kp);
  6571. SERIAL_PROTOCOL(" i:");
  6572. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6573. SERIAL_PROTOCOL(" d:");
  6574. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6575. #ifdef PID_ADD_EXTRUSION_RATE
  6576. SERIAL_PROTOCOL(" c:");
  6577. //Kc does not have scaling applied above, or in resetting defaults
  6578. SERIAL_PROTOCOL(Kc);
  6579. #endif
  6580. SERIAL_PROTOCOLLN("");
  6581. }
  6582. break;
  6583. #endif //PIDTEMP
  6584. #ifdef PIDTEMPBED
  6585. /*!
  6586. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6587. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6588. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6589. #### Usage
  6590. M304 [ P | I | D ]
  6591. #### Parameters
  6592. - `P` - proportional (Kp)
  6593. - `I` - integral (Ki)
  6594. - `D` - derivative (Kd)
  6595. */
  6596. case 304:
  6597. {
  6598. if(code_seen('P')) cs.bedKp = code_value();
  6599. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6600. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6601. updatePID();
  6602. SERIAL_PROTOCOLRPGM(MSG_OK);
  6603. SERIAL_PROTOCOL(" p:");
  6604. SERIAL_PROTOCOL(cs.bedKp);
  6605. SERIAL_PROTOCOL(" i:");
  6606. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6607. SERIAL_PROTOCOL(" d:");
  6608. SERIAL_PROTOCOL(unscalePID_d(cs.bedKd));
  6609. SERIAL_PROTOCOLLN("");
  6610. }
  6611. break;
  6612. #endif //PIDTEMP
  6613. /*!
  6614. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6615. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6616. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6617. */
  6618. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6619. {
  6620. #ifdef CHDK
  6621. SET_OUTPUT(CHDK);
  6622. WRITE(CHDK, HIGH);
  6623. chdkHigh = _millis();
  6624. chdkActive = true;
  6625. #else
  6626. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6627. const uint8_t NUM_PULSES=16;
  6628. const float PULSE_LENGTH=0.01524;
  6629. for(int i=0; i < NUM_PULSES; i++) {
  6630. WRITE(PHOTOGRAPH_PIN, HIGH);
  6631. _delay_ms(PULSE_LENGTH);
  6632. WRITE(PHOTOGRAPH_PIN, LOW);
  6633. _delay_ms(PULSE_LENGTH);
  6634. }
  6635. _delay(7.33);
  6636. for(int i=0; i < NUM_PULSES; i++) {
  6637. WRITE(PHOTOGRAPH_PIN, HIGH);
  6638. _delay_ms(PULSE_LENGTH);
  6639. WRITE(PHOTOGRAPH_PIN, LOW);
  6640. _delay_ms(PULSE_LENGTH);
  6641. }
  6642. #endif
  6643. #endif //chdk end if
  6644. }
  6645. break;
  6646. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6647. /*!
  6648. ### M302 - Allow cold extrude, or set minimum extrude temperature <a href="https://reprap.org/wiki/G-code#M302:_Allow_cold_extrudes">M302: Allow cold extrudes</a>
  6649. This tells the printer to allow movement of the extruder motor above a certain temperature, or if disabled, to allow extruder movement when the hotend is below a safe printing temperature.
  6650. #### Usage
  6651. M302 [ S ]
  6652. #### Parameters
  6653. - `S` - Cold extrude minimum temperature
  6654. */
  6655. case 302:
  6656. {
  6657. float temp = .0;
  6658. if (code_seen('S')) temp=code_value();
  6659. set_extrude_min_temp(temp);
  6660. }
  6661. break;
  6662. #endif
  6663. /*!
  6664. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6665. PID Tuning refers to a control algorithm used in some repraps to tune heating behavior for hot ends and heated beds. This command generates Proportional (Kp), Integral (Ki), and Derivative (Kd) values for the hotend or bed. Send the appropriate code and wait for the output to update the firmware values.
  6666. #### Usage
  6667. M303 [ E | S | C ]
  6668. #### Parameters
  6669. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6670. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6671. - `C` - Cycles, default `5`
  6672. */
  6673. case 303:
  6674. {
  6675. float temp = 150.0;
  6676. int e=0;
  6677. int c=5;
  6678. if (code_seen('E')) e=code_value();
  6679. if (e<0)
  6680. temp=70;
  6681. if (code_seen('S')) temp=code_value();
  6682. if (code_seen('C')) c=code_value();
  6683. PID_autotune(temp, e, c);
  6684. }
  6685. break;
  6686. /*!
  6687. ### M400 - Wait for all moves to finish <a href="https://reprap.org/wiki/G-code#M400:_Wait_for_current_moves_to_finish">M400: Wait for current moves to finish</a>
  6688. Finishes all current moves and and thus clears the buffer.
  6689. Equivalent to `G4` with no parameters.
  6690. */
  6691. case 400:
  6692. {
  6693. st_synchronize();
  6694. }
  6695. break;
  6696. /*!
  6697. ### M403 - Set filament type (material) for particular extruder and notify the MMU <a href="https://reprap.org/wiki/G-code#M403:_Set_filament_type_.28material.29_for_particular_extruder_and_notify_the_MMU.">M403 - Set filament type (material) for particular extruder and notify the MMU</a>
  6698. Currently three different materials are needed (default, flex and PVA).
  6699. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6700. #### Usage
  6701. M403 [ E | F ]
  6702. #### Parameters
  6703. - `E` - Extruder number. 0-indexed.
  6704. - `F` - Filament type
  6705. */
  6706. case 403:
  6707. {
  6708. // currently three different materials are needed (default, flex and PVA)
  6709. // add storing this information for different load/unload profiles etc. in the future
  6710. // firmware does not wait for "ok" from mmu
  6711. if (mmu_enabled)
  6712. {
  6713. uint8_t extruder = 255;
  6714. uint8_t filament = FILAMENT_UNDEFINED;
  6715. if(code_seen('E')) extruder = code_value();
  6716. if(code_seen('F')) filament = code_value();
  6717. mmu_set_filament_type(extruder, filament);
  6718. }
  6719. }
  6720. break;
  6721. /*!
  6722. ### M500 - Store settings in EEPROM <a href="https://reprap.org/wiki/G-code#M500:_Store_parameters_in_non-volatile_storage">M500: Store parameters in non-volatile storage</a>
  6723. Save current parameters to EEPROM.
  6724. */
  6725. case 500:
  6726. {
  6727. Config_StoreSettings();
  6728. }
  6729. break;
  6730. /*!
  6731. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6732. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6733. */
  6734. case 501:
  6735. {
  6736. Config_RetrieveSettings();
  6737. }
  6738. break;
  6739. /*!
  6740. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6741. This command resets all tunable parameters to their default values, as set in the firmware's configuration files. This doesn't reset any parameters stored in the EEPROM, so it must be followed by M500 to write the default settings.
  6742. */
  6743. case 502:
  6744. {
  6745. Config_ResetDefault();
  6746. }
  6747. break;
  6748. /*!
  6749. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6750. This command asks the firmware to reply with the current print settings as set in memory. Settings will differ from EEPROM contents if changed since the last load / save. The reply output includes the G-Code commands to produce each setting. For example, Steps-Per-Unit values are displayed as an M92 command.
  6751. */
  6752. case 503:
  6753. {
  6754. Config_PrintSettings();
  6755. }
  6756. break;
  6757. /*!
  6758. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6759. Resets the language to English.
  6760. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6761. */
  6762. case 509:
  6763. {
  6764. lang_reset();
  6765. SERIAL_ECHO_START;
  6766. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6767. }
  6768. break;
  6769. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6770. /*!
  6771. ### M540 - Abort print on endstop hit (enable/disable) <a href="https://reprap.org/wiki/G-code#M540_in_Marlin:_Enable.2FDisable_.22Stop_SD_Print_on_Endstop_Hit.22">M540 in Marlin: Enable/Disable "Stop SD Print on Endstop Hit"</a>
  6772. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. You must define `ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED`.
  6773. #### Usage
  6774. M540 [ S ]
  6775. #### Parameters
  6776. - `S` - disabled=0, enabled=1
  6777. */
  6778. case 540:
  6779. {
  6780. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6781. }
  6782. break;
  6783. #endif
  6784. /*!
  6785. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6786. Sets the Z-probe Z offset. This offset is used to determine the actual Z position of the nozzle when using a probe to home Z with G28. This value may also be used by G81 (Prusa) / G29 (Marlin) to apply correction to the Z position.
  6787. This value represents the distance from nozzle to the bed surface at the point where the probe is triggered. This value will be negative for typical switch probes, inductive probes, and setups where the nozzle makes a circuit with a raised metal contact. This setting will be greater than zero on machines where the nozzle itself is used as the probe, pressing down on the bed to press a switch. (This is a common setup on delta machines.)
  6788. #### Usage
  6789. M851 [ Z ]
  6790. #### Parameters
  6791. - `Z` - Z offset probe to nozzle.
  6792. */
  6793. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6794. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6795. {
  6796. float value;
  6797. if (code_seen('Z'))
  6798. {
  6799. value = code_value();
  6800. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6801. {
  6802. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6803. SERIAL_ECHO_START;
  6804. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6805. SERIAL_PROTOCOLLN("");
  6806. }
  6807. else
  6808. {
  6809. SERIAL_ECHO_START;
  6810. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6811. SERIAL_ECHORPGM(MSG_Z_MIN);
  6812. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6813. SERIAL_ECHORPGM(MSG_Z_MAX);
  6814. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6815. SERIAL_PROTOCOLLN("");
  6816. }
  6817. }
  6818. else
  6819. {
  6820. SERIAL_ECHO_START;
  6821. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6822. SERIAL_ECHO(-cs.zprobe_zoffset);
  6823. SERIAL_PROTOCOLLN("");
  6824. }
  6825. break;
  6826. }
  6827. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6828. #ifdef FILAMENTCHANGEENABLE
  6829. /*!
  6830. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6831. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6832. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6833. #### Usage
  6834. M600 [ X | Y | Z | E | L | AUTO ]
  6835. - `X` - X position, default 211
  6836. - `Y` - Y position, default 0
  6837. - `Z` - relative lift Z, default 2.
  6838. - `E` - initial retract, default -2
  6839. - `L` - later retract distance for removal, default -80
  6840. - `AUTO` - Automatically (only with MMU)
  6841. */
  6842. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6843. {
  6844. st_synchronize();
  6845. float x_position = current_position[X_AXIS];
  6846. float y_position = current_position[Y_AXIS];
  6847. float z_shift = 0; // is it necessary to be a float?
  6848. float e_shift_init = 0;
  6849. float e_shift_late = 0;
  6850. bool automatic = false;
  6851. //Retract extruder
  6852. if(code_seen('E'))
  6853. {
  6854. e_shift_init = code_value();
  6855. }
  6856. else
  6857. {
  6858. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6859. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6860. #endif
  6861. }
  6862. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6863. if (code_seen('L'))
  6864. {
  6865. e_shift_late = code_value();
  6866. }
  6867. else
  6868. {
  6869. #ifdef FILAMENTCHANGE_FINALRETRACT
  6870. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6871. #endif
  6872. }
  6873. //Lift Z
  6874. if(code_seen('Z'))
  6875. {
  6876. z_shift = code_value();
  6877. }
  6878. else
  6879. {
  6880. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6881. }
  6882. //Move XY to side
  6883. if(code_seen('X'))
  6884. {
  6885. x_position = code_value();
  6886. }
  6887. else
  6888. {
  6889. #ifdef FILAMENTCHANGE_XPOS
  6890. x_position = FILAMENTCHANGE_XPOS;
  6891. #endif
  6892. }
  6893. if(code_seen('Y'))
  6894. {
  6895. y_position = code_value();
  6896. }
  6897. else
  6898. {
  6899. #ifdef FILAMENTCHANGE_YPOS
  6900. y_position = FILAMENTCHANGE_YPOS ;
  6901. #endif
  6902. }
  6903. if (mmu_enabled && code_seen("AUTO"))
  6904. automatic = true;
  6905. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6906. }
  6907. break;
  6908. #endif //FILAMENTCHANGEENABLE
  6909. /*!
  6910. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6911. */
  6912. /*!
  6913. ### M125 - Pause print (TODO: not implemented)
  6914. */
  6915. /*!
  6916. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6917. */
  6918. case 25:
  6919. case 601:
  6920. {
  6921. if (!isPrintPaused)
  6922. {
  6923. st_synchronize();
  6924. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6925. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6926. lcd_pause_print();
  6927. }
  6928. }
  6929. break;
  6930. /*!
  6931. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6932. */
  6933. case 602: {
  6934. if (isPrintPaused)
  6935. lcd_resume_print();
  6936. }
  6937. break;
  6938. /*!
  6939. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6940. */
  6941. case 603: {
  6942. lcd_print_stop();
  6943. }
  6944. break;
  6945. #ifdef PINDA_THERMISTOR
  6946. /*!
  6947. ### M860 - Wait for extruder temperature (PINDA) <a href="https://reprap.org/wiki/G-code#M860_Wait_for_Probe_Temperature">M860 Wait for Probe Temperature</a>
  6948. Wait for PINDA thermistor to reach target temperature
  6949. #### Usage
  6950. M860 [ S ]
  6951. #### Parameters
  6952. - `S` - Target temperature
  6953. */
  6954. case 860:
  6955. {
  6956. int set_target_pinda = 0;
  6957. if (code_seen('S')) {
  6958. set_target_pinda = code_value();
  6959. }
  6960. else {
  6961. break;
  6962. }
  6963. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6964. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6965. SERIAL_PROTOCOL(set_target_pinda);
  6966. SERIAL_PROTOCOLLN("");
  6967. codenum = _millis();
  6968. cancel_heatup = false;
  6969. bool is_pinda_cooling = false;
  6970. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6971. is_pinda_cooling = true;
  6972. }
  6973. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6974. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6975. {
  6976. SERIAL_PROTOCOLPGM("P:");
  6977. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6978. SERIAL_PROTOCOL('/');
  6979. SERIAL_PROTOCOLLN(set_target_pinda);
  6980. codenum = _millis();
  6981. }
  6982. manage_heater();
  6983. manage_inactivity();
  6984. lcd_update(0);
  6985. }
  6986. LCD_MESSAGERPGM(MSG_OK);
  6987. break;
  6988. }
  6989. /*!
  6990. ### M861 - Set/Get PINDA temperature compensation offsets <a href="https://reprap.org/wiki/G-code#M861_Set_Probe_Thermal_Compensation">M861 Set Probe Thermal Compensation</a>
  6991. Set compensation ustep value `S` for compensation table index `I`.
  6992. #### Usage
  6993. M861 [ ? | ! | Z | S | I ]
  6994. #### Parameters
  6995. - `?` - Print current EEPROM offset values
  6996. - `!` - Set factory default values
  6997. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6998. - `S` - Microsteps
  6999. - `I` - Table index
  7000. */
  7001. case 861:
  7002. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  7003. uint8_t cal_status = calibration_status_pinda();
  7004. int16_t usteps = 0;
  7005. cal_status ? SERIAL_PROTOCOLLN("PINDA cal status: 1") : SERIAL_PROTOCOLLN("PINDA cal status: 0");
  7006. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  7007. for (uint8_t i = 0; i < 6; i++)
  7008. {
  7009. if(i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &usteps);
  7010. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7011. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7012. SERIAL_PROTOCOLPGM(", ");
  7013. SERIAL_PROTOCOL(35 + (i * 5));
  7014. SERIAL_PROTOCOLPGM(", ");
  7015. SERIAL_PROTOCOL(usteps);
  7016. SERIAL_PROTOCOLPGM(", ");
  7017. SERIAL_PROTOCOL(mm * 1000);
  7018. SERIAL_PROTOCOLLN("");
  7019. }
  7020. }
  7021. else if (code_seen('!')) { // ! - Set factory default values
  7022. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  7023. int16_t z_shift = 8; //40C - 20um - 8usteps
  7024. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT, &z_shift);
  7025. z_shift = 24; //45C - 60um - 24usteps
  7026. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 2, &z_shift);
  7027. z_shift = 48; //50C - 120um - 48usteps
  7028. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 4, &z_shift);
  7029. z_shift = 80; //55C - 200um - 80usteps
  7030. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 6, &z_shift);
  7031. z_shift = 120; //60C - 300um - 120usteps
  7032. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 8, &z_shift);
  7033. SERIAL_PROTOCOLLN("factory restored");
  7034. }
  7035. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  7036. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  7037. int16_t z_shift = 0;
  7038. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  7039. SERIAL_PROTOCOLLN("zerorized");
  7040. }
  7041. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  7042. int16_t usteps = code_value();
  7043. if (code_seen('I')) {
  7044. uint8_t index = code_value();
  7045. if (index < 5) {
  7046. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + index * 2, &usteps);
  7047. SERIAL_PROTOCOLLN("OK");
  7048. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  7049. for (uint8_t i = 0; i < 6; i++)
  7050. {
  7051. usteps = 0;
  7052. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i - 1) * 2, &usteps);
  7053. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7054. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7055. SERIAL_PROTOCOLPGM(", ");
  7056. SERIAL_PROTOCOL(35 + (i * 5));
  7057. SERIAL_PROTOCOLPGM(", ");
  7058. SERIAL_PROTOCOL(usteps);
  7059. SERIAL_PROTOCOLPGM(", ");
  7060. SERIAL_PROTOCOL(mm * 1000);
  7061. SERIAL_PROTOCOLLN("");
  7062. }
  7063. }
  7064. }
  7065. }
  7066. else {
  7067. SERIAL_PROTOCOLPGM("no valid command");
  7068. }
  7069. break;
  7070. #endif //PINDA_THERMISTOR
  7071. /*!
  7072. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  7073. Checks the parameters of the printer and gcode and performs compatibility check
  7074. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  7075. - M862.2 { P<model_code> | Q }
  7076. - M862.3 { P"<model_name>" | Q }
  7077. - M862.4 { P<fw_version> | Q }
  7078. - M862.5 { P<gcode_level> | Q }
  7079. When run with P<> argument, the check is performed against the input value.
  7080. When run with Q argument, the current value is shown.
  7081. M862.3 accepts text identifiers of printer types too.
  7082. The syntax of M862.3 is (note the quotes around the type):
  7083. M862.3 P "MK3S"
  7084. Accepted printer type identifiers and their numeric counterparts:
  7085. - MK1 (100)
  7086. - MK2 (200)
  7087. - MK2MM (201)
  7088. - MK2S (202)
  7089. - MK2SMM (203)
  7090. - MK2.5 (250)
  7091. - MK2.5MMU2 (20250)
  7092. - MK2.5S (252)
  7093. - MK2.5SMMU2S (20252)
  7094. - MK3 (300)
  7095. - MK3MMU2 (20300)
  7096. - MK3S (302)
  7097. - MK3SMMU2S (20302)
  7098. */
  7099. case 862: // M862: print checking
  7100. float nDummy;
  7101. uint8_t nCommand;
  7102. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7103. switch((ClPrintChecking)nCommand)
  7104. {
  7105. case ClPrintChecking::_Nozzle: // ~ .1
  7106. uint16_t nDiameter;
  7107. if(code_seen('P'))
  7108. {
  7109. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7110. nozzle_diameter_check(nDiameter);
  7111. }
  7112. /*
  7113. else if(code_seen('S')&&farm_mode)
  7114. {
  7115. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7116. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  7117. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  7118. }
  7119. */
  7120. else if(code_seen('Q'))
  7121. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7122. break;
  7123. case ClPrintChecking::_Model: // ~ .2
  7124. if(code_seen('P'))
  7125. {
  7126. uint16_t nPrinterModel;
  7127. nPrinterModel=(uint16_t)code_value_long();
  7128. printer_model_check(nPrinterModel);
  7129. }
  7130. else if(code_seen('Q'))
  7131. SERIAL_PROTOCOLLN(nPrinterType);
  7132. break;
  7133. case ClPrintChecking::_Smodel: // ~ .3
  7134. if(code_seen('P'))
  7135. printer_smodel_check(strchr_pointer);
  7136. else if(code_seen('Q'))
  7137. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7138. break;
  7139. case ClPrintChecking::_Version: // ~ .4
  7140. if(code_seen('P'))
  7141. fw_version_check(++strchr_pointer);
  7142. else if(code_seen('Q'))
  7143. SERIAL_PROTOCOLLN(FW_VERSION);
  7144. break;
  7145. case ClPrintChecking::_Gcode: // ~ .5
  7146. if(code_seen('P'))
  7147. {
  7148. uint16_t nGcodeLevel;
  7149. nGcodeLevel=(uint16_t)code_value_long();
  7150. gcode_level_check(nGcodeLevel);
  7151. }
  7152. else if(code_seen('Q'))
  7153. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7154. break;
  7155. }
  7156. break;
  7157. #ifdef LIN_ADVANCE
  7158. /*!
  7159. ### M900 - Set Linear advance options <a href="https://reprap.org/wiki/G-code#M900_Set_Linear_Advance_Scaling_Factors">M900 Set Linear Advance Scaling Factors</a>
  7160. Sets the advance extrusion factors for Linear Advance. If any of the R, W, H, or D parameters are set to zero the ratio will be computed dynamically during printing.
  7161. #### Usage
  7162. M900 [ K | R | W | H | D]
  7163. #### Parameters
  7164. - `K` - Advance K factor
  7165. - `R` - Set ratio directly (overrides WH/D)
  7166. - `W` - Width
  7167. - `H` - Height
  7168. - `D` - Diameter Set ratio from WH/D
  7169. */
  7170. case 900:
  7171. gcode_M900();
  7172. break;
  7173. #endif
  7174. /*!
  7175. ### M907 - Set digital trimpot motor current in mA using axis codes <a href="https://reprap.org/wiki/G-code#M907:_Set_digital_trimpot_motor">M907: Set digital trimpot motor</a>
  7176. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7177. #### Usage
  7178. M907 [ X | Y | Z | E | B | S ]
  7179. #### Parameters
  7180. - `X` - X motor driver
  7181. - `Y` - Y motor driver
  7182. - `Z` - Z motor driver
  7183. - `E` - Extruder motor driver
  7184. - `B` - Second Extruder motor driver
  7185. - `S` - All motors
  7186. */
  7187. case 907:
  7188. {
  7189. #ifdef TMC2130
  7190. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7191. for (int i = 0; i < NUM_AXIS; i++)
  7192. if(code_seen(axis_codes[i]))
  7193. {
  7194. long cur_mA = code_value_long();
  7195. uint8_t val = tmc2130_cur2val(cur_mA);
  7196. tmc2130_set_current_h(i, val);
  7197. tmc2130_set_current_r(i, val);
  7198. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7199. }
  7200. #else //TMC2130
  7201. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7202. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7203. if(code_seen('B')) st_current_set(4,code_value());
  7204. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7205. #endif
  7206. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7207. if(code_seen('X')) st_current_set(0, code_value());
  7208. #endif
  7209. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7210. if(code_seen('Z')) st_current_set(1, code_value());
  7211. #endif
  7212. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7213. if(code_seen('E')) st_current_set(2, code_value());
  7214. #endif
  7215. #endif //TMC2130
  7216. }
  7217. break;
  7218. /*!
  7219. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7220. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7221. #### Usage
  7222. M908 [ P | S ]
  7223. #### Parameters
  7224. - `P` - channel
  7225. - `S` - current
  7226. */
  7227. case 908:
  7228. {
  7229. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7230. uint8_t channel,current;
  7231. if(code_seen('P')) channel=code_value();
  7232. if(code_seen('S')) current=code_value();
  7233. digitalPotWrite(channel, current);
  7234. #endif
  7235. }
  7236. break;
  7237. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7238. /*!
  7239. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7240. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7241. */
  7242. case 910:
  7243. {
  7244. tmc2130_init();
  7245. }
  7246. break;
  7247. /*!
  7248. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7249. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7250. #### Usage
  7251. M911 [ X | Y | Z | E ]
  7252. #### Parameters
  7253. - `X` - X stepper driver holding current value
  7254. - `Y` - Y stepper driver holding current value
  7255. - `Z` - Z stepper driver holding current value
  7256. - `E` - Extruder stepper driver holding current value
  7257. */
  7258. case 911:
  7259. {
  7260. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7261. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7262. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7263. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7264. }
  7265. break;
  7266. /*!
  7267. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7268. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7269. #### Usage
  7270. M912 [ X | Y | Z | E ]
  7271. #### Parameters
  7272. - `X` - X stepper driver running current value
  7273. - `Y` - Y stepper driver running current value
  7274. - `Z` - Z stepper driver running current value
  7275. - `E` - Extruder stepper driver running current value
  7276. */
  7277. case 912:
  7278. {
  7279. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7280. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7281. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7282. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7283. }
  7284. break;
  7285. /*!
  7286. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7287. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7288. Shows TMC2130 currents.
  7289. */
  7290. case 913:
  7291. {
  7292. tmc2130_print_currents();
  7293. }
  7294. break;
  7295. /*!
  7296. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7297. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7298. */
  7299. case 914:
  7300. {
  7301. tmc2130_mode = TMC2130_MODE_NORMAL;
  7302. update_mode_profile();
  7303. tmc2130_init();
  7304. }
  7305. break;
  7306. /*!
  7307. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7308. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7309. */
  7310. case 915:
  7311. {
  7312. tmc2130_mode = TMC2130_MODE_SILENT;
  7313. update_mode_profile();
  7314. tmc2130_init();
  7315. }
  7316. break;
  7317. /*!
  7318. ### M916 - Set TMC2130 Stallguard sensitivity threshold <a href="https://reprap.org/wiki/G-code#M916:_Set_TMC2130_Stallguard_sensitivity_threshold">M916: Set TMC2130 Stallguard sensitivity threshold</a>
  7319. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7320. #### Usage
  7321. M916 [ X | Y | Z | E ]
  7322. #### Parameters
  7323. - `X` - X stepper driver stallguard sensitivity threshold value
  7324. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7325. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7326. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7327. */
  7328. case 916:
  7329. {
  7330. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7331. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7332. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7333. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7334. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7335. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7336. }
  7337. break;
  7338. /*!
  7339. ### M917 - Set TMC2130 PWM amplitude offset (pwm_ampl) <a href="https://reprap.org/wiki/G-code#M917:_Set_TMC2130_PWM_amplitude_offset_.28pwm_ampl.29">M917: Set TMC2130 PWM amplitude offset (pwm_ampl)</a>
  7340. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7341. #### Usage
  7342. M917 [ X | Y | Z | E ]
  7343. #### Parameters
  7344. - `X` - X stepper driver PWM amplitude offset value
  7345. - `Y` - Y stepper driver PWM amplitude offset value
  7346. - `Z` - Z stepper driver PWM amplitude offset value
  7347. - `E` - Extruder stepper driver PWM amplitude offset value
  7348. */
  7349. case 917:
  7350. {
  7351. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7352. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7353. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7354. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7355. }
  7356. break;
  7357. /*!
  7358. ### M918 - Set TMC2130 PWM amplitude gradient (pwm_grad) <a href="https://reprap.org/wiki/G-code#M918:_Set_TMC2130_PWM_amplitude_gradient_.28pwm_grad.29">M918: Set TMC2130 PWM amplitude gradient (pwm_grad)</a>
  7359. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7360. #### Usage
  7361. M918 [ X | Y | Z | E ]
  7362. #### Parameters
  7363. - `X` - X stepper driver PWM amplitude gradient value
  7364. - `Y` - Y stepper driver PWM amplitude gradient value
  7365. - `Z` - Z stepper driver PWM amplitude gradient value
  7366. - `E` - Extruder stepper driver PWM amplitude gradient value
  7367. */
  7368. case 918:
  7369. {
  7370. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7371. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7372. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7373. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7374. }
  7375. break;
  7376. #endif //TMC2130_SERVICE_CODES_M910_M918
  7377. /*!
  7378. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7379. Printers with TMC2130 drivers have `X`, `Y`, `Z` and `E` as options. The steps-per-unit value is updated accordingly. Not all resolutions are valid!
  7380. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7381. #### Usage
  7382. M350 [ X | Y | Z | E | B | S ]
  7383. #### Parameters
  7384. - `X` - X new resolution
  7385. - `Y` - Y new resolution
  7386. - `Z` - Z new resolution
  7387. - `E` - E new resolution
  7388. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7389. - `B` - Second extruder new resolution
  7390. - `S` - All axes new resolution
  7391. */
  7392. case 350:
  7393. {
  7394. #ifdef TMC2130
  7395. for (int i=0; i<NUM_AXIS; i++)
  7396. {
  7397. if(code_seen(axis_codes[i]))
  7398. {
  7399. uint16_t res_new = code_value();
  7400. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7401. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7402. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7403. if (res_valid)
  7404. {
  7405. st_synchronize();
  7406. uint16_t res = tmc2130_get_res(i);
  7407. tmc2130_set_res(i, res_new);
  7408. cs.axis_ustep_resolution[i] = res_new;
  7409. if (res_new > res)
  7410. {
  7411. uint16_t fac = (res_new / res);
  7412. cs.axis_steps_per_unit[i] *= fac;
  7413. position[i] *= fac;
  7414. }
  7415. else
  7416. {
  7417. uint16_t fac = (res / res_new);
  7418. cs.axis_steps_per_unit[i] /= fac;
  7419. position[i] /= fac;
  7420. }
  7421. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  7422. if (i == E_AXIS)
  7423. fsensor_set_axis_steps_per_unit(cs.axis_steps_per_unit[i]);
  7424. #endif
  7425. }
  7426. }
  7427. }
  7428. #else //TMC2130
  7429. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7430. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7431. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7432. if(code_seen('B')) microstep_mode(4,code_value());
  7433. microstep_readings();
  7434. #endif
  7435. #endif //TMC2130
  7436. }
  7437. break;
  7438. /*!
  7439. ### M351 - Toggle Microstep Pins <a href="https://reprap.org/wiki/G-code#M351:_Toggle_MS1_MS2_pins_directly">M351: Toggle MS1 MS2 pins directly</a>
  7440. Toggle MS1 MS2 pins directly.
  7441. #### Usage
  7442. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7443. #### Parameters
  7444. - `X` - Update X axis
  7445. - `Y` - Update Y axis
  7446. - `Z` - Update Z axis
  7447. - `E` - Update E axis
  7448. - `S` - which MSx pin to toggle
  7449. - `B` - new pin value
  7450. */
  7451. case 351:
  7452. {
  7453. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7454. if(code_seen('S')) switch((int)code_value())
  7455. {
  7456. case 1:
  7457. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7458. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7459. break;
  7460. case 2:
  7461. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7462. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7463. break;
  7464. }
  7465. microstep_readings();
  7466. #endif
  7467. }
  7468. break;
  7469. /*!
  7470. ### M701 - Load filament <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7471. */
  7472. case 701:
  7473. {
  7474. if (mmu_enabled && code_seen('E'))
  7475. tmp_extruder = code_value();
  7476. gcode_M701();
  7477. }
  7478. break;
  7479. /*!
  7480. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7481. #### Usage
  7482. M702 [ U | C ]
  7483. #### Parameters
  7484. - `U` - Unload all filaments used in current print
  7485. - `C` - Unload just current filament
  7486. - without any parameters unload all filaments
  7487. */
  7488. case 702:
  7489. {
  7490. #ifdef SNMM
  7491. if (code_seen('U'))
  7492. extr_unload_used(); //! if "U" unload all filaments which were used in current print
  7493. else if (code_seen('C'))
  7494. extr_unload(); //! if "C" unload just current filament
  7495. else
  7496. extr_unload_all(); //! otherwise unload all filaments
  7497. #else
  7498. if (code_seen('C')) {
  7499. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  7500. }
  7501. else {
  7502. if(mmu_enabled) extr_unload(); //! unload current filament
  7503. else unload_filament();
  7504. }
  7505. #endif //SNMM
  7506. }
  7507. break;
  7508. /*!
  7509. ### M999 - Restart after being stopped <a href="https://reprap.org/wiki/G-code#M999:_Restart_after_being_stopped_by_error">M999: Restart after being stopped by error</a>
  7510. @todo Usually doesn't work. Should be fixed or removed. Most of the time, if `Stopped` it set, the print fails and is unrecoverable.
  7511. */
  7512. case 999:
  7513. Stopped = false;
  7514. lcd_reset_alert_level();
  7515. gcode_LastN = Stopped_gcode_LastN;
  7516. FlushSerialRequestResend();
  7517. break;
  7518. /*!
  7519. #### End of M-Commands
  7520. */
  7521. default:
  7522. printf_P(PSTR("Unknown M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  7523. }
  7524. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7525. mcode_in_progress = 0;
  7526. }
  7527. }
  7528. // end if(code_seen('M')) (end of M codes)
  7529. /*!
  7530. -----------------------------------------------------------------------------------------
  7531. # T Codes
  7532. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7533. #### For MMU_V2:
  7534. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7535. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7536. @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.
  7537. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7538. */
  7539. else if(code_seen('T'))
  7540. {
  7541. int index;
  7542. bool load_to_nozzle = false;
  7543. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  7544. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  7545. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  7546. SERIAL_ECHOLNPGM("Invalid T code.");
  7547. }
  7548. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  7549. if (mmu_enabled)
  7550. {
  7551. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  7552. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7553. {
  7554. printf_P(PSTR("Duplicate T-code ignored.\n"));
  7555. }
  7556. else
  7557. {
  7558. st_synchronize();
  7559. mmu_command(MmuCmd::T0 + tmp_extruder);
  7560. manage_response(true, true, MMU_TCODE_MOVE);
  7561. }
  7562. }
  7563. }
  7564. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  7565. if (mmu_enabled)
  7566. {
  7567. st_synchronize();
  7568. mmu_continue_loading(is_usb_printing || (lcd_commands_type == LcdCommands::Layer1Cal));
  7569. mmu_extruder = tmp_extruder; //filament change is finished
  7570. mmu_load_to_nozzle();
  7571. }
  7572. }
  7573. else {
  7574. if (*(strchr_pointer + index) == '?')
  7575. {
  7576. if(mmu_enabled)
  7577. {
  7578. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  7579. load_to_nozzle = true;
  7580. } else
  7581. {
  7582. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_EXTRUDER), _T(MSG_EXTRUDER));
  7583. }
  7584. }
  7585. else {
  7586. tmp_extruder = code_value();
  7587. if (mmu_enabled && lcd_autoDepleteEnabled())
  7588. {
  7589. tmp_extruder = ad_getAlternative(tmp_extruder);
  7590. }
  7591. }
  7592. st_synchronize();
  7593. snmm_filaments_used |= (1 << tmp_extruder); //for stop print
  7594. if (mmu_enabled)
  7595. {
  7596. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7597. {
  7598. printf_P(PSTR("Duplicate T-code ignored.\n"));
  7599. }
  7600. else
  7601. {
  7602. #if defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7603. if (EEPROM_MMU_CUTTER_ENABLED_always == eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED))
  7604. {
  7605. mmu_command(MmuCmd::K0 + tmp_extruder);
  7606. manage_response(true, true, MMU_UNLOAD_MOVE);
  7607. }
  7608. #endif //defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7609. mmu_command(MmuCmd::T0 + tmp_extruder);
  7610. manage_response(true, true, MMU_TCODE_MOVE);
  7611. mmu_continue_loading(is_usb_printing || (lcd_commands_type == LcdCommands::Layer1Cal));
  7612. mmu_extruder = tmp_extruder; //filament change is finished
  7613. if (load_to_nozzle)// for single material usage with mmu
  7614. {
  7615. mmu_load_to_nozzle();
  7616. }
  7617. }
  7618. }
  7619. else
  7620. {
  7621. #ifdef SNMM
  7622. mmu_extruder = tmp_extruder;
  7623. _delay(100);
  7624. disable_e0();
  7625. disable_e1();
  7626. disable_e2();
  7627. pinMode(E_MUX0_PIN, OUTPUT);
  7628. pinMode(E_MUX1_PIN, OUTPUT);
  7629. _delay(100);
  7630. SERIAL_ECHO_START;
  7631. SERIAL_ECHO("T:");
  7632. SERIAL_ECHOLN((int)tmp_extruder);
  7633. switch (tmp_extruder) {
  7634. case 1:
  7635. WRITE(E_MUX0_PIN, HIGH);
  7636. WRITE(E_MUX1_PIN, LOW);
  7637. break;
  7638. case 2:
  7639. WRITE(E_MUX0_PIN, LOW);
  7640. WRITE(E_MUX1_PIN, HIGH);
  7641. break;
  7642. case 3:
  7643. WRITE(E_MUX0_PIN, HIGH);
  7644. WRITE(E_MUX1_PIN, HIGH);
  7645. break;
  7646. default:
  7647. WRITE(E_MUX0_PIN, LOW);
  7648. WRITE(E_MUX1_PIN, LOW);
  7649. break;
  7650. }
  7651. _delay(100);
  7652. #else //SNMM
  7653. if (tmp_extruder >= EXTRUDERS) {
  7654. SERIAL_ECHO_START;
  7655. SERIAL_ECHO('T');
  7656. SERIAL_PROTOCOLLN((int)tmp_extruder);
  7657. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER
  7658. }
  7659. else {
  7660. #if EXTRUDERS > 1
  7661. boolean make_move = false;
  7662. #endif
  7663. if (code_seen('F')) {
  7664. #if EXTRUDERS > 1
  7665. make_move = true;
  7666. #endif
  7667. next_feedrate = code_value();
  7668. if (next_feedrate > 0.0) {
  7669. feedrate = next_feedrate;
  7670. }
  7671. }
  7672. #if EXTRUDERS > 1
  7673. if (tmp_extruder != active_extruder) {
  7674. // Save current position to return to after applying extruder offset
  7675. memcpy(destination, current_position, sizeof(destination));
  7676. // Offset extruder (only by XY)
  7677. int i;
  7678. for (i = 0; i < 2; i++) {
  7679. current_position[i] = current_position[i] -
  7680. extruder_offset[i][active_extruder] +
  7681. extruder_offset[i][tmp_extruder];
  7682. }
  7683. // Set the new active extruder and position
  7684. active_extruder = tmp_extruder;
  7685. plan_set_position_curposXYZE();
  7686. // Move to the old position if 'F' was in the parameters
  7687. if (make_move && Stopped == false) {
  7688. prepare_move();
  7689. }
  7690. }
  7691. #endif
  7692. SERIAL_ECHO_START;
  7693. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER
  7694. SERIAL_PROTOCOLLN((int)active_extruder);
  7695. }
  7696. #endif //SNMM
  7697. }
  7698. }
  7699. } // end if(code_seen('T')) (end of T codes)
  7700. /*!
  7701. #### End of T-Codes
  7702. */
  7703. /**
  7704. *---------------------------------------------------------------------------------
  7705. *# D codes
  7706. */
  7707. else if (code_seen('D')) // D codes (debug)
  7708. {
  7709. switch((int)code_value())
  7710. {
  7711. /*!
  7712. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7713. */
  7714. case -1:
  7715. dcode__1(); break;
  7716. #ifdef DEBUG_DCODES
  7717. /*!
  7718. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7719. #### Usage
  7720. D0 [ B ]
  7721. #### Parameters
  7722. - `B` - Bootloader
  7723. */
  7724. case 0:
  7725. dcode_0(); break;
  7726. /*!
  7727. *
  7728. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7729. D1
  7730. *
  7731. */
  7732. case 1:
  7733. dcode_1(); break;
  7734. /*!
  7735. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7736. This command can be used without any additional parameters. It will read the entire RAM.
  7737. #### Usage
  7738. D2 [ A | C | X ]
  7739. #### Parameters
  7740. - `A` - Address (x0000-x1fff)
  7741. - `C` - Count (1-8192)
  7742. - `X` - Data
  7743. #### Notes
  7744. - The hex address needs to be lowercase without the 0 before the x
  7745. - Count is decimal
  7746. - The hex data needs to be lowercase
  7747. */
  7748. case 2:
  7749. dcode_2(); break;
  7750. #endif //DEBUG_DCODES
  7751. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7752. /*!
  7753. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7754. This command can be used without any additional parameters. It will read the entire eeprom.
  7755. #### Usage
  7756. D3 [ A | C | X ]
  7757. #### Parameters
  7758. - `A` - Address (x0000-x0fff)
  7759. - `C` - Count (1-4096)
  7760. - `X` - Data (hex)
  7761. #### Notes
  7762. - The hex address needs to be lowercase without the 0 before the x
  7763. - Count is decimal
  7764. - The hex data needs to be lowercase
  7765. */
  7766. case 3:
  7767. dcode_3(); break;
  7768. #endif //DEBUG_DCODE3
  7769. #ifdef DEBUG_DCODES
  7770. /*!
  7771. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7772. To read the digital value of a pin you need only to define the pin number.
  7773. #### Usage
  7774. D4 [ P | F | V ]
  7775. #### Parameters
  7776. - `P` - Pin (0-255)
  7777. - `F` - Function in/out (0/1)
  7778. - `V` - Value (0/1)
  7779. */
  7780. case 4:
  7781. dcode_4(); break;
  7782. #endif //DEBUG_DCODES
  7783. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7784. /*!
  7785. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7786. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7787. #### Usage
  7788. D5 [ A | C | X | E ]
  7789. #### Parameters
  7790. - `A` - Address (x00000-x3ffff)
  7791. - `C` - Count (1-8192)
  7792. - `X` - Data (hex)
  7793. - `E` - Erase
  7794. #### Notes
  7795. - The hex address needs to be lowercase without the 0 before the x
  7796. - Count is decimal
  7797. - The hex data needs to be lowercase
  7798. */
  7799. case 5:
  7800. dcode_5(); break;
  7801. #endif //DEBUG_DCODE5
  7802. #ifdef DEBUG_DCODES
  7803. /*!
  7804. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7805. Reserved
  7806. */
  7807. case 6:
  7808. dcode_6(); break;
  7809. /*!
  7810. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7811. Reserved
  7812. */
  7813. case 7:
  7814. dcode_7(); break;
  7815. /*!
  7816. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7817. #### Usage
  7818. D8 [ ? | ! | P | Z ]
  7819. #### Parameters
  7820. - `?` - Read PINDA temperature shift values
  7821. - `!` - Reset PINDA temperature shift values to default
  7822. - `P` - Pinda temperature [C]
  7823. - `Z` - Z Offset [mm]
  7824. */
  7825. case 8:
  7826. dcode_8(); break;
  7827. /*!
  7828. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7829. #### Usage
  7830. D9 [ I | V ]
  7831. #### Parameters
  7832. - `I` - ADC channel index
  7833. - `0` - Heater 0 temperature
  7834. - `1` - Heater 1 temperature
  7835. - `2` - Bed temperature
  7836. - `3` - PINDA temperature
  7837. - `4` - PWR voltage
  7838. - `5` - Ambient temperature
  7839. - `6` - BED voltage
  7840. - `V` Value to be written as simulated
  7841. */
  7842. case 9:
  7843. dcode_9(); break;
  7844. /*!
  7845. ### D10 - Set XYZ calibration = OK <a href="https://reprap.org/wiki/G-code#D10:_Set_XYZ_calibration_.3D_OK">D10: Set XYZ calibration = OK</a>
  7846. */
  7847. case 10:
  7848. dcode_10(); break;
  7849. /*!
  7850. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7851. Writes the current time in the log file.
  7852. */
  7853. #endif //DEBUG_DCODES
  7854. #ifdef HEATBED_ANALYSIS
  7855. /*!
  7856. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7857. This command will log data to SD card file "mesh.txt".
  7858. #### Usage
  7859. D80 [ E | F | G | H | I | J ]
  7860. #### Parameters
  7861. - `E` - Dimension X (default 40)
  7862. - `F` - Dimention Y (default 40)
  7863. - `G` - Points X (default 40)
  7864. - `H` - Points Y (default 40)
  7865. - `I` - Offset X (default 74)
  7866. - `J` - Offset Y (default 34)
  7867. */
  7868. case 80:
  7869. dcode_80(); break;
  7870. /*!
  7871. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7872. This command will log data to SD card file "wldsd.txt".
  7873. #### Usage
  7874. D81 [ E | F | G | H | I | J ]
  7875. #### Parameters
  7876. - `E` - Dimension X (default 40)
  7877. - `F` - Dimention Y (default 40)
  7878. - `G` - Points X (default 40)
  7879. - `H` - Points Y (default 40)
  7880. - `I` - Offset X (default 74)
  7881. - `J` - Offset Y (default 34)
  7882. */
  7883. case 81:
  7884. dcode_81(); break;
  7885. #endif //HEATBED_ANALYSIS
  7886. #ifdef DEBUG_DCODES
  7887. /*!
  7888. ### D106 - Print measured fan speed for different pwm values <a href="https://reprap.org/wiki/G-code#D106:_Print_measured_fan_speed_for_different_pwm_values">D106: Print measured fan speed for different pwm values</a>
  7889. */
  7890. case 106:
  7891. dcode_106(); break;
  7892. #ifdef TMC2130
  7893. /*!
  7894. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7895. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7896. #### Usage
  7897. D2130 [ Axis | Command | Subcommand | Value ]
  7898. #### Parameters
  7899. - Axis
  7900. - `X` - X stepper driver
  7901. - `Y` - Y stepper driver
  7902. - `Z` - Z stepper driver
  7903. - `E` - Extruder stepper driver
  7904. - Commands
  7905. - `0` - Current off
  7906. - `1` - Current on
  7907. - `+` - Single step
  7908. - `-` - Single step oposite direction
  7909. - `NNN` - Value sereval steps
  7910. - `?` - Read register
  7911. - Subcommands for read register
  7912. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7913. - `step` - Step
  7914. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7915. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7916. - `wave` - Microstep linearity compensation curve
  7917. - `!` - Set register
  7918. - Subcommands for set register
  7919. - `mres` - Micro step resolution
  7920. - `step` - Step
  7921. - `wave` - Microstep linearity compensation curve
  7922. - Values for set register
  7923. - `0, 180 --> 250` - Off
  7924. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7925. - `@` - Home calibrate axis
  7926. Examples:
  7927. D2130E?wave
  7928. Print extruder microstep linearity compensation curve
  7929. D2130E!wave0
  7930. Disable extruder linearity compensation curve, (sine curve is used)
  7931. D2130E!wave220
  7932. (sin(x))^1.1 extruder microstep compensation curve used
  7933. Notes:
  7934. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7935. *
  7936. */
  7937. case 2130:
  7938. dcode_2130(); break;
  7939. #endif //TMC2130
  7940. #if (defined (FILAMENT_SENSOR) && defined(PAT9125))
  7941. /*!
  7942. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7943. #### Usage
  7944. D9125 [ ? | ! | R | X | Y | L ]
  7945. #### Parameters
  7946. - `?` - Print values
  7947. - `!` - Print values
  7948. - `R` - Resolution. Not active in code
  7949. - `X` - X values
  7950. - `Y` - Y values
  7951. - `L` - Activate filament sensor log
  7952. */
  7953. case 9125:
  7954. dcode_9125(); break;
  7955. #endif //FILAMENT_SENSOR
  7956. #endif //DEBUG_DCODES
  7957. }
  7958. }
  7959. else
  7960. {
  7961. SERIAL_ECHO_START;
  7962. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7963. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7964. SERIAL_ECHOLNPGM("\"(2)");
  7965. }
  7966. KEEPALIVE_STATE(NOT_BUSY);
  7967. ClearToSend();
  7968. }
  7969. /*!
  7970. #### End of D-Codes
  7971. */
  7972. /** @defgroup GCodes G-Code List
  7973. */
  7974. // ---------------------------------------------------
  7975. void FlushSerialRequestResend()
  7976. {
  7977. //char cmdbuffer[bufindr][100]="Resend:";
  7978. MYSERIAL.flush();
  7979. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7980. }
  7981. // Confirm the execution of a command, if sent from a serial line.
  7982. // Execution of a command from a SD card will not be confirmed.
  7983. void ClearToSend()
  7984. {
  7985. previous_millis_cmd = _millis();
  7986. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7987. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7988. }
  7989. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7990. void update_currents() {
  7991. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7992. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7993. float tmp_motor[3];
  7994. //SERIAL_ECHOLNPGM("Currents updated: ");
  7995. if (destination[Z_AXIS] < Z_SILENT) {
  7996. //SERIAL_ECHOLNPGM("LOW");
  7997. for (uint8_t i = 0; i < 3; i++) {
  7998. st_current_set(i, current_low[i]);
  7999. /*MYSERIAL.print(int(i));
  8000. SERIAL_ECHOPGM(": ");
  8001. MYSERIAL.println(current_low[i]);*/
  8002. }
  8003. }
  8004. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  8005. //SERIAL_ECHOLNPGM("HIGH");
  8006. for (uint8_t i = 0; i < 3; i++) {
  8007. st_current_set(i, current_high[i]);
  8008. /*MYSERIAL.print(int(i));
  8009. SERIAL_ECHOPGM(": ");
  8010. MYSERIAL.println(current_high[i]);*/
  8011. }
  8012. }
  8013. else {
  8014. for (uint8_t i = 0; i < 3; i++) {
  8015. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  8016. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  8017. st_current_set(i, tmp_motor[i]);
  8018. /*MYSERIAL.print(int(i));
  8019. SERIAL_ECHOPGM(": ");
  8020. MYSERIAL.println(tmp_motor[i]);*/
  8021. }
  8022. }
  8023. }
  8024. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8025. void get_coordinates()
  8026. {
  8027. bool seen[4]={false,false,false,false};
  8028. for(int8_t i=0; i < NUM_AXIS; i++) {
  8029. if(code_seen(axis_codes[i]))
  8030. {
  8031. bool relative = axis_relative_modes & (1 << i);
  8032. destination[i] = (float)code_value();
  8033. if (i == E_AXIS) {
  8034. float emult = extruder_multiplier[active_extruder];
  8035. if (emult != 1.) {
  8036. if (! relative) {
  8037. destination[i] -= current_position[i];
  8038. relative = true;
  8039. }
  8040. destination[i] *= emult;
  8041. }
  8042. }
  8043. if (relative)
  8044. destination[i] += current_position[i];
  8045. seen[i]=true;
  8046. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8047. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  8048. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8049. }
  8050. else destination[i] = current_position[i]; //Are these else lines really needed?
  8051. }
  8052. if(code_seen('F')) {
  8053. next_feedrate = code_value();
  8054. #ifdef MAX_SILENT_FEEDRATE
  8055. if (tmc2130_mode == TMC2130_MODE_SILENT)
  8056. if (next_feedrate > MAX_SILENT_FEEDRATE) next_feedrate = MAX_SILENT_FEEDRATE;
  8057. #endif //MAX_SILENT_FEEDRATE
  8058. if(next_feedrate > 0.0) feedrate = next_feedrate;
  8059. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  8060. {
  8061. // float e_max_speed =
  8062. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  8063. }
  8064. }
  8065. }
  8066. void get_arc_coordinates()
  8067. {
  8068. #ifdef SF_ARC_FIX
  8069. bool relative_mode_backup = relative_mode;
  8070. relative_mode = true;
  8071. #endif
  8072. get_coordinates();
  8073. #ifdef SF_ARC_FIX
  8074. relative_mode=relative_mode_backup;
  8075. #endif
  8076. if(code_seen('I')) {
  8077. offset[0] = code_value();
  8078. }
  8079. else {
  8080. offset[0] = 0.0;
  8081. }
  8082. if(code_seen('J')) {
  8083. offset[1] = code_value();
  8084. }
  8085. else {
  8086. offset[1] = 0.0;
  8087. }
  8088. }
  8089. void clamp_to_software_endstops(float target[3])
  8090. {
  8091. #ifdef DEBUG_DISABLE_SWLIMITS
  8092. return;
  8093. #endif //DEBUG_DISABLE_SWLIMITS
  8094. world2machine_clamp(target[0], target[1]);
  8095. // Clamp the Z coordinate.
  8096. if (min_software_endstops) {
  8097. float negative_z_offset = 0;
  8098. #ifdef ENABLE_AUTO_BED_LEVELING
  8099. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8100. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8101. #endif
  8102. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8103. }
  8104. if (max_software_endstops) {
  8105. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8106. }
  8107. }
  8108. #ifdef MESH_BED_LEVELING
  8109. 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) {
  8110. float dx = x - current_position[X_AXIS];
  8111. float dy = y - current_position[Y_AXIS];
  8112. int n_segments = 0;
  8113. if (mbl.active) {
  8114. float len = abs(dx) + abs(dy);
  8115. if (len > 0)
  8116. // Split to 3cm segments or shorter.
  8117. n_segments = int(ceil(len / 30.f));
  8118. }
  8119. if (n_segments > 1) {
  8120. // In a multi-segment move explicitly set the final target in the plan
  8121. // as the move will be recalculated in it's entirety
  8122. float gcode_target[NUM_AXIS];
  8123. gcode_target[X_AXIS] = x;
  8124. gcode_target[Y_AXIS] = y;
  8125. gcode_target[Z_AXIS] = z;
  8126. gcode_target[E_AXIS] = e;
  8127. float dz = z - current_position[Z_AXIS];
  8128. float de = e - current_position[E_AXIS];
  8129. for (int i = 1; i < n_segments; ++ i) {
  8130. float t = float(i) / float(n_segments);
  8131. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8132. current_position[Y_AXIS] + t * dy,
  8133. current_position[Z_AXIS] + t * dz,
  8134. current_position[E_AXIS] + t * de,
  8135. feed_rate, extruder, gcode_target);
  8136. if (waiting_inside_plan_buffer_line_print_aborted)
  8137. return;
  8138. }
  8139. }
  8140. // The rest of the path.
  8141. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  8142. }
  8143. #endif // MESH_BED_LEVELING
  8144. void prepare_move()
  8145. {
  8146. clamp_to_software_endstops(destination);
  8147. previous_millis_cmd = _millis();
  8148. // Do not use feedmultiply for E or Z only moves
  8149. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  8150. plan_buffer_line_destinationXYZE(feedrate/60);
  8151. }
  8152. else {
  8153. #ifdef MESH_BED_LEVELING
  8154. 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);
  8155. #else
  8156. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8157. #endif
  8158. }
  8159. set_current_to_destination();
  8160. }
  8161. void prepare_arc_move(char isclockwise) {
  8162. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8163. // Trace the arc
  8164. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  8165. // As far as the parser is concerned, the position is now == target. In reality the
  8166. // motion control system might still be processing the action and the real tool position
  8167. // in any intermediate location.
  8168. for(int8_t i=0; i < NUM_AXIS; i++) {
  8169. current_position[i] = destination[i];
  8170. }
  8171. previous_millis_cmd = _millis();
  8172. }
  8173. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8174. #if defined(FAN_PIN)
  8175. #if CONTROLLERFAN_PIN == FAN_PIN
  8176. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8177. #endif
  8178. #endif
  8179. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8180. unsigned long lastMotorCheck = 0;
  8181. void controllerFan()
  8182. {
  8183. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8184. {
  8185. lastMotorCheck = _millis();
  8186. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8187. #if EXTRUDERS > 2
  8188. || !READ(E2_ENABLE_PIN)
  8189. #endif
  8190. #if EXTRUDER > 1
  8191. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8192. || !READ(X2_ENABLE_PIN)
  8193. #endif
  8194. || !READ(E1_ENABLE_PIN)
  8195. #endif
  8196. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8197. {
  8198. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8199. }
  8200. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8201. {
  8202. digitalWrite(CONTROLLERFAN_PIN, 0);
  8203. analogWrite(CONTROLLERFAN_PIN, 0);
  8204. }
  8205. else
  8206. {
  8207. // allows digital or PWM fan output to be used (see M42 handling)
  8208. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8209. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8210. }
  8211. }
  8212. }
  8213. #endif
  8214. #ifdef TEMP_STAT_LEDS
  8215. static bool blue_led = false;
  8216. static bool red_led = false;
  8217. static uint32_t stat_update = 0;
  8218. void handle_status_leds(void) {
  8219. float max_temp = 0.0;
  8220. if(_millis() > stat_update) {
  8221. stat_update += 500; // Update every 0.5s
  8222. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  8223. max_temp = max(max_temp, degHotend(cur_extruder));
  8224. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  8225. }
  8226. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  8227. max_temp = max(max_temp, degTargetBed());
  8228. max_temp = max(max_temp, degBed());
  8229. #endif
  8230. if((max_temp > 55.0) && (red_led == false)) {
  8231. digitalWrite(STAT_LED_RED, 1);
  8232. digitalWrite(STAT_LED_BLUE, 0);
  8233. red_led = true;
  8234. blue_led = false;
  8235. }
  8236. if((max_temp < 54.0) && (blue_led == false)) {
  8237. digitalWrite(STAT_LED_RED, 0);
  8238. digitalWrite(STAT_LED_BLUE, 1);
  8239. red_led = false;
  8240. blue_led = true;
  8241. }
  8242. }
  8243. }
  8244. #endif
  8245. #ifdef SAFETYTIMER
  8246. /**
  8247. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8248. *
  8249. * Full screen blocking notification message is shown after heater turning off.
  8250. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8251. * damage print.
  8252. *
  8253. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8254. */
  8255. static void handleSafetyTimer()
  8256. {
  8257. #if (EXTRUDERS > 1)
  8258. #error Implemented only for one extruder.
  8259. #endif //(EXTRUDERS > 1)
  8260. if ((PRINTER_ACTIVE) || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8261. {
  8262. safetyTimer.stop();
  8263. }
  8264. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8265. {
  8266. safetyTimer.start();
  8267. }
  8268. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8269. {
  8270. setTargetBed(0);
  8271. setAllTargetHotends(0);
  8272. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED
  8273. }
  8274. }
  8275. #endif //SAFETYTIMER
  8276. #ifdef IR_SENSOR_ANALOG
  8277. #define FS_CHECK_COUNT 16
  8278. /// Switching mechanism of the fsensor type.
  8279. /// Called from 2 spots which have a very similar behavior
  8280. /// 1: ClFsensorPCB::_Old -> ClFsensorPCB::_Rev04 and print _i("FS v0.4 or newer")
  8281. /// 2: ClFsensorPCB::_Rev04 -> oFsensorPCB=ClFsensorPCB::_Old and print _i("FS v0.3 or older")
  8282. void manage_inactivity_IR_ANALOG_Check(uint16_t &nFSCheckCount, ClFsensorPCB isVersion, ClFsensorPCB switchTo, const char *statusLineTxt_P) {
  8283. bool bTemp = (!CHECK_ALL_HEATERS);
  8284. bTemp = bTemp && (menu_menu == lcd_status_screen);
  8285. bTemp = bTemp && ((oFsensorPCB == isVersion) || (oFsensorPCB == ClFsensorPCB::_Undef));
  8286. bTemp = bTemp && fsensor_enabled;
  8287. if (bTemp) {
  8288. nFSCheckCount++;
  8289. if (nFSCheckCount > FS_CHECK_COUNT) {
  8290. nFSCheckCount = 0; // not necessary
  8291. oFsensorPCB = switchTo;
  8292. eeprom_update_byte((uint8_t *)EEPROM_FSENSOR_PCB, (uint8_t)oFsensorPCB);
  8293. printf_IRSensorAnalogBoardChange();
  8294. lcd_setstatuspgm(statusLineTxt_P);
  8295. }
  8296. } else {
  8297. nFSCheckCount = 0;
  8298. }
  8299. }
  8300. #endif
  8301. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8302. {
  8303. #ifdef FILAMENT_SENSOR
  8304. bool bInhibitFlag;
  8305. #ifdef IR_SENSOR_ANALOG
  8306. static uint16_t nFSCheckCount=0;
  8307. #endif // IR_SENSOR_ANALOG
  8308. if (mmu_enabled == false)
  8309. {
  8310. //-// if (mcode_in_progress != 600) //M600 not in progress
  8311. #ifdef PAT9125
  8312. bInhibitFlag=(menu_menu==lcd_menu_extruder_info); // Support::ExtruderInfo menu active
  8313. #endif // PAT9125
  8314. #ifdef IR_SENSOR
  8315. bInhibitFlag=(menu_menu==lcd_menu_show_sensors_state); // Support::SensorInfo menu active
  8316. #ifdef IR_SENSOR_ANALOG
  8317. bInhibitFlag=bInhibitFlag||bMenuFSDetect; // Settings::HWsetup::FSdetect menu active
  8318. #endif // IR_SENSOR_ANALOG
  8319. #endif // IR_SENSOR
  8320. if ((mcode_in_progress != 600) && (eFilamentAction != FilamentAction::AutoLoad) && (!bInhibitFlag) && (menu_menu != lcd_move_e)) //M600 not in progress, preHeat @ autoLoad menu not active, Support::ExtruderInfo/SensorInfo menu not active
  8321. {
  8322. if (!moves_planned() && !IS_SD_PRINTING && !is_usb_printing && (lcd_commands_type != LcdCommands::Layer1Cal) && ! eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE))
  8323. {
  8324. #ifdef IR_SENSOR_ANALOG
  8325. static uint16_t minVolt = Voltage2Raw(6.F), maxVolt = 0;
  8326. // detect min-max, some long term sliding window for filtration may be added
  8327. // avoiding floating point operations, thus computing in raw
  8328. if( current_voltage_raw_IR > maxVolt )maxVolt = current_voltage_raw_IR;
  8329. if( current_voltage_raw_IR < minVolt )minVolt = current_voltage_raw_IR;
  8330. #if 0 // Start: IR Sensor debug info
  8331. { // debug print
  8332. static uint16_t lastVolt = ~0U;
  8333. if( current_voltage_raw_IR != lastVolt ){
  8334. printf_P(PSTR("fs volt=%4.2fV (min=%4.2f max=%4.2f)\n"), Raw2Voltage(current_voltage_raw_IR), Raw2Voltage(minVolt), Raw2Voltage(maxVolt) );
  8335. lastVolt = current_voltage_raw_IR;
  8336. }
  8337. }
  8338. #endif // End: IR Sensor debug info
  8339. //! The trouble is, I can hold the filament in the hole in such a way, that it creates the exact voltage
  8340. //! to be detected as the new fsensor
  8341. //! We can either fake it by extending the detection window to a looooong time
  8342. //! or do some other countermeasures
  8343. //! what we want to detect:
  8344. //! if minvolt gets below ~0.3V, it means there is an old fsensor
  8345. //! if maxvolt gets above 4.6V, it means we either have an old fsensor or broken cables/fsensor
  8346. //! So I'm waiting for a situation, when minVolt gets to range <0, 1.5> and maxVolt gets into range <3.0, 5>
  8347. //! If and only if minVolt is in range <0.3, 1.5> and maxVolt is in range <3.0, 4.6>, I'm considering a situation with the new fsensor
  8348. if( minVolt >= IRsensor_Ldiode_TRESHOLD && minVolt <= IRsensor_Lmax_TRESHOLD
  8349. && maxVolt >= IRsensor_Hmin_TRESHOLD && maxVolt <= IRsensor_Hopen_TRESHOLD
  8350. ){
  8351. manage_inactivity_IR_ANALOG_Check(nFSCheckCount, ClFsensorPCB::_Old, ClFsensorPCB::_Rev04, _i("FS v0.4 or newer") ); ////c=18
  8352. }
  8353. //! If and only if minVolt is in range <0.0, 0.3> and maxVolt is in range <4.6, 5.0V>, I'm considering a situation with the old fsensor
  8354. //! Note, we are not relying on one voltage here - getting just +5V can mean an old fsensor or a broken new sensor - that's why
  8355. //! we need to have both voltages detected correctly to allow switching back to the old fsensor.
  8356. else if( minVolt < IRsensor_Ldiode_TRESHOLD
  8357. && maxVolt > IRsensor_Hopen_TRESHOLD && maxVolt <= IRsensor_VMax_TRESHOLD
  8358. ){
  8359. manage_inactivity_IR_ANALOG_Check(nFSCheckCount, ClFsensorPCB::_Rev04, oFsensorPCB=ClFsensorPCB::_Old, _i("FS v0.3 or older")); ////c=18
  8360. }
  8361. #endif // IR_SENSOR_ANALOG
  8362. if (fsensor_check_autoload())
  8363. {
  8364. #ifdef PAT9125
  8365. fsensor_autoload_check_stop();
  8366. #endif //PAT9125
  8367. //-// if (degHotend0() > EXTRUDE_MINTEMP)
  8368. if(0)
  8369. {
  8370. Sound_MakeCustom(50,1000,false);
  8371. loading_flag = true;
  8372. enquecommand_front_P((PSTR("M701")));
  8373. }
  8374. else
  8375. {
  8376. /*
  8377. lcd_update_enable(false);
  8378. show_preheat_nozzle_warning();
  8379. lcd_update_enable(true);
  8380. */
  8381. eFilamentAction=FilamentAction::AutoLoad;
  8382. bFilamentFirstRun=false;
  8383. if(target_temperature[0]>=EXTRUDE_MINTEMP){
  8384. bFilamentPreheatState=true;
  8385. // mFilamentItem(target_temperature[0],target_temperature_bed);
  8386. menu_submenu(mFilamentItemForce);
  8387. } else {
  8388. menu_submenu(lcd_generic_preheat_menu);
  8389. lcd_timeoutToStatus.start();
  8390. }
  8391. }
  8392. }
  8393. }
  8394. else
  8395. {
  8396. #ifdef PAT9125
  8397. fsensor_autoload_check_stop();
  8398. #endif //PAT9125
  8399. if (fsensor_enabled && !saved_printing)
  8400. fsensor_update();
  8401. }
  8402. }
  8403. }
  8404. #endif //FILAMENT_SENSOR
  8405. #ifdef SAFETYTIMER
  8406. handleSafetyTimer();
  8407. #endif //SAFETYTIMER
  8408. #if defined(KILL_PIN) && KILL_PIN > -1
  8409. static int killCount = 0; // make the inactivity button a bit less responsive
  8410. const int KILL_DELAY = 10000;
  8411. #endif
  8412. if(buflen < (BUFSIZE-1)){
  8413. get_command();
  8414. }
  8415. if( (_millis() - previous_millis_cmd) > max_inactive_time )
  8416. if(max_inactive_time)
  8417. kill(_n("Inactivity Shutdown"), 4);
  8418. if(stepper_inactive_time) {
  8419. if( (_millis() - previous_millis_cmd) > stepper_inactive_time )
  8420. {
  8421. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8422. disable_x();
  8423. disable_y();
  8424. disable_z();
  8425. disable_e0();
  8426. disable_e1();
  8427. disable_e2();
  8428. }
  8429. }
  8430. }
  8431. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8432. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8433. {
  8434. chdkActive = false;
  8435. WRITE(CHDK, LOW);
  8436. }
  8437. #endif
  8438. #if defined(KILL_PIN) && KILL_PIN > -1
  8439. // Check if the kill button was pressed and wait just in case it was an accidental
  8440. // key kill key press
  8441. // -------------------------------------------------------------------------------
  8442. if( 0 == READ(KILL_PIN) )
  8443. {
  8444. killCount++;
  8445. }
  8446. else if (killCount > 0)
  8447. {
  8448. killCount--;
  8449. }
  8450. // Exceeded threshold and we can confirm that it was not accidental
  8451. // KILL the machine
  8452. // ----------------------------------------------------------------
  8453. if ( killCount >= KILL_DELAY)
  8454. {
  8455. kill(NULL, 5);
  8456. }
  8457. #endif
  8458. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8459. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8460. #endif
  8461. #ifdef EXTRUDER_RUNOUT_PREVENT
  8462. if( (_millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  8463. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8464. {
  8465. bool oldstatus=READ(E0_ENABLE_PIN);
  8466. enable_e0();
  8467. float oldepos=current_position[E_AXIS];
  8468. float oldedes=destination[E_AXIS];
  8469. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8470. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8471. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8472. current_position[E_AXIS]=oldepos;
  8473. destination[E_AXIS]=oldedes;
  8474. plan_set_e_position(oldepos);
  8475. previous_millis_cmd=_millis();
  8476. st_synchronize();
  8477. WRITE(E0_ENABLE_PIN,oldstatus);
  8478. }
  8479. #endif
  8480. #ifdef TEMP_STAT_LEDS
  8481. handle_status_leds();
  8482. #endif
  8483. check_axes_activity();
  8484. mmu_loop();
  8485. }
  8486. void kill(const char *full_screen_message, unsigned char id)
  8487. {
  8488. printf_P(_N("KILL: %d\n"), id);
  8489. //return;
  8490. cli(); // Stop interrupts
  8491. disable_heater();
  8492. disable_x();
  8493. // SERIAL_ECHOLNPGM("kill - disable Y");
  8494. disable_y();
  8495. poweroff_z();
  8496. disable_e0();
  8497. disable_e1();
  8498. disable_e2();
  8499. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8500. pinMode(PS_ON_PIN,INPUT);
  8501. #endif
  8502. SERIAL_ERROR_START;
  8503. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8504. if (full_screen_message != NULL) {
  8505. SERIAL_ERRORLNRPGM(full_screen_message);
  8506. lcd_display_message_fullscreen_P(full_screen_message);
  8507. } else {
  8508. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8509. }
  8510. // FMC small patch to update the LCD before ending
  8511. sei(); // enable interrupts
  8512. for ( int i=5; i--; lcd_update(0))
  8513. {
  8514. _delay(200);
  8515. }
  8516. cli(); // disable interrupts
  8517. suicide();
  8518. while(1)
  8519. {
  8520. #ifdef WATCHDOG
  8521. wdt_reset();
  8522. #endif //WATCHDOG
  8523. /* Intentionally left empty */
  8524. } // Wait for reset
  8525. }
  8526. // Stop: Emergency stop used by overtemp functions which allows recovery
  8527. //
  8528. // In addition to stopping the print, this prevents subsequent G[0-3] commands to be
  8529. // processed via USB (using "Stopped") until the print is resumed via M999 or
  8530. // manually started from scratch with the LCD.
  8531. //
  8532. // Note that the current instruction is completely discarded, so resuming from Stop()
  8533. // will introduce either over/under extrusion on the current segment, and will not
  8534. // survive a power panic. Switching Stop() to use the pause machinery instead (with
  8535. // the addition of disabling the headers) could allow true recovery in the future.
  8536. void Stop()
  8537. {
  8538. disable_heater();
  8539. if(Stopped == false) {
  8540. Stopped = true;
  8541. lcd_print_stop();
  8542. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  8543. SERIAL_ERROR_START;
  8544. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8545. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8546. }
  8547. }
  8548. bool IsStopped() { return Stopped; };
  8549. void finishAndDisableSteppers()
  8550. {
  8551. st_synchronize();
  8552. disable_x();
  8553. disable_y();
  8554. disable_z();
  8555. disable_e0();
  8556. disable_e1();
  8557. disable_e2();
  8558. #ifndef LA_NOCOMPAT
  8559. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8560. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8561. // state for the next print.
  8562. la10c_reset();
  8563. #endif
  8564. }
  8565. #ifdef FAST_PWM_FAN
  8566. void setPwmFrequency(uint8_t pin, int val)
  8567. {
  8568. val &= 0x07;
  8569. switch(digitalPinToTimer(pin))
  8570. {
  8571. #if defined(TCCR0A)
  8572. case TIMER0A:
  8573. case TIMER0B:
  8574. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8575. // TCCR0B |= val;
  8576. break;
  8577. #endif
  8578. #if defined(TCCR1A)
  8579. case TIMER1A:
  8580. case TIMER1B:
  8581. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8582. // TCCR1B |= val;
  8583. break;
  8584. #endif
  8585. #if defined(TCCR2)
  8586. case TIMER2:
  8587. case TIMER2:
  8588. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8589. TCCR2 |= val;
  8590. break;
  8591. #endif
  8592. #if defined(TCCR2A)
  8593. case TIMER2A:
  8594. case TIMER2B:
  8595. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8596. TCCR2B |= val;
  8597. break;
  8598. #endif
  8599. #if defined(TCCR3A)
  8600. case TIMER3A:
  8601. case TIMER3B:
  8602. case TIMER3C:
  8603. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8604. TCCR3B |= val;
  8605. break;
  8606. #endif
  8607. #if defined(TCCR4A)
  8608. case TIMER4A:
  8609. case TIMER4B:
  8610. case TIMER4C:
  8611. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8612. TCCR4B |= val;
  8613. break;
  8614. #endif
  8615. #if defined(TCCR5A)
  8616. case TIMER5A:
  8617. case TIMER5B:
  8618. case TIMER5C:
  8619. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8620. TCCR5B |= val;
  8621. break;
  8622. #endif
  8623. }
  8624. }
  8625. #endif //FAST_PWM_FAN
  8626. //! @brief Get and validate extruder number
  8627. //!
  8628. //! If it is not specified, active_extruder is returned in parameter extruder.
  8629. //! @param [in] code M code number
  8630. //! @param [out] extruder
  8631. //! @return error
  8632. //! @retval true Invalid extruder specified in T code
  8633. //! @retval false Valid extruder specified in T code, or not specifiead
  8634. bool setTargetedHotend(int code, uint8_t &extruder)
  8635. {
  8636. extruder = active_extruder;
  8637. if(code_seen('T')) {
  8638. extruder = code_value();
  8639. if(extruder >= EXTRUDERS) {
  8640. SERIAL_ECHO_START;
  8641. switch(code){
  8642. case 104:
  8643. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8644. break;
  8645. case 105:
  8646. SERIAL_ECHO(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8647. break;
  8648. case 109:
  8649. SERIAL_ECHO(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8650. break;
  8651. case 218:
  8652. SERIAL_ECHO(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8653. break;
  8654. case 221:
  8655. SERIAL_ECHO(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8656. break;
  8657. }
  8658. SERIAL_PROTOCOLLN((int)extruder);
  8659. return true;
  8660. }
  8661. }
  8662. return false;
  8663. }
  8664. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8665. {
  8666. 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)
  8667. {
  8668. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8669. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8670. }
  8671. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8672. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8673. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8674. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8675. total_filament_used = 0;
  8676. }
  8677. float calculate_extruder_multiplier(float diameter) {
  8678. float out = 1.f;
  8679. if (cs.volumetric_enabled && diameter > 0.f) {
  8680. float area = M_PI * diameter * diameter * 0.25;
  8681. out = 1.f / area;
  8682. }
  8683. if (extrudemultiply != 100)
  8684. out *= float(extrudemultiply) * 0.01f;
  8685. return out;
  8686. }
  8687. void calculate_extruder_multipliers() {
  8688. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8689. #if EXTRUDERS > 1
  8690. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8691. #if EXTRUDERS > 2
  8692. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8693. #endif
  8694. #endif
  8695. }
  8696. void delay_keep_alive(unsigned int ms)
  8697. {
  8698. for (;;) {
  8699. manage_heater();
  8700. // Manage inactivity, but don't disable steppers on timeout.
  8701. manage_inactivity(true);
  8702. lcd_update(0);
  8703. if (ms == 0)
  8704. break;
  8705. else if (ms >= 50) {
  8706. _delay(50);
  8707. ms -= 50;
  8708. } else {
  8709. _delay(ms);
  8710. ms = 0;
  8711. }
  8712. }
  8713. }
  8714. static void wait_for_heater(long codenum, uint8_t extruder) {
  8715. if (!degTargetHotend(extruder))
  8716. return;
  8717. #ifdef TEMP_RESIDENCY_TIME
  8718. long residencyStart;
  8719. residencyStart = -1;
  8720. /* continue to loop until we have reached the target temp
  8721. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8722. cancel_heatup = false;
  8723. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8724. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8725. #else
  8726. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8727. #endif //TEMP_RESIDENCY_TIME
  8728. if ((_millis() - codenum) > 1000UL)
  8729. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8730. if (!farm_mode) {
  8731. SERIAL_PROTOCOLPGM("T:");
  8732. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8733. SERIAL_PROTOCOLPGM(" E:");
  8734. SERIAL_PROTOCOL((int)extruder);
  8735. #ifdef TEMP_RESIDENCY_TIME
  8736. SERIAL_PROTOCOLPGM(" W:");
  8737. if (residencyStart > -1)
  8738. {
  8739. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8740. SERIAL_PROTOCOLLN(codenum);
  8741. }
  8742. else
  8743. {
  8744. SERIAL_PROTOCOLLN('?');
  8745. }
  8746. }
  8747. #else
  8748. SERIAL_PROTOCOLLN("");
  8749. #endif
  8750. codenum = _millis();
  8751. }
  8752. manage_heater();
  8753. manage_inactivity(true); //do not disable steppers
  8754. lcd_update(0);
  8755. #ifdef TEMP_RESIDENCY_TIME
  8756. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8757. or when current temp falls outside the hysteresis after target temp was reached */
  8758. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8759. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8760. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8761. {
  8762. residencyStart = _millis();
  8763. }
  8764. #endif //TEMP_RESIDENCY_TIME
  8765. }
  8766. }
  8767. void check_babystep()
  8768. {
  8769. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8770. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8771. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8772. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8773. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8774. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8775. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8776. babystep_z);
  8777. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8778. lcd_update_enable(true);
  8779. }
  8780. }
  8781. #ifdef HEATBED_ANALYSIS
  8782. void d_setup()
  8783. {
  8784. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8785. pinMode(D_DATA, INPUT_PULLUP);
  8786. pinMode(D_REQUIRE, OUTPUT);
  8787. digitalWrite(D_REQUIRE, HIGH);
  8788. }
  8789. float d_ReadData()
  8790. {
  8791. int digit[13];
  8792. String mergeOutput;
  8793. float output;
  8794. digitalWrite(D_REQUIRE, HIGH);
  8795. for (int i = 0; i<13; i++)
  8796. {
  8797. for (int j = 0; j < 4; j++)
  8798. {
  8799. while (digitalRead(D_DATACLOCK) == LOW) {}
  8800. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8801. bitWrite(digit[i], j, digitalRead(D_DATA));
  8802. }
  8803. }
  8804. digitalWrite(D_REQUIRE, LOW);
  8805. mergeOutput = "";
  8806. output = 0;
  8807. for (int r = 5; r <= 10; r++) //Merge digits
  8808. {
  8809. mergeOutput += digit[r];
  8810. }
  8811. output = mergeOutput.toFloat();
  8812. if (digit[4] == 8) //Handle sign
  8813. {
  8814. output *= -1;
  8815. }
  8816. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8817. {
  8818. output /= 10;
  8819. }
  8820. return output;
  8821. }
  8822. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8823. int t1 = 0;
  8824. int t_delay = 0;
  8825. int digit[13];
  8826. int m;
  8827. char str[3];
  8828. //String mergeOutput;
  8829. char mergeOutput[15];
  8830. float output;
  8831. int mesh_point = 0; //index number of calibration point
  8832. 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
  8833. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8834. float mesh_home_z_search = 4;
  8835. float measure_z_height = 0.2f;
  8836. float row[x_points_num];
  8837. int ix = 0;
  8838. int iy = 0;
  8839. const char* filename_wldsd = "mesh.txt";
  8840. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8841. char numb_wldsd[8]; // (" -A.BCD" + null)
  8842. #ifdef MICROMETER_LOGGING
  8843. d_setup();
  8844. #endif //MICROMETER_LOGGING
  8845. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8846. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8847. unsigned int custom_message_type_old = custom_message_type;
  8848. unsigned int custom_message_state_old = custom_message_state;
  8849. custom_message_type = CustomMsg::MeshBedLeveling;
  8850. custom_message_state = (x_points_num * y_points_num) + 10;
  8851. lcd_update(1);
  8852. //mbl.reset();
  8853. babystep_undo();
  8854. card.openFile(filename_wldsd, false);
  8855. /*destination[Z_AXIS] = mesh_home_z_search;
  8856. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8857. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8858. for(int8_t i=0; i < NUM_AXIS; i++) {
  8859. current_position[i] = destination[i];
  8860. }
  8861. st_synchronize();
  8862. */
  8863. destination[Z_AXIS] = measure_z_height;
  8864. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8865. for(int8_t i=0; i < NUM_AXIS; i++) {
  8866. current_position[i] = destination[i];
  8867. }
  8868. st_synchronize();
  8869. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8870. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8871. SERIAL_PROTOCOL(x_points_num);
  8872. SERIAL_PROTOCOLPGM(",");
  8873. SERIAL_PROTOCOL(y_points_num);
  8874. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8875. SERIAL_PROTOCOL(mesh_home_z_search);
  8876. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8877. SERIAL_PROTOCOL(x_dimension);
  8878. SERIAL_PROTOCOLPGM(",");
  8879. SERIAL_PROTOCOL(y_dimension);
  8880. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8881. while (mesh_point != x_points_num * y_points_num) {
  8882. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8883. iy = mesh_point / x_points_num;
  8884. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8885. float z0 = 0.f;
  8886. /*destination[Z_AXIS] = mesh_home_z_search;
  8887. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8888. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8889. for(int8_t i=0; i < NUM_AXIS; i++) {
  8890. current_position[i] = destination[i];
  8891. }
  8892. st_synchronize();*/
  8893. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8894. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8895. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8896. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8897. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8898. set_current_to_destination();
  8899. st_synchronize();
  8900. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8901. delay_keep_alive(1000);
  8902. #ifdef MICROMETER_LOGGING
  8903. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8904. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8905. //strcat(data_wldsd, numb_wldsd);
  8906. //MYSERIAL.println(data_wldsd);
  8907. //delay(1000);
  8908. //delay(3000);
  8909. //t1 = millis();
  8910. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8911. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8912. memset(digit, 0, sizeof(digit));
  8913. //cli();
  8914. digitalWrite(D_REQUIRE, LOW);
  8915. for (int i = 0; i<13; i++)
  8916. {
  8917. //t1 = millis();
  8918. for (int j = 0; j < 4; j++)
  8919. {
  8920. while (digitalRead(D_DATACLOCK) == LOW) {}
  8921. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8922. //printf_P(PSTR("Done %d\n"), j);
  8923. bitWrite(digit[i], j, digitalRead(D_DATA));
  8924. }
  8925. //t_delay = (millis() - t1);
  8926. //SERIAL_PROTOCOLPGM(" ");
  8927. //SERIAL_PROTOCOL_F(t_delay, 5);
  8928. //SERIAL_PROTOCOLPGM(" ");
  8929. }
  8930. //sei();
  8931. digitalWrite(D_REQUIRE, HIGH);
  8932. mergeOutput[0] = '\0';
  8933. output = 0;
  8934. for (int r = 5; r <= 10; r++) //Merge digits
  8935. {
  8936. sprintf(str, "%d", digit[r]);
  8937. strcat(mergeOutput, str);
  8938. }
  8939. output = atof(mergeOutput);
  8940. if (digit[4] == 8) //Handle sign
  8941. {
  8942. output *= -1;
  8943. }
  8944. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8945. {
  8946. output *= 0.1;
  8947. }
  8948. //output = d_ReadData();
  8949. //row[ix] = current_position[Z_AXIS];
  8950. //row[ix] = d_ReadData();
  8951. row[ix] = output;
  8952. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8953. memset(data_wldsd, 0, sizeof(data_wldsd));
  8954. for (int i = 0; i < x_points_num; i++) {
  8955. SERIAL_PROTOCOLPGM(" ");
  8956. SERIAL_PROTOCOL_F(row[i], 5);
  8957. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8958. dtostrf(row[i], 7, 3, numb_wldsd);
  8959. strcat(data_wldsd, numb_wldsd);
  8960. }
  8961. card.write_command(data_wldsd);
  8962. SERIAL_PROTOCOLPGM("\n");
  8963. }
  8964. custom_message_state--;
  8965. mesh_point++;
  8966. lcd_update(1);
  8967. }
  8968. #endif //MICROMETER_LOGGING
  8969. card.closefile();
  8970. //clean_up_after_endstop_move(l_feedmultiply);
  8971. }
  8972. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8973. int t1 = 0;
  8974. int t_delay = 0;
  8975. int digit[13];
  8976. int m;
  8977. char str[3];
  8978. //String mergeOutput;
  8979. char mergeOutput[15];
  8980. float output;
  8981. int mesh_point = 0; //index number of calibration point
  8982. 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
  8983. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8984. float mesh_home_z_search = 4;
  8985. float row[x_points_num];
  8986. int ix = 0;
  8987. int iy = 0;
  8988. const char* filename_wldsd = "wldsd.txt";
  8989. char data_wldsd[70];
  8990. char numb_wldsd[10];
  8991. d_setup();
  8992. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8993. // We don't know where we are! HOME!
  8994. // Push the commands to the front of the message queue in the reverse order!
  8995. // There shall be always enough space reserved for these commands.
  8996. repeatcommand_front(); // repeat G80 with all its parameters
  8997. enquecommand_front_P((PSTR("G28 W0")));
  8998. enquecommand_front_P((PSTR("G1 Z5")));
  8999. return;
  9000. }
  9001. unsigned int custom_message_type_old = custom_message_type;
  9002. unsigned int custom_message_state_old = custom_message_state;
  9003. custom_message_type = CustomMsg::MeshBedLeveling;
  9004. custom_message_state = (x_points_num * y_points_num) + 10;
  9005. lcd_update(1);
  9006. mbl.reset();
  9007. babystep_undo();
  9008. card.openFile(filename_wldsd, false);
  9009. current_position[Z_AXIS] = mesh_home_z_search;
  9010. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  9011. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  9012. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  9013. int l_feedmultiply = setup_for_endstop_move(false);
  9014. SERIAL_PROTOCOLPGM("Num X,Y: ");
  9015. SERIAL_PROTOCOL(x_points_num);
  9016. SERIAL_PROTOCOLPGM(",");
  9017. SERIAL_PROTOCOL(y_points_num);
  9018. SERIAL_PROTOCOLPGM("\nZ search height: ");
  9019. SERIAL_PROTOCOL(mesh_home_z_search);
  9020. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  9021. SERIAL_PROTOCOL(x_dimension);
  9022. SERIAL_PROTOCOLPGM(",");
  9023. SERIAL_PROTOCOL(y_dimension);
  9024. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  9025. while (mesh_point != x_points_num * y_points_num) {
  9026. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  9027. iy = mesh_point / x_points_num;
  9028. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  9029. float z0 = 0.f;
  9030. current_position[Z_AXIS] = mesh_home_z_search;
  9031. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  9032. st_synchronize();
  9033. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  9034. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  9035. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  9036. st_synchronize();
  9037. 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
  9038. break;
  9039. card.closefile();
  9040. }
  9041. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9042. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  9043. //strcat(data_wldsd, numb_wldsd);
  9044. //MYSERIAL.println(data_wldsd);
  9045. //_delay(1000);
  9046. //_delay(3000);
  9047. //t1 = _millis();
  9048. //while (digitalRead(D_DATACLOCK) == LOW) {}
  9049. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  9050. memset(digit, 0, sizeof(digit));
  9051. //cli();
  9052. digitalWrite(D_REQUIRE, LOW);
  9053. for (int i = 0; i<13; i++)
  9054. {
  9055. //t1 = _millis();
  9056. for (int j = 0; j < 4; j++)
  9057. {
  9058. while (digitalRead(D_DATACLOCK) == LOW) {}
  9059. while (digitalRead(D_DATACLOCK) == HIGH) {}
  9060. bitWrite(digit[i], j, digitalRead(D_DATA));
  9061. }
  9062. //t_delay = (_millis() - t1);
  9063. //SERIAL_PROTOCOLPGM(" ");
  9064. //SERIAL_PROTOCOL_F(t_delay, 5);
  9065. //SERIAL_PROTOCOLPGM(" ");
  9066. }
  9067. //sei();
  9068. digitalWrite(D_REQUIRE, HIGH);
  9069. mergeOutput[0] = '\0';
  9070. output = 0;
  9071. for (int r = 5; r <= 10; r++) //Merge digits
  9072. {
  9073. sprintf(str, "%d", digit[r]);
  9074. strcat(mergeOutput, str);
  9075. }
  9076. output = atof(mergeOutput);
  9077. if (digit[4] == 8) //Handle sign
  9078. {
  9079. output *= -1;
  9080. }
  9081. for (int i = digit[11]; i > 0; i--) //Handle floating point
  9082. {
  9083. output *= 0.1;
  9084. }
  9085. //output = d_ReadData();
  9086. //row[ix] = current_position[Z_AXIS];
  9087. memset(data_wldsd, 0, sizeof(data_wldsd));
  9088. for (int i = 0; i <3; i++) {
  9089. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9090. dtostrf(current_position[i], 8, 5, numb_wldsd);
  9091. strcat(data_wldsd, numb_wldsd);
  9092. strcat(data_wldsd, ";");
  9093. }
  9094. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9095. dtostrf(output, 8, 5, numb_wldsd);
  9096. strcat(data_wldsd, numb_wldsd);
  9097. //strcat(data_wldsd, ";");
  9098. card.write_command(data_wldsd);
  9099. //row[ix] = d_ReadData();
  9100. row[ix] = output; // current_position[Z_AXIS];
  9101. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  9102. for (int i = 0; i < x_points_num; i++) {
  9103. SERIAL_PROTOCOLPGM(" ");
  9104. SERIAL_PROTOCOL_F(row[i], 5);
  9105. }
  9106. SERIAL_PROTOCOLPGM("\n");
  9107. }
  9108. custom_message_state--;
  9109. mesh_point++;
  9110. lcd_update(1);
  9111. }
  9112. card.closefile();
  9113. clean_up_after_endstop_move(l_feedmultiply);
  9114. }
  9115. #endif //HEATBED_ANALYSIS
  9116. #ifndef PINDA_THERMISTOR
  9117. static void temp_compensation_start() {
  9118. custom_message_type = CustomMsg::TempCompPreheat;
  9119. custom_message_state = PINDA_HEAT_T + 1;
  9120. lcd_update(2);
  9121. if (degHotend(active_extruder) > EXTRUDE_MINTEMP) {
  9122. current_position[E_AXIS] -= default_retraction;
  9123. }
  9124. plan_buffer_line_curposXYZE(400, active_extruder);
  9125. current_position[X_AXIS] = PINDA_PREHEAT_X;
  9126. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  9127. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  9128. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  9129. st_synchronize();
  9130. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  9131. for (int i = 0; i < PINDA_HEAT_T; i++) {
  9132. delay_keep_alive(1000);
  9133. custom_message_state = PINDA_HEAT_T - i;
  9134. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  9135. else lcd_update(1);
  9136. }
  9137. custom_message_type = CustomMsg::Status;
  9138. custom_message_state = 0;
  9139. }
  9140. static void temp_compensation_apply() {
  9141. int i_add;
  9142. int z_shift = 0;
  9143. float z_shift_mm;
  9144. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  9145. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  9146. i_add = (target_temperature_bed - 60) / 10;
  9147. EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + i_add * 2, &z_shift);
  9148. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  9149. }else {
  9150. //interpolation
  9151. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  9152. }
  9153. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  9154. 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);
  9155. st_synchronize();
  9156. plan_set_z_position(current_position[Z_AXIS]);
  9157. }
  9158. else {
  9159. //we have no temp compensation data
  9160. }
  9161. }
  9162. #endif //ndef PINDA_THERMISTOR
  9163. float temp_comp_interpolation(float inp_temperature) {
  9164. //cubic spline interpolation
  9165. int n, i, j;
  9166. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  9167. int shift[10];
  9168. int temp_C[10];
  9169. n = 6; //number of measured points
  9170. shift[0] = 0;
  9171. for (i = 0; i < n; i++) {
  9172. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &shift[i]); //read shift in steps from EEPROM
  9173. temp_C[i] = 50 + i * 10; //temperature in C
  9174. #ifdef PINDA_THERMISTOR
  9175. constexpr int start_compensating_temp = 35;
  9176. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  9177. #ifdef SUPERPINDA_SUPPORT
  9178. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  9179. #endif //SUPERPINDA_SUPPORT
  9180. #else
  9181. temp_C[i] = 50 + i * 10; //temperature in C
  9182. #endif
  9183. x[i] = (float)temp_C[i];
  9184. f[i] = (float)shift[i];
  9185. }
  9186. if (inp_temperature < x[0]) return 0;
  9187. for (i = n - 1; i>0; i--) {
  9188. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9189. h[i - 1] = x[i] - x[i - 1];
  9190. }
  9191. //*********** formation of h, s , f matrix **************
  9192. for (i = 1; i<n - 1; i++) {
  9193. m[i][i] = 2 * (h[i - 1] + h[i]);
  9194. if (i != 1) {
  9195. m[i][i - 1] = h[i - 1];
  9196. m[i - 1][i] = h[i - 1];
  9197. }
  9198. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9199. }
  9200. //*********** forward elimination **************
  9201. for (i = 1; i<n - 2; i++) {
  9202. temp = (m[i + 1][i] / m[i][i]);
  9203. for (j = 1; j <= n - 1; j++)
  9204. m[i + 1][j] -= temp*m[i][j];
  9205. }
  9206. //*********** backward substitution *********
  9207. for (i = n - 2; i>0; i--) {
  9208. sum = 0;
  9209. for (j = i; j <= n - 2; j++)
  9210. sum += m[i][j] * s[j];
  9211. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9212. }
  9213. for (i = 0; i<n - 1; i++)
  9214. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9215. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9216. b = s[i] / 2;
  9217. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9218. d = f[i];
  9219. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9220. }
  9221. return sum;
  9222. }
  9223. #ifdef PINDA_THERMISTOR
  9224. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9225. {
  9226. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9227. if (!calibration_status_pinda()) return 0;
  9228. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9229. }
  9230. #endif //PINDA_THERMISTOR
  9231. void long_pause() //long pause print
  9232. {
  9233. st_synchronize();
  9234. start_pause_print = _millis();
  9235. // Stop heaters
  9236. setAllTargetHotends(0);
  9237. //lift z
  9238. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  9239. if (current_position[Z_AXIS] > Z_MAX_POS) current_position[Z_AXIS] = Z_MAX_POS;
  9240. plan_buffer_line_curposXYZE(15);
  9241. //Move XY to side
  9242. current_position[X_AXIS] = X_PAUSE_POS;
  9243. current_position[Y_AXIS] = Y_PAUSE_POS;
  9244. plan_buffer_line_curposXYZE(50);
  9245. // Turn off the print fan
  9246. fanSpeed = 0;
  9247. }
  9248. void serialecho_temperatures() {
  9249. float tt = degHotend(active_extruder);
  9250. SERIAL_PROTOCOLPGM("T:");
  9251. SERIAL_PROTOCOL(tt);
  9252. SERIAL_PROTOCOLPGM(" E:");
  9253. SERIAL_PROTOCOL((int)active_extruder);
  9254. SERIAL_PROTOCOLPGM(" B:");
  9255. SERIAL_PROTOCOL_F(degBed(), 1);
  9256. SERIAL_PROTOCOLLN("");
  9257. }
  9258. #ifdef UVLO_SUPPORT
  9259. void uvlo_drain_reset()
  9260. {
  9261. // burn all that residual power
  9262. wdt_enable(WDTO_1S);
  9263. WRITE(BEEPER,HIGH);
  9264. lcd_clear();
  9265. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9266. while(1);
  9267. }
  9268. void uvlo_()
  9269. {
  9270. unsigned long time_start = _millis();
  9271. bool sd_print = card.sdprinting;
  9272. // Conserve power as soon as possible.
  9273. #ifdef LCD_BL_PIN
  9274. backlightMode = BACKLIGHT_MODE_DIM;
  9275. backlightLevel_LOW = 0;
  9276. backlight_update();
  9277. #endif //LCD_BL_PIN
  9278. disable_x();
  9279. disable_y();
  9280. #ifdef TMC2130
  9281. tmc2130_set_current_h(Z_AXIS, 20);
  9282. tmc2130_set_current_r(Z_AXIS, 20);
  9283. tmc2130_set_current_h(E_AXIS, 20);
  9284. tmc2130_set_current_r(E_AXIS, 20);
  9285. #endif //TMC2130
  9286. // Stop all heaters
  9287. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9288. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9289. setAllTargetHotends(0);
  9290. setTargetBed(0);
  9291. // Calculate the file position, from which to resume this print.
  9292. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9293. {
  9294. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9295. sd_position -= sdlen_planner;
  9296. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9297. sd_position -= sdlen_cmdqueue;
  9298. if (sd_position < 0) sd_position = 0;
  9299. }
  9300. // save the global state at planning time
  9301. uint16_t feedrate_bckp;
  9302. if (current_block)
  9303. {
  9304. memcpy(saved_target, current_block->gcode_target, sizeof(saved_target));
  9305. feedrate_bckp = current_block->gcode_feedrate;
  9306. }
  9307. else
  9308. {
  9309. saved_target[0] = SAVED_TARGET_UNSET;
  9310. feedrate_bckp = feedrate;
  9311. }
  9312. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9313. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9314. // get the physical Z for further manipulation.
  9315. bool mbl_was_active = mbl.active;
  9316. mbl.active = false;
  9317. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9318. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9319. // are in action.
  9320. planner_abort_hard();
  9321. // Store the print logical Z position, which we need to recover (a slight error here would be
  9322. // recovered on the next Gcode instruction, while a physical location error would not)
  9323. float logical_z = current_position[Z_AXIS];
  9324. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9325. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9326. // Store the print E position before we lose track
  9327. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9328. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9329. // Clean the input command queue, inhibit serial processing using saved_printing
  9330. cmdqueue_reset();
  9331. card.sdprinting = false;
  9332. saved_printing = true;
  9333. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9334. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9335. sei();
  9336. // Retract
  9337. current_position[E_AXIS] -= default_retraction;
  9338. plan_buffer_line_curposXYZE(95);
  9339. st_synchronize();
  9340. disable_e0();
  9341. // Read out the current Z motor microstep counter to move the axis up towards
  9342. // a full step before powering off. NOTE: we need to ensure to schedule more
  9343. // than "dropsegments" steps in order to move (this is always the case here
  9344. // due to UVLO_Z_AXIS_SHIFT being used)
  9345. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9346. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9347. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9348. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9349. + UVLO_Z_AXIS_SHIFT;
  9350. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9351. st_synchronize();
  9352. poweroff_z();
  9353. // Write the file position.
  9354. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9355. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9356. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9357. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9358. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9359. // Scale the z value to 1u resolution.
  9360. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9361. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9362. }
  9363. // Write the _final_ Z position and motor microstep counter (unused).
  9364. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9365. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9366. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9367. // Store the current position.
  9368. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9369. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9370. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9371. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9372. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9373. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9374. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9375. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9376. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9377. #if EXTRUDERS > 1
  9378. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9379. #if EXTRUDERS > 2
  9380. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9381. #endif
  9382. #endif
  9383. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9384. // Store the saved target
  9385. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+0*4), saved_target[X_AXIS]);
  9386. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+1*4), saved_target[Y_AXIS]);
  9387. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+2*4), saved_target[Z_AXIS]);
  9388. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+3*4), saved_target[E_AXIS]);
  9389. #ifdef LIN_ADVANCE
  9390. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9391. #endif
  9392. // Finaly store the "power outage" flag.
  9393. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9394. // Increment power failure counter
  9395. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9396. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9397. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9398. WRITE(BEEPER,HIGH);
  9399. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9400. poweron_z();
  9401. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9402. plan_buffer_line_curposXYZE(500);
  9403. st_synchronize();
  9404. wdt_enable(WDTO_1S);
  9405. while(1);
  9406. }
  9407. void uvlo_tiny()
  9408. {
  9409. unsigned long time_start = _millis();
  9410. // Conserve power as soon as possible.
  9411. disable_x();
  9412. disable_y();
  9413. disable_e0();
  9414. #ifdef TMC2130
  9415. tmc2130_set_current_h(Z_AXIS, 20);
  9416. tmc2130_set_current_r(Z_AXIS, 20);
  9417. #endif //TMC2130
  9418. // Stop all heaters
  9419. setAllTargetHotends(0);
  9420. setTargetBed(0);
  9421. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9422. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9423. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9424. // Disable MBL (if not already) to work with physical coordinates.
  9425. mbl.active = false;
  9426. planner_abort_hard();
  9427. // Allow for small roundoffs to be ignored
  9428. if(abs(current_position[Z_AXIS] - eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))) >= 1.f/cs.axis_steps_per_unit[Z_AXIS])
  9429. {
  9430. // Clean the input command queue, inhibit serial processing using saved_printing
  9431. cmdqueue_reset();
  9432. card.sdprinting = false;
  9433. saved_printing = true;
  9434. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9435. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9436. sei();
  9437. // The axis was moved: adjust Z as done on a regular UVLO.
  9438. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9439. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9440. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9441. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9442. + UVLO_TINY_Z_AXIS_SHIFT;
  9443. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9444. st_synchronize();
  9445. poweroff_z();
  9446. // Update Z position
  9447. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9448. // Update the _final_ Z motor microstep counter (unused).
  9449. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9450. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9451. }
  9452. // Update the the "power outage" flag.
  9453. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9454. // Increment power failure counter
  9455. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9456. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9457. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9458. uvlo_drain_reset();
  9459. }
  9460. #endif //UVLO_SUPPORT
  9461. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9462. void setup_fan_interrupt() {
  9463. //INT7
  9464. DDRE &= ~(1 << 7); //input pin
  9465. PORTE &= ~(1 << 7); //no internal pull-up
  9466. //start with sensing rising edge
  9467. EICRB &= ~(1 << 6);
  9468. EICRB |= (1 << 7);
  9469. //enable INT7 interrupt
  9470. EIMSK |= (1 << 7);
  9471. }
  9472. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9473. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9474. ISR(INT7_vect) {
  9475. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9476. #ifdef FAN_SOFT_PWM
  9477. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9478. #else //FAN_SOFT_PWM
  9479. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9480. #endif //FAN_SOFT_PWM
  9481. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9482. t_fan_rising_edge = millis_nc();
  9483. }
  9484. else { //interrupt was triggered by falling edge
  9485. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9486. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9487. }
  9488. }
  9489. EICRB ^= (1 << 6); //change edge
  9490. }
  9491. #endif
  9492. #ifdef UVLO_SUPPORT
  9493. void setup_uvlo_interrupt() {
  9494. DDRE &= ~(1 << 4); //input pin
  9495. PORTE &= ~(1 << 4); //no internal pull-up
  9496. // sensing falling edge
  9497. EICRB |= (1 << 0);
  9498. EICRB &= ~(1 << 1);
  9499. // enable INT4 interrupt
  9500. EIMSK |= (1 << 4);
  9501. // check if power was lost before we armed the interrupt
  9502. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9503. {
  9504. SERIAL_ECHOLNPGM("INT4");
  9505. uvlo_drain_reset();
  9506. }
  9507. }
  9508. ISR(INT4_vect) {
  9509. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9510. SERIAL_ECHOLNPGM("INT4");
  9511. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9512. if(PRINTER_ACTIVE && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9513. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9514. }
  9515. void recover_print(uint8_t automatic) {
  9516. char cmd[30];
  9517. lcd_update_enable(true);
  9518. lcd_update(2);
  9519. lcd_setstatuspgm(_i("Recovering print "));////MSG_RECOVERING_PRINT c=20
  9520. // Recover position, temperatures and extrude_multipliers
  9521. bool mbl_was_active = recover_machine_state_after_power_panic();
  9522. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9523. // and second also so one may remove the excess priming material.
  9524. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9525. {
  9526. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9527. enquecommand(cmd);
  9528. }
  9529. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9530. // transformation status. G28 will not touch Z when MBL is off.
  9531. enquecommand_P(PSTR("G28 X Y"));
  9532. // Set the target bed and nozzle temperatures and wait.
  9533. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9534. enquecommand(cmd);
  9535. sprintf_P(cmd, PSTR("M190 S%d"), target_temperature_bed);
  9536. enquecommand(cmd);
  9537. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9538. enquecommand(cmd);
  9539. enquecommand_P(PSTR("M83")); //E axis relative mode
  9540. // If not automatically recoreverd (long power loss)
  9541. if(automatic == 0){
  9542. //Extrude some filament to stabilize the pressure
  9543. enquecommand_P(PSTR("G1 E5 F120"));
  9544. // Retract to be consistent with a short pause
  9545. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9546. enquecommand(cmd);
  9547. }
  9548. 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]);
  9549. // Restart the print.
  9550. restore_print_from_eeprom(mbl_was_active);
  9551. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9552. }
  9553. bool recover_machine_state_after_power_panic()
  9554. {
  9555. // 1) Preset some dummy values for the XY axes
  9556. current_position[X_AXIS] = 0;
  9557. current_position[Y_AXIS] = 0;
  9558. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9559. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9560. bool mbl_was_active = false;
  9561. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9562. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9563. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9564. // Scale the z value to 10u resolution.
  9565. int16_t v;
  9566. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9567. if (v != 0)
  9568. mbl_was_active = true;
  9569. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9570. }
  9571. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9572. // The current position after power panic is moved to the next closest 0th full step.
  9573. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9574. // Recover last E axis position
  9575. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9576. memcpy(destination, current_position, sizeof(destination));
  9577. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9578. print_world_coordinates();
  9579. // 3) Initialize the logical to physical coordinate system transformation.
  9580. world2machine_initialize();
  9581. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9582. // print_mesh_bed_leveling_table();
  9583. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9584. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9585. babystep_load();
  9586. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9587. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9588. plan_set_position_curposXYZE();
  9589. // 6) Power up the Z motors, mark their positions as known.
  9590. axis_known_position[Z_AXIS] = true;
  9591. enable_z();
  9592. // 7) Recover the target temperatures.
  9593. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9594. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9595. // 8) Recover extruder multipilers
  9596. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9597. #if EXTRUDERS > 1
  9598. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9599. #if EXTRUDERS > 2
  9600. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9601. #endif
  9602. #endif
  9603. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9604. // 9) Recover the saved target
  9605. saved_target[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+0*4));
  9606. saved_target[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+1*4));
  9607. saved_target[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+2*4));
  9608. saved_target[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+3*4));
  9609. #ifdef LIN_ADVANCE
  9610. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9611. #endif
  9612. return mbl_was_active;
  9613. }
  9614. void restore_print_from_eeprom(bool mbl_was_active) {
  9615. int feedrate_rec;
  9616. int feedmultiply_rec;
  9617. uint8_t fan_speed_rec;
  9618. char cmd[30];
  9619. char filename[13];
  9620. uint8_t depth = 0;
  9621. char dir_name[9];
  9622. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9623. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9624. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9625. SERIAL_ECHOPGM("Feedrate:");
  9626. MYSERIAL.print(feedrate_rec);
  9627. SERIAL_ECHOPGM(", feedmultiply:");
  9628. MYSERIAL.println(feedmultiply_rec);
  9629. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9630. MYSERIAL.println(int(depth));
  9631. for (int i = 0; i < depth; i++) {
  9632. for (int j = 0; j < 8; j++) {
  9633. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9634. }
  9635. dir_name[8] = '\0';
  9636. MYSERIAL.println(dir_name);
  9637. strcpy(dir_names[i], dir_name);
  9638. card.chdir(dir_name);
  9639. }
  9640. for (int i = 0; i < 8; i++) {
  9641. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9642. }
  9643. filename[8] = '\0';
  9644. MYSERIAL.print(filename);
  9645. strcat_P(filename, PSTR(".gco"));
  9646. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9647. enquecommand(cmd);
  9648. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9649. SERIAL_ECHOPGM("Position read from eeprom:");
  9650. MYSERIAL.println(position);
  9651. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9652. // without shifting Z along the way. This requires performing the move without mbl.
  9653. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"),
  9654. eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0)),
  9655. eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4)));
  9656. enquecommand(cmd);
  9657. // Enable MBL and switch to logical positioning
  9658. if (mbl_was_active)
  9659. enquecommand_P(PSTR("PRUSA MBL V1"));
  9660. // Move the Z axis down to the print, in logical coordinates.
  9661. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9662. enquecommand(cmd);
  9663. // Unretract.
  9664. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9665. enquecommand(cmd);
  9666. // Recover final E axis position and mode
  9667. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9668. sprintf_P(cmd, PSTR("G92 E"));
  9669. dtostrf(pos_e, 6, 3, cmd + strlen(cmd));
  9670. enquecommand(cmd);
  9671. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9672. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9673. // Set the feedrates saved at the power panic.
  9674. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9675. enquecommand(cmd);
  9676. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9677. enquecommand(cmd);
  9678. // Set the fan speed saved at the power panic.
  9679. strcpy_P(cmd, PSTR("M106 S"));
  9680. strcat(cmd, itostr3(int(fan_speed_rec)));
  9681. enquecommand(cmd);
  9682. // Set a position in the file.
  9683. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9684. enquecommand(cmd);
  9685. enquecommand_P(PSTR("G4 S0"));
  9686. enquecommand_P(PSTR("PRUSA uvlo"));
  9687. }
  9688. #endif //UVLO_SUPPORT
  9689. //! @brief Immediately stop print moves
  9690. //!
  9691. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9692. //! If printing from sd card, position in file is saved.
  9693. //! If printing from USB, line number is saved.
  9694. //!
  9695. //! @param z_move
  9696. //! @param e_move
  9697. void stop_and_save_print_to_ram(float z_move, float e_move)
  9698. {
  9699. if (saved_printing) return;
  9700. #if 0
  9701. unsigned char nplanner_blocks;
  9702. #endif
  9703. unsigned char nlines;
  9704. uint16_t sdlen_planner;
  9705. uint16_t sdlen_cmdqueue;
  9706. cli();
  9707. if (card.sdprinting) {
  9708. #if 0
  9709. nplanner_blocks = number_of_blocks();
  9710. #endif
  9711. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9712. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9713. saved_sdpos -= sdlen_planner;
  9714. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9715. saved_sdpos -= sdlen_cmdqueue;
  9716. saved_printing_type = PRINTING_TYPE_SD;
  9717. }
  9718. else if (is_usb_printing) { //reuse saved_sdpos for storing line number
  9719. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9720. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9721. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9722. saved_sdpos -= nlines;
  9723. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9724. saved_printing_type = PRINTING_TYPE_USB;
  9725. }
  9726. else {
  9727. saved_printing_type = PRINTING_TYPE_NONE;
  9728. //not sd printing nor usb printing
  9729. }
  9730. #if 0
  9731. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9732. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9733. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9734. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9735. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9736. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9737. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9738. {
  9739. card.setIndex(saved_sdpos);
  9740. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9741. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9742. MYSERIAL.print(char(card.get()));
  9743. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9744. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9745. MYSERIAL.print(char(card.get()));
  9746. SERIAL_ECHOLNPGM("End of command buffer");
  9747. }
  9748. {
  9749. // Print the content of the planner buffer, line by line:
  9750. card.setIndex(saved_sdpos);
  9751. int8_t iline = 0;
  9752. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9753. SERIAL_ECHOPGM("Planner line (from file): ");
  9754. MYSERIAL.print(int(iline), DEC);
  9755. SERIAL_ECHOPGM(", length: ");
  9756. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9757. SERIAL_ECHOPGM(", steps: (");
  9758. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9759. SERIAL_ECHOPGM(",");
  9760. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9761. SERIAL_ECHOPGM(",");
  9762. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9763. SERIAL_ECHOPGM(",");
  9764. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9765. SERIAL_ECHOPGM("), events: ");
  9766. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9767. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9768. MYSERIAL.print(char(card.get()));
  9769. }
  9770. }
  9771. {
  9772. // Print the content of the command buffer, line by line:
  9773. int8_t iline = 0;
  9774. union {
  9775. struct {
  9776. char lo;
  9777. char hi;
  9778. } lohi;
  9779. uint16_t value;
  9780. } sdlen_single;
  9781. int _bufindr = bufindr;
  9782. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9783. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9784. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9785. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9786. }
  9787. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9788. MYSERIAL.print(int(iline), DEC);
  9789. SERIAL_ECHOPGM(", type: ");
  9790. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9791. SERIAL_ECHOPGM(", len: ");
  9792. MYSERIAL.println(sdlen_single.value, DEC);
  9793. // Print the content of the buffer line.
  9794. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9795. SERIAL_ECHOPGM("Buffer line (from file): ");
  9796. MYSERIAL.println(int(iline), DEC);
  9797. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9798. MYSERIAL.print(char(card.get()));
  9799. if (-- _buflen == 0)
  9800. break;
  9801. // First skip the current command ID and iterate up to the end of the string.
  9802. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9803. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9804. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9805. // If the end of the buffer was empty,
  9806. if (_bufindr == sizeof(cmdbuffer)) {
  9807. // skip to the start and find the nonzero command.
  9808. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9809. }
  9810. }
  9811. }
  9812. #endif
  9813. // save the global state at planning time
  9814. if (current_block)
  9815. {
  9816. memcpy(saved_target, current_block->gcode_target, sizeof(saved_target));
  9817. saved_feedrate2 = current_block->gcode_feedrate;
  9818. }
  9819. else
  9820. {
  9821. saved_target[0] = SAVED_TARGET_UNSET;
  9822. saved_feedrate2 = feedrate;
  9823. }
  9824. planner_abort_hard(); //abort printing
  9825. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9826. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9827. saved_active_extruder = active_extruder; //save active_extruder
  9828. saved_extruder_temperature = degTargetHotend(active_extruder);
  9829. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9830. saved_fanSpeed = fanSpeed;
  9831. cmdqueue_reset(); //empty cmdqueue
  9832. card.sdprinting = false;
  9833. // card.closefile();
  9834. saved_printing = true;
  9835. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9836. st_reset_timer();
  9837. sei();
  9838. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9839. #if 1
  9840. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9841. // the caller can continue processing. This is used during powerpanic to save the state as we
  9842. // move away from the print.
  9843. char buf[48];
  9844. if(e_move)
  9845. {
  9846. // First unretract (relative extrusion)
  9847. if(!saved_extruder_relative_mode){
  9848. enquecommand(PSTR("M83"), true);
  9849. }
  9850. //retract 45mm/s
  9851. // A single sprintf may not be faster, but is definitely 20B shorter
  9852. // than a sequence of commands building the string piece by piece
  9853. // A snprintf would have been a safer call, but since it is not used
  9854. // in the whole program, its implementation would bring more bytes to the total size
  9855. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9856. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9857. enquecommand(buf, false);
  9858. }
  9859. if(z_move)
  9860. {
  9861. // Then lift Z axis
  9862. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9863. enquecommand(buf, false);
  9864. }
  9865. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9866. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9867. repeatcommand_front();
  9868. #else
  9869. 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);
  9870. st_synchronize(); //wait moving
  9871. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9872. memcpy(destination, current_position, sizeof(destination));
  9873. #endif
  9874. waiting_inside_plan_buffer_line_print_aborted = true; //unroll the stack
  9875. }
  9876. }
  9877. //! @brief Restore print from ram
  9878. //!
  9879. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9880. //! print fan speed, waits for extruder temperature restore, then restores
  9881. //! position and continues print moves.
  9882. //!
  9883. //! Internally lcd_update() is called by wait_for_heater().
  9884. //!
  9885. //! @param e_move
  9886. void restore_print_from_ram_and_continue(float e_move)
  9887. {
  9888. if (!saved_printing) return;
  9889. #ifdef FANCHECK
  9890. // Do not allow resume printing if fans are still not ok
  9891. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9892. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9893. #endif
  9894. // for (int axis = X_AXIS; axis <= E_AXIS; axis++)
  9895. // current_position[axis] = st_get_position_mm(axis);
  9896. active_extruder = saved_active_extruder; //restore active_extruder
  9897. fanSpeed = saved_fanSpeed;
  9898. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  9899. {
  9900. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  9901. heating_status = 1;
  9902. wait_for_heater(_millis(), saved_active_extruder);
  9903. heating_status = 2;
  9904. }
  9905. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9906. float e = saved_pos[E_AXIS] - e_move;
  9907. plan_set_e_position(e);
  9908. #ifdef FANCHECK
  9909. fans_check_enabled = false;
  9910. #endif
  9911. //first move print head in XY to the saved position:
  9912. 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);
  9913. //then move Z
  9914. 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);
  9915. //and finaly unretract (35mm/s)
  9916. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9917. st_synchronize();
  9918. #ifdef FANCHECK
  9919. fans_check_enabled = true;
  9920. #endif
  9921. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9922. feedrate = saved_feedrate2;
  9923. feedmultiply = saved_feedmultiply2;
  9924. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9925. memcpy(destination, current_position, sizeof(destination));
  9926. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9927. card.setIndex(saved_sdpos);
  9928. sdpos_atomic = saved_sdpos;
  9929. card.sdprinting = true;
  9930. }
  9931. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9932. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9933. serial_count = 0;
  9934. FlushSerialRequestResend();
  9935. }
  9936. else {
  9937. //not sd printing nor usb printing
  9938. }
  9939. lcd_setstatuspgm(_T(WELCOME_MSG));
  9940. saved_printing_type = PRINTING_TYPE_NONE;
  9941. saved_printing = false;
  9942. waiting_inside_plan_buffer_line_print_aborted = true; //unroll the stack
  9943. }
  9944. // Cancel the state related to a currently saved print
  9945. void cancel_saved_printing()
  9946. {
  9947. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9948. saved_target[0] = SAVED_TARGET_UNSET;
  9949. saved_printing_type = PRINTING_TYPE_NONE;
  9950. saved_printing = false;
  9951. }
  9952. void print_world_coordinates()
  9953. {
  9954. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9955. }
  9956. void print_physical_coordinates()
  9957. {
  9958. 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));
  9959. }
  9960. void print_mesh_bed_leveling_table()
  9961. {
  9962. SERIAL_ECHOPGM("mesh bed leveling: ");
  9963. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9964. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9965. MYSERIAL.print(mbl.z_values[y][x], 3);
  9966. SERIAL_ECHO(' ');
  9967. }
  9968. SERIAL_ECHOLN();
  9969. }
  9970. uint16_t print_time_remaining() {
  9971. uint16_t print_t = PRINT_TIME_REMAINING_INIT;
  9972. #ifdef TMC2130
  9973. if (SilentModeMenu == SILENT_MODE_OFF) print_t = print_time_remaining_normal;
  9974. else print_t = print_time_remaining_silent;
  9975. #else
  9976. print_t = print_time_remaining_normal;
  9977. #endif //TMC2130
  9978. if ((print_t != PRINT_TIME_REMAINING_INIT) && (feedmultiply != 0)) print_t = 100ul * print_t / feedmultiply;
  9979. return print_t;
  9980. }
  9981. uint8_t calc_percent_done()
  9982. {
  9983. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9984. uint8_t percent_done = 0;
  9985. #ifdef TMC2130
  9986. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100) {
  9987. percent_done = print_percent_done_normal;
  9988. }
  9989. else if (print_percent_done_silent <= 100) {
  9990. percent_done = print_percent_done_silent;
  9991. }
  9992. #else
  9993. if (print_percent_done_normal <= 100) {
  9994. percent_done = print_percent_done_normal;
  9995. }
  9996. #endif //TMC2130
  9997. else {
  9998. percent_done = card.percentDone();
  9999. }
  10000. return percent_done;
  10001. }
  10002. static void print_time_remaining_init()
  10003. {
  10004. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  10005. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  10006. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  10007. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  10008. }
  10009. void load_filament_final_feed()
  10010. {
  10011. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  10012. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  10013. }
  10014. //! @brief Wait for user to check the state
  10015. //! @par nozzle_temp nozzle temperature to load filament
  10016. void M600_check_state(float nozzle_temp)
  10017. {
  10018. lcd_change_fil_state = 0;
  10019. while (lcd_change_fil_state != 1)
  10020. {
  10021. lcd_change_fil_state = 0;
  10022. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10023. lcd_alright();
  10024. KEEPALIVE_STATE(IN_HANDLER);
  10025. switch(lcd_change_fil_state)
  10026. {
  10027. // Filament failed to load so load it again
  10028. case 2:
  10029. if (mmu_enabled)
  10030. mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  10031. else
  10032. M600_load_filament_movements();
  10033. break;
  10034. // Filament loaded properly but color is not clear
  10035. case 3:
  10036. st_synchronize();
  10037. load_filament_final_feed();
  10038. lcd_loading_color();
  10039. st_synchronize();
  10040. break;
  10041. // Everything good
  10042. default:
  10043. lcd_change_success();
  10044. break;
  10045. }
  10046. }
  10047. }
  10048. //! @brief Wait for user action
  10049. //!
  10050. //! Beep, manage nozzle heater and wait for user to start unload filament
  10051. //! If times out, active extruder temperature is set to 0.
  10052. //!
  10053. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  10054. void M600_wait_for_user(float HotendTempBckp) {
  10055. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10056. int counterBeep = 0;
  10057. unsigned long waiting_start_time = _millis();
  10058. uint8_t wait_for_user_state = 0;
  10059. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10060. bool bFirst=true;
  10061. while (!(wait_for_user_state == 0 && lcd_clicked())){
  10062. manage_heater();
  10063. manage_inactivity(true);
  10064. #if BEEPER > 0
  10065. if (counterBeep == 500) {
  10066. counterBeep = 0;
  10067. }
  10068. SET_OUTPUT(BEEPER);
  10069. if (counterBeep == 0) {
  10070. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  10071. {
  10072. bFirst=false;
  10073. WRITE(BEEPER, HIGH);
  10074. }
  10075. }
  10076. if (counterBeep == 20) {
  10077. WRITE(BEEPER, LOW);
  10078. }
  10079. counterBeep++;
  10080. #endif //BEEPER > 0
  10081. switch (wait_for_user_state) {
  10082. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  10083. delay_keep_alive(4);
  10084. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  10085. lcd_display_message_fullscreen_P(_i("Press knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  10086. wait_for_user_state = 1;
  10087. setAllTargetHotends(0);
  10088. st_synchronize();
  10089. disable_e0();
  10090. disable_e1();
  10091. disable_e2();
  10092. }
  10093. break;
  10094. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  10095. delay_keep_alive(4);
  10096. if (lcd_clicked()) {
  10097. setTargetHotend(HotendTempBckp, active_extruder);
  10098. lcd_wait_for_heater();
  10099. wait_for_user_state = 2;
  10100. }
  10101. break;
  10102. case 2: //waiting for nozzle to reach target temperature
  10103. if (abs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  10104. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10105. waiting_start_time = _millis();
  10106. wait_for_user_state = 0;
  10107. }
  10108. else {
  10109. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  10110. lcd_set_cursor(1, 4);
  10111. lcd_print(ftostr3(degHotend(active_extruder)));
  10112. }
  10113. break;
  10114. }
  10115. }
  10116. WRITE(BEEPER, LOW);
  10117. }
  10118. void M600_load_filament_movements()
  10119. {
  10120. #ifdef SNMM
  10121. display_loading();
  10122. do
  10123. {
  10124. current_position[E_AXIS] += 0.002;
  10125. plan_buffer_line_curposXYZE(500, active_extruder);
  10126. delay_keep_alive(2);
  10127. }
  10128. while (!lcd_clicked());
  10129. st_synchronize();
  10130. current_position[E_AXIS] += bowden_length[mmu_extruder];
  10131. plan_buffer_line_curposXYZE(3000, active_extruder);
  10132. current_position[E_AXIS] += FIL_LOAD_LENGTH - 60;
  10133. plan_buffer_line_curposXYZE(1400, active_extruder);
  10134. current_position[E_AXIS] += 40;
  10135. plan_buffer_line_curposXYZE(400, active_extruder);
  10136. current_position[E_AXIS] += 10;
  10137. plan_buffer_line_curposXYZE(50, active_extruder);
  10138. #else
  10139. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  10140. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  10141. #endif
  10142. load_filament_final_feed();
  10143. lcd_loading_filament();
  10144. st_synchronize();
  10145. }
  10146. void M600_load_filament() {
  10147. //load filament for single material and SNMM
  10148. lcd_wait_interact();
  10149. //load_filament_time = _millis();
  10150. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10151. #ifdef PAT9125
  10152. fsensor_autoload_check_start();
  10153. #endif //PAT9125
  10154. while(!lcd_clicked())
  10155. {
  10156. manage_heater();
  10157. manage_inactivity(true);
  10158. #ifdef FILAMENT_SENSOR
  10159. if (fsensor_check_autoload())
  10160. {
  10161. Sound_MakeCustom(50,1000,false);
  10162. break;
  10163. }
  10164. #endif //FILAMENT_SENSOR
  10165. }
  10166. #ifdef PAT9125
  10167. fsensor_autoload_check_stop();
  10168. #endif //PAT9125
  10169. KEEPALIVE_STATE(IN_HANDLER);
  10170. #ifdef FSENSOR_QUALITY
  10171. fsensor_oq_meassure_start(70);
  10172. #endif //FSENSOR_QUALITY
  10173. M600_load_filament_movements();
  10174. Sound_MakeCustom(50,1000,false);
  10175. #ifdef FSENSOR_QUALITY
  10176. fsensor_oq_meassure_stop();
  10177. if (!fsensor_oq_result())
  10178. {
  10179. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  10180. lcd_update_enable(true);
  10181. lcd_update(2);
  10182. if (disable)
  10183. fsensor_disable();
  10184. }
  10185. #endif //FSENSOR_QUALITY
  10186. lcd_update_enable(false);
  10187. }
  10188. //! @brief Wait for click
  10189. //!
  10190. //! Set
  10191. void marlin_wait_for_click()
  10192. {
  10193. int8_t busy_state_backup = busy_state;
  10194. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10195. lcd_consume_click();
  10196. while(!lcd_clicked())
  10197. {
  10198. manage_heater();
  10199. manage_inactivity(true);
  10200. lcd_update(0);
  10201. }
  10202. KEEPALIVE_STATE(busy_state_backup);
  10203. }
  10204. #define FIL_LOAD_LENGTH 60
  10205. #ifdef PSU_Delta
  10206. bool bEnableForce_z;
  10207. void init_force_z()
  10208. {
  10209. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10210. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10211. disable_force_z();
  10212. }
  10213. void check_force_z()
  10214. {
  10215. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10216. init_force_z(); // causes enforced switching into disable-state
  10217. }
  10218. void disable_force_z()
  10219. {
  10220. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10221. bEnableForce_z=false;
  10222. // switching to silent mode
  10223. #ifdef TMC2130
  10224. tmc2130_mode=TMC2130_MODE_SILENT;
  10225. update_mode_profile();
  10226. tmc2130_init(true);
  10227. #endif // TMC2130
  10228. }
  10229. void enable_force_z()
  10230. {
  10231. if(bEnableForce_z)
  10232. return; // motor already enabled (may be ;-p )
  10233. bEnableForce_z=true;
  10234. // mode recovering
  10235. #ifdef TMC2130
  10236. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10237. update_mode_profile();
  10238. tmc2130_init(true);
  10239. #endif // TMC2130
  10240. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10241. }
  10242. #endif // PSU_Delta