Marlin_main.cpp 246 KB

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