Marlin_main.cpp 248 KB

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