Marlin_main.cpp 286 KB

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