Marlin_main.cpp 249 KB

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