Marlin_main.cpp 227 KB

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