Marlin_main.cpp 219 KB

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