Marlin_main.cpp 219 KB

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