Marlin_main.cpp 207 KB

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