Marlin_main.cpp 298 KB

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