Marlin_main.cpp 183 KB

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