Marlin_main.cpp 240 KB

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