Marlin_main.cpp 287 KB

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