Marlin_main.cpp 231 KB

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