Marlin_main.cpp 286 KB

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