Anda di halaman 1dari 10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

SparkFunEthernetShieldQuickstartGuide
byJimb0|November27,2012|2comments

SkillLevel:Beginner

EquipyourArduinowithnetwork/internetconnectivityusingtheSparkFunEthernetShieldandthepowerful
Ethernetlibrary!

Inthistutorial,wellcoverhowtogetupandrunningwiththeSparkFunEthernetShield.Requirements,
hardware,assembly,andprogrammingwillallbecovered.Followalong,andyourArduinoshouldbeskimming
Twitterandhostingwebpagesinnotime!

Requirements
Inadditiontotheshield,youllneedafewmorebitsandpiecestogetthemostoutoftheSparkFunEthernet
Shield:

Headers(andsolderingtools)
Headersprovidetheshieldwithasolid,electricalconnectiontoyourArduino.You'vegotafewoptionswhenit
comestoheaders,butformostshieldsIrecommendthestackingheaders.Theseallowyoutoplugwires,or
evenothershields,intotheunusedArduinopins.

Youwillneedtosolderthoseheadersintoyourshield.So,ifyoudontalreadyhaveone,Idrecommendgetting
agood,cheapsolderingiron,andsomesolder.Astandwouldnthurteither,anditmightsaveyourcarpet.
(Moreonthisintheassemblysectionbelow).
https://www.sparkfun.com/tutorials/409

1/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

AnEthernetcable
ThiswillinterfacebetweenyourEthernetShieldsRJ45jackandarouterorswitch.CAT5,CAT6,reallyanything
withapairofRJ45terminationsshouldwork.Findalengththatworksbestforyou1,3,5,or10feet.Ormake
yourowncabletofindyourbestfit!

SDCard(optional)
YoullquicklyfindthattheEthernetequippedArduinosketchesuseabigchunkoftheArduinosSRAMand
flash.Ifyouwanttohostwebpages,orreadandstoreinformation,aSDcardisagreatwaytoexpandupon
theArduinosratherlimitedmemory.Youwontneedahighcapacitycard1GBorsowillcertainlydothough
reallyanySDcardyouvegotlyingaroundshouldwork.

ArduinoDevelopmentBoard
WhiletheEthernetShieldcouldworkwithjustaboutanydevelopmentplatform,itscertainlybestsuitedfor
Arduinos.IfyourelookingforanArduinotopairwiththisshield,IdrecommendtherocksolidArduinoUno.
OtherArduinos(Mega,Leonardo,Due)shouldworkwiththeShield,butyoumayneedaTransmogriShieldto
movepinsaround.

ArduinoSoftware
https://www.sparkfun.com/tutorials/409

2/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

Norevelationshere,youllneedtheArduinoIDEtoprogramtheArduino.Fortunatelyforus,theIDEcomeswith
afantasticEthernetlibraryaswellasanSDlibrary.Ifyoudonthavethemostrecentversion,youcandownload
itfromArduinosdownloadspage.

Hardware
TheSparkFunEthernetShieldiscomprisedoftwostandoutcomponentsaWiznetW5100TCP/IPembedded
EthernetcontrollerandaSDsocket.
TheW5100isapowerfullittlechip,whichimplementsallsortsofcomplexnetworkprotocols
TCP,UDP,ICMP,IPv4,ARP,IGMP,PPPoE,andthephyscialEthernetlayer.Thisalleviatesalot
ofprogrammingstressonusandmemorystressontheArduino.Allofthecommunication
betweentheW5100andtheArduinoisSPIbasedandhandledusingtheEthernetlibrary,which
welldiscussinthefirmwaresectionbelow.
TheW5100issupportedbyanumberofcomponentscapacitors,acrystal,resetmonitors
butmostespeciallyanEthernetjack,actuallyaMagJack.InsidethatlittleRJ45jackarea
numberoftransformersandmagneticsrequiredforisolatingEthernetsignals(youcouldsay
thisjackismorethanmeetstheeye).ThereareevensomeLEDspokingouttheend.
TheSDsocketextendsneartheedgeoftheshield,wherethecardshouldbe
inserted.Thesocketsitsnexttoa74HC4050(hightolowlevelshifter),which
handlesallofthe5Vto3.3Vvoltageshifting(thosedelicateSDcards
shouldn'tbesubjectedto5Vsignals).
Someofthelessspectacularcomponents(donttellthemIsaidthat)onthe
EthernetShieldincludearesetbutton,3.3Vregulator,andanumberofblinkyLEDs.Theresetbuttonworks
justliketheonetheArduinoitself,thoughitllalsoresettheW5100.TheLEDsincludeapowerindicatorLED,as
wellasanumberofstatusLEDs(Ethernetreceive/transmit,collision,andspeed)tiedtotheW5100,whichwill
appeartohaveamindoftheirown.

WhatIdreallyliketostressinthissectioniswhichpinstheshieldrequiresoftheArduino.Heresatableofthe
sixpinsusedbytheshield:
Arduino
Pin

4
10

W5100Interruptoutput(optional,setwith
jumper)
SDCardChipselect
W5100Chipselect

11
12

SDCardandW5100MOSI
SDCardandW5100MISO

13

SDCardandW5100SPIClock

https://www.sparkfun.com/tutorials/409

SparkFunEthernetShieldPinFunction

3/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

Ingeneralyoullwanttoavoidusingthechipselectpins(4and10)foranythingelse.IfyouhaveotherSPI
devices,youshouldbeabletolinkthemuponthesameSPIbus(pins11,12,and13).
Pin2isactuallynotusedbydefaultontheshield.Theresajumperonthetopsideoftheboardifyouwantto
enabletheW5100sinterruptoutput(IdontthinktheEthernetshieldmakesuseofthispinregardless,though).

TheSparkFunEthernetShield,particularlytheWiznetW5100,canbeapowerhungrylittlebeast.Its
recommendedthatyouuseapowersupplythatcansourceatleast400mA.PoweringtheshieldoverUSBwill
workinmostcases,thoughitwouldnthurttopoweryourArduinoviaa9Vwallwart.
TheW5100shungerforpowerwillcauseitandthe3.3Vregulatortoheatup.Thisisnormal,especiallywhen
thechipisdoingalotofwork.Theyshouldnevergetuntouchablehot,buttheymightgettoohotto
comfortablyleaveyourfingeronforextendedperiodshot.

Assembly
Theresreallyjustonestepinthissection:soldering!
Ifyouveneversolderedbefore,thatsOK!Thisisactuallyaperfectplacetostartallofthesolderpointsare
throughholeandwellspaced.However,Idreallyrecommendcheckingoutoursolderingcrashcoursefirst.
Readtheguide,watchthevideo,andyoullpickupsomegoodtipsthatwillhelpyourfirstsolderingexperience
gomoresmoothly.
Therearefourheaderstosolder.Therealchallengeinsolderingtheseheadersisgettingthemstraightand
alignedwitheachotherandthematingArduinoheaders.
InserttheheadersthroughthetopsideoftheEthernetShieldboardsotheextralongpinsextendoutthe
bottom.Iliketoinsertallfourofmyheadersbeforesolderinganyofthem.Whenpluggingthemin,makesure
the6pinheadersgointothe6pinholesandthe8pinheaderstothe8pinholes.

https://www.sparkfun.com/tutorials/409

4/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

Now,fliptheboardover,andsolderall28connections.Trytokeeptheheaderpinsextendingfromthebottom
oftheshieldasperpendiculartothePCBaspossible.Ifyouhaveanothershield,itdoesagreatjobholding
thoseheadersstraight(likeintheabovepicture).

https://www.sparkfun.com/tutorials/409

5/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

Oncetheshieldissoldered,feelfreetoplugitintotheArduino.Makesurenoneofthepinsbendandtheyallgo
intotheirmatingArduinopins.
YoucanalsoplugaSDcardandEthernetcableintotheEthernetShield.TheSDcardgoesintotheshiny
littlesocketontheendoftheboardinsertitsothatthecardslogoisfacingup.Plugonein,andfeelthat
satisfying,lockingclick.
YoullalsoneedtoplugthatEthernetcabletosomethingontheotherend.ItcouldbeanRJ45walljack,an
Ethernetswitch,router,oranadhocsomethingorother.
Finally,onceyouvegottenallofthatpluggedin,poweruptheArduino.Youshouldbeabletopoweritoffthe
USBcable.And,withthat,youshouldseesomeblinkies!ThePWRLEDshouldilluminateforsure.Youmay
alsoseetheSPD,andRX/TXlightup/blinktoo.AlsolookforthegreenandyellowLEDsonthemagjacktolight
upaswell.

TimetouploadsomecodetotheArduino!

Firmware
TheexamplesinthissectionwillallmakeuseoftheArduinoEthernetlibrary.ThislibrarycomeswithArduino,
sonodownloadingorinstallingrequired.Idencourageyoutocheckoutalloftheexamplesketchesforthe
Ethernetlibrary.GotoFile>Examples>Ethernet>andpickasketchtocheckout,mostshouldworkwithout
anymodification.
TheEthernetlibraryallowstheArduinototurnintooneoftwoEthernetdevices:aclientoraserver.Turning
yourArduinointoclientallowsyoutoconnecttoandrequestdatafromservers.Forexample,yourclientcould
makeanhttprequesttoTwitter,andsearchforatweet.Letsdiscussaclientexamplefirst.

EthernetClient

https://www.sparkfun.com/tutorials/409

6/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

LoaduptheTwitterClientexampleintheFile>Examples>Ethernetmenu.Thisismygotoexamplefor
makingsuremyEthernetShieldisworking.ThisexampleconnectstoTwitterandusesitsAPItosearchfor
arduino.ItdisplaystheresultsintheSerialMonitor.
ThereareafewfunctionsandvariabledeclarationsIdliketopointoutinthisexample.First,nearthetop,we
declareanarraynamed mac ,andan IPAddres named ip :
bytemac[]={0x00,0xAA,0xBB,0xCC,0xDE,0x01};
IPAddressip(192,168,1,20);
//initializethelibraryinstance:
EthernetClientclient;
...
charserverName[]="api.twitter.com";//twitterURL

That mac variableiswhatwillbecometheMACaddressofyourArduinoa6bytevalue,whichshouldbe


uniquetoanetwork,andrepresentsthephysicalnetworkaddressofyourdevice.EveryArduinoEthernet
sketchwillneedtodeclareaMACaddress.Thesearedeclaredasanarrayofbytes(inthisexampletheMAC
addressbecomes00AABBCCDE01)butIdencourageyoutocreateyourownMAC.Justrememberitsa
hexvalue,soonlyuse09andAF,anditmustbesixbytes.
The ip variabledeclaresastaticIPaddressforyourArduino.ThevalueabovewouldsetthestaticIPaddress
oftheArduinoto192.168.1.20.Youmayhavetochangethisvalue,dependingonyournetworksubnetand
gatewayaddresses.Alsoknowthatthisvariableisoptional.Hopefullyyoudontevenhavetouseit.The
EthernetlibraryhasDHCPfunctionality,whichmeansyourArduinocanbeassignedadynamicIPbyaDHCP
server.ThisisgreatforclientsketcheswhereknowingourIPdoesntmatterasmuch.
Finally,wemakeacalltotheEthernetClientclasstocreateaninstancenamed client .The client objectis
goingtobewidelyusedthroughtherestofthissketchwheneverwewanttoconnecttoaserveror
send/receivedata.
Finally,the serverName stringissettotheTwitterURL.TheEthernetlibraryhasDNSbuiltin,soyoudonthave
toseekoutIPaddressesifyoudontwantto!Thisstringwillbeusedlater,whenweattempttoconnectto
Twitter.
Nextletslookinsidethe setup() function,whereyoullseethis:
if(!Ethernet.begin(mac)){
//ifDHCPfails,startwithahardcodedaddress:
Serial.println("failedtogetanIPaddressusingDHCP,tryingmanually");
Ethernet.begin(mac,ip);
}

Ethernet.begin()shouldbecalledineveryEthernetsketch.ItsusedtoinitializetheEthernetlibraryaswellas
thenetworksettingsonyourArduino.Noticethattherearetwodifferentcallsto Ethernet.begin() .Thefirstcall
putssolelytheMACaddressasaparameter.Thisversionof begin attemptstograbadynamicIPaddress
fromaDHCPserver.Ifthatfails,ittriestoconnectusingthestaticIPdefinedearlier.
Finally,checkoutthe connectToServer() function:

https://www.sparkfun.com/tutorials/409

7/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

voidconnectToServer(){
//attempttoconnect,andwaitamillisecond:
Serial.println("connectingtoserver...");
if(client.connect(serverName,80)){
Serial.println("makingHTTPrequest...");
//makeHTTPGETrequesttotwitter:
client.println("GET/1/statuses/user_timeline.xml?screen_name=arduino&count=1HTTP/1.1");
client.println("HOST:api.twitter.com");
client.println();
}
//notethetimeofthisconnectattempt:
lastAttemptTime=millis();
}

Thisfunctionusestheclient.connect()toattempttoconnecttoTwittersAPIontheTCPport(80).Following
that,itmakesanHTTPGETrequesttotheserveraskingforatanaddressof
api.twitter.com/1/statuses/user_timeline.xml?screen_name=arduino&count=1.Formoreinfoonwhatthat
meanscheckouttheTwittersAPIDocumentation.Basically,wereseekingoutthetimelineof@arduino,and
lookingatthesinglemostrecenttweettheyvesent.Youcouldevenlookatotheruserstimelinesbyreplacing
arduinowithsparkfunorwhateveryourfavoritetwitterstreammaybe.
Finally,intheloop,assumingtheArduinoconnectedtothetwitterserver,wellreadintheHTTPdatareturned.
Muchoftheloopisdevotedtoparsingthereturneddata,soweendupwithsomethinglikethisifwepeerinto
theSerialMonitor:
AttemptingtogetanIPaddressusingDHCP:
Myaddress:192.168.20.53
connectingtoserver...
makingHTTPrequest...
>@aoqassamnice:)
GohavesomefunwithTwitter,orlearnhowtosetupyourArduinoasaservernext.

EthernetServer
AnothergreatexampleincludedwithArduinosEthernetlibraryisWebServer.FinditunderFile>Examples>
Ethernet.ThissketchsetsuptheArduinoasaserverdevice,andhostsupawebpagewheneveraclient
connectstoit.Thewebpageissimpleitshowsthestatusoftheanalogpins,butitgoesalongwayto
showingwhatcanbedone.
Atthetoparesomefamiliarvariabledefinitions mac and ip .TheIPaddressdefinitionbecomesmuchmore
importantinthiscase,becauseyoullneedtoknowtheIPaddresswhenpointingyourbrowsertotheArduino.
Youmayneedtomodifythe ip variabletoconformwithyournetworksgateway.Thedefault192.168.1.177will
workfornetworksgatewayslikethecommon192.168.1.0,butitmayneedtobemodifiedforothers.Alsomake
suretheIPaddressyoupickisntalreadyinusebyanotherdeviceonthenetwork,creatinganIPaddress
conflict.IPaddressesmustbeunique!
YoucanstillopttouseDHCP,byremovingthe ip parameterfromthe Ethernet.begin(mac) line.Keepinmind
that,withdynamicaddressassignments,yourIPaddresscouldchangefromresettoreset.
Inthissketch,theEthernetServerclassisusedtocreateanobjectnamed server onport80(TCP).And
server.begin() iscalledtoinitializetheserver.

https://www.sparkfun.com/tutorials/409

8/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

Intheloopwewaitforaclienttoconnect.Oncewegetsomething,theArduinoservesupasimpleHTML
webpage. client.println sand client.print sareusedtoserveupHTMLcode.
Tryitout!Uploadthecode,andpointyourcomputerswebbrowsertotheIPaddressassignedtoyourArduino.
YoumayneedtoopenupyourSerialMonitortofindoutwhatIPaddressitwasassigned.Thatllresultin
somethinglikethis:
serverisat192.168.20.58
newclient
GET/HTTP/1.1
Host:192.168.20.58
Connection:keepalive
CacheControl:maxage=0
UserAgent:Mozilla/5.0(WindowsNT6.1WOW64)AppleWebKit/537.11(KHTML,likeGecko)
Chrome/23.0.1271.91Safari/537.11
Accept:text/html,application/xhtml+xml,application/xmlq=0.9,*/*q=0.8
Referer:http://192.168.20.58/
NoticetheIPaddressitlistsforyourArduinoserver.Assumingyourcomputersonthesamenetwork,you
shouldbeabletoopenupyourfavoritewebbrowser,typetheIPaddressintotheaddressbarandGO.You
shouldbegreetedwithawebpagelikebelow.Whichreloadsitselfeveryfivesecondsorso.Ifyouvegotsome
HTMLfutrymodifyingoraddingmore client.print stomakeyourwebpageprettier.

Resources
HerearesomedocumentsrelatedtotheEthernetShielditselfwhichyoumightfinduseful:
SchematicIfyoudlikemoreindepthinformationontheSparkFunEthernetShieldshardwaresetup,
checktheschematicout.
EagleFilesThesearethePCBdesignfiles,sharedbecausethishardwareisopensource!Youcan
downloadanduseEagleLiteforfreetoviewthesefiles.
FormoreinformationontheArduinolibrariesused:
Ethernetlibraryreference
SDlibraryreference
Thanksforreading!Ihopethishasgottenyouwellonthewaytocreatingthenextsuperawesome,network
enabledArduinoproject.Ifyoureleftwithanyburningquestions,comments,orfeedback,pleasepostawayin
thecommentsbelow!

Comments2comments
Loginorregistertopostcomments.
https://www.sparkfun.com/tutorials/409

9/10

9/1/2016

SparkFunEthernetShieldQuickstartGuideSparkFunElectronics

Icouldreallyusesomespecdatasheetsforthev2,v3,v4andthev66DOFgreenboardsfromycollege
Member#615502 / about2yearsago / 1

assignment.

Hey,richtigsuperInternetseite.WoherhastdudasThemeoderistdasselbstprogrammiert?Leasedlinequote
Member#444188 / about3yearsago / 1

https://www.sparkfun.com/tutorials/409

10/10

Anda mungkin juga menyukai