Marlin_main.cpp 276 KB

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