Marlin_main.cpp 206 KB

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