Marlin_main.cpp 219 KB

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