Marlin_main.cpp 286 KB

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