Marlin_main.cpp 218 KB

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