Marlin_main.cpp 298 KB

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