Tải bản đầy đủ (.pdf) (226 trang)

Connecting arduino programming and networking with the ethernet shield

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.65 MB, 226 trang )



ConnectingArduino:ProgrammingandNetworkingwiththeEthernetShield
Copyright©2014BobHammell.
EBooksarenottransferable.Allrightsreserved.Nopartofthispublicationmaybe
reproduced,distributed,ortransmittedinanyformorbyanymeans,including
photocopying,recording,orotherelectronicormechanicalmethods,withoutthe
priorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotations
embodiedincriticalreviewsandcertainothernon-commercialusespermittedby
copyrightlaw.
Trademarkednames,logos,andimagesmayappearinthisbook.Ratherthan
useatrademarksymbolwitheveryoccurrenceofatrademarkedname,logo,or
image,thenames,logos,andimagesareusedonlyinaneditorialfashionandto
thebenefitofthetrademarkowner,withnointentionofinfringementofthe
trademark.
TheinformationinthispublicationisprovidedbyBobHammellonan“ASIS”
basis.BobHammellmakesnowarranties,expressorimplied,regardinguseof
theinformationaloneorincombinationwithyourproducts.Neithertheauthornor
theeditorsnorthepublishercanacceptanylegalresponsibilityforanyerrorsor
omissionsthatmaybemade.
PublishedintheUnitedStatesofAmericabyBobHammell.
ISBN-10(Print):1-500-74567-7
ISBN-13(Print):978-1-500-74567-7
ISBN-13(ePub):978-1-312-41034-3
Anysourcecodeorsupplementarymaterialsreferencedbytheauthorinthistext
areavailableforreadersatwww.connectingarduino.com.



TableofContents
Preface


GettingStarted
ConnectingtheEthernetShield•Establishinganetworkconnection•
Testingconnections
UsingSDCards
FormattingandinitializingSDcards•ReadingandwritingfromSD
cards•Creatingandremovingdirectories
ArduinoasaWebClient
MakingHTTPGETandPOSTrequests•Scrapingwebpages•
Handlingtimeouts•Sendingtweets
ArduinoasaWebServer
UsingastaticIPaddress•PortforwardinganddynamicDNS•
AcceptingincomingHTTPconnections•ServingfilesfromtheSD
card•Creatingaweb-basedUI
UsingUDPandSocketProgramming
CommunicatingoverUDP•BuildingaDNSserver•Implementinga
customapplicationprotocol
AppendixA–HypertextTransferProtocol–HTTP/1.0
AppendixB–DNS–ImplementationandSpecification



Preface
Atthispoint,theArduinohardlyneedsanyintroduction.It’sbecomeaforceof
nature–inspiring,initsshortlifetime,millionsofpeoplefromallwalksoflifeand
withvaryinglevelsofpriorexperienceinelectronicsandcomputerprogramming.
There’smuchyoucandowiththisflexibledevelopmentplatform,andsomuch
amazingworkhasalreadybeendone.Butwherethingsreallygetinteresting,
reallygetuseful,iswhenyoumakeprojectsthattalktoeachotherandtotherest
oftheworld.
Thathobbyistandbeginnerelectronicshackersand“makers”cancreate

standalonedeviceswhichcommunicatewithothermachinesonthelocalnetwork
andacrosstheInternet,andusingthesameInternetprotocolsasusedby
desktopPCs,servers,andmobiledevices,iscertainlynotinsignificant.
Despitetheemergenceofnewdevelopmentboards,shields,andmodules,the
EthernetShieldremainsapopularchoiceforArduinoprojects.Andit’seasyto
seewhy–thesectionofthisbookthatcoversgettingtheshieldupandrunningis
verythin.Unfortunately,makingfulluseofthisingeniousdeviceisalittlemore
difficultthanthefirststepssuggest…Andthatbringsmeneatlytothesubjectof
protocolsandthereasonwhyIwrotethisbook.


What’sinthisBook?
Internetandnetworkcommunicationismadeupofmanylayers–startingwith
low-levelprotocolsandtechniquesusedtohandlecommunicationwithhardware
devices,suchasnetworkcards,modems,andWi-Fidongles.Ontopofthislayer,
theInternetprotocol(IP)isresponsibleforthedeliveryofmessagefragments(or
packets)totheintendedrecipient.Then,runningoverIP,youhavethetransport
layerwheretransportcontrolprotocol(TCP)addserror-checkingandstreaming
capabilities.Theapplicationlayerconsistsofprotocolssuchashypertexttransfer
protocol(HTTP),domainnamesystem(DNS),andsimplemailtransferprotocol
(SMTP).Theseapplicationprotocolsdefinehowdataisencodedandexchanged
foraspecificpurpose.Youcouldalsosaythatweb-basedapplication
programminginterfaces(APIs)andwebserviceswhichrunoverHTTPadda
fourthlayertothissystem.
TheEthernetShield,inpartnershipwiththeEthernetlibrarythatcomeswiththe
ArduinoIDE,doesanexcellentjobofencapsulatingthecomplexitiesofTCP/IP
andtalkingtotheWiznetW5100integratedcircuitontheshield.Butitshelponly
goesasfarasthetransportlayer;you’reonyourownwhenitcomestoHTTPand
theapplicationlayer.Atfirst,workingwiththeseprotocolsseemsadauntingtask
–onethatappearsthatonlyaccomplishedandexperiencedprogrammershave

theskillsorknowledgetoattempt–andthissuggestionisreinforcedbythe
relativelysmallnumberofexamplesandguidesthatreallytrytoexplainthe
detailsofapplicationprotocolstoArduinoprogrammers.Soifyoulearnonlyone
thingfromthisbookthenIhopeitisthis:workingwithapplicationprotocolsis
nothingtobeafraidof.
I’vewrittenConnectingArduinotoshowyou,inquitealotofdetail,howtouse
applicationprotocolsinyourArduinosketchesandgetthemostoutofthe
EthernetShield.Themajorityoftheinformationisorganizedintoeight“projects”–
andIusethattermloosely.Thegoalwasnottogiveyouarecipebook,ora
collectionofplansforArduinoprojects.Instead,Iwanttowalkyouthroughthe
backgroundinformation,libraryclassesandmethods,andprogramming
techniquesthatyoucanuseinyourownprojects.But,critically,Iwantedtogive
eachitemenoughcontextualinformationsothatit’seasyforyoutoseeits
relevancetothetaskathand.Thechaptersdivideintothemes,andeachproject
buildsontheknowledgeandinformationpresentedinthepreviousproject.As
such,youmayfinditbeneficialtoreadthroughthebookinorder,evenifyoudo
notactuallybuildandcompleteeachproject.
Myprojectsmightseembasic,buttheonesyoudevelopyourselfafterwardswill
bemuchmoreinteresting.AndIhopeyouletmeknowaboutthecoolthingsyou
build–orbetterstill,havethedevicescontactmethemselves.


WhoShouldReadthisBook?
Unfortunately,Ican’tteachyoueverythingabouttheArduinointhespaceofone
book.There’stoomuchaboutelectronics,C,andprogrammingingeneralto
cover.Ihavetoassumethatyou’realreadycompetentatprogrammingthe
Arduinoandbuildingsimplecircuits.Withthissaid,ifyoucanconnectalightemittingdiode(LED)totheArduino,throughanappropriateresistor,andwritea
sketchthatturnstheLEDonandsendsamessagetotheArduino’sserialport
thenyou’lleasilyunderstand90%ofthecodeandcircuitryinthisbook.
Forsomeoftheprojects,basicfamiliaritywithhypertextmark-uplanguage

(HTML)wouldbeuseful.Buildingwebpagesandweb-baseduserinterfacesis
definitelyaskill,butitisonethatyoucanlearnasyougo,andthereisno
shortageofexcellenttutorialsavailableonlinetohelpyou.


OnlineResources
ConnectingArduino.comisthecompanionwebsiteforthisbook;youcancontact
methereifthere’sanythingIcanhelpyouwithorifyouwanttoshowoffyour
work.I’vealsoputalloftheprojectsketchesuptheresothatyoucandownload
them,insteadoftypingthemin.It’llbeworthyourwhiletovisitthesiteregularly–
anynews,updates,andaddendumswillbepostedtherefirst.
Tothebestofmyability,Ihaveverifiedtheaccuracyofalloftheinformationinthis
book,andtriedtoensurethatthecodesamplesarerobustenoughforyoutouse
(whilenotbeingsofullofoptimizedprogrammingcodeanderror-checkingasto
makethecodedifficulttounderstand).However,thingschangeandmistakesdo
happen.Youcanhelpmetoimprovefutureeditions,forthebenefitofother
Arduinoenthusiasts,bycontactingmeatthewebsiteifyoufindanyerrors,
inaccuracies,orplaceswhereinformationisconfusing.


ConventionsUsedinthisBook
Thefollowingtabledescribesthetextconventionsusedinthisbook.
Convention

Meaning

Italic

Textthatappearsinitalicsreferstofilenames,variableand
functionnames,orothercodethatexistsintheprojectsketch

orArduinolibraries.Withinthecontextofgivinginstruction,
italictextshouldbetypedexactlyasshown.

Bold

Withinthecontextofgivinginstruction,itemsinboldtextare
userinterfaceelements,suchaskeystrokes,menuitems,or
buttonlabels.Inothercontexts,wordsmaybeemboldenedfor
emphasis.

Monospace
font

AmonospacefontisusedforArduinoC,Processing,
JavaScript,andHTMLcodethatshouldbetypedinyour
project.

Coloredtext

Itemsshownwithcoloredtextarelinkstootherpagesinthis
book.



GettingStarted
TheArduinoEthernetShieldisanadditionalcircuitboardthatfitsontopofyour
Arduino.ItextendstheArduino’scapabilitieswithcircuitrytoconnecttoanetwork
router,usingacommonly-availableRJ45Ethernetcable.YourArduinoprojects
cancommunicatewiththeworldthroughthisconnection–everythingfrom
fetchinginformationfromtheInternetanddisplayingitonaliquidcrystaldisplay

(LCD),toprovidingpublically-accessible,web-basedtoolsthatcancontrolmotors
andotherhardware.
Morethanjustahardwaredevicethatcanconsumecontentandaccept
messages,theEthernetShieldisyourentrypointintobuildingthingsforthe
InternetofThings–devicesthattakeanactiveroleintalkingtohumansandother
machinesoverInternetprotocols.
InThisChapter
ConnectingtheShield
EstablishingaNetworkConnection
IntroducingWebClientsandWebServers


ConnectingtheShield
TheArduinoEthernetShieldR3mountsontopofArduinodevicesusinglong
wire-wrappedheadersthatextendthroughtheshieldandintotheheadersofthe
Arduinobelow.Itonlyfitsinonedirection.
ToconnecttheshieldtoanArduinoUnoR3orArduinoLeonardo:
1. DisconnecttheArduinofromallpowersources,andremoveanywires
connectedtoit.
2. Lineuptheshield’sheaderswiththoseoftheArduino.
3. Applygentlepressureuntiltheshieldslotssecurelyintoplace.

Figure1.ConnectingtheshieldtoanArduinoUno

ToconnecttheshieldtoanArduinoMega2560:
1. DisconnecttheArduinofromanysourceofpowerandremoveanywires
connectedtoit.
2. Lineuptheshield’sheaderswiththoseoftheArduino.Theshieldslotsinto
thetwoleft-mostgroupsofheaders–uptoRX0onthetoprowandA5onthe
bottomrow.

3. Applygentlepressureuntiltheshieldslotssecurelyintoplace.


Figure2.ConnectingtheshieldtoanArduinoMega2560

TheEthernetShieldR3canalsobeusedwithearlierUnodevicesandthe
Duemilanove.However,whenusingolderArduinos,fouroftheshield’sheader
pinsareleftunconnected.Youmustensurethatnoneofthesepinsareallowedto
makecontactwithanyoftheArduino’scomponents,oreachother.
Suitableoptionsforthisare:
Wrapthetwoleft-mostpinsonthetoprow,andthetwoleft-mostpinsonthe
bottomrow,ininsulatingtape.
Bendthetwoleft-mostpinsonthetoprow,andthetwoleft-mostpinsonthe
bottomrow,awayfromcontactwiththeArduino.
OncetheshieldisfittedsecurelyontheArduino,youcanreconnectthepower.
Caution:Itisusuallysafetoconnectanddisconnectcablesandwires
fromtheEthernetshieldwhiletheArduinoisconnectedtoitspower
supply.However,toavoidanyaccidentaldamagetoelectronic
components,itispreferabletodisconnectthepowerbeforedoingso.
TheconnectorsandkeycomponentsoftheArduinoEthernetShieldR3are
shownbelow:


Figure3.TheArduinoEthernetShield

ItispossibletostackothershieldsontopoftheEthernetShield,andtousemost
oftheArduino’spinsasusual.However,theArduinotalkstotheEthernetShield
overSPIandwhenactuallyusingtheEthernetShield,thefollowingpinsare
unavailableforanyotherpurpose:
ArduinoUno

Pin

ArduinoMega
Pin

Function

D4

D4

SS–whenusingtheSDcard.

D10

D10

SS–whenusingtheEthernetShield’sSPI
interface.

D11

D50

MOSI

D12

D51


MISO

D13

D52

SCK



D53

Notused.Butmustnotbesettoaninput.

ThereareseveralmethodsofcablingtheEthernetShieldtoyournetwork.This
choicemakesnodifferencetohowArduinosketchesareprogrammed,andyou
shouldsimplychoosetheonethatismostconvenientforyouandyour
workspace.

ConnectingtheEthernetShieldtoaRouter
ToconnecttheEthernetshieldtoarouter:


1. PlugoneendofaCAT5orCAT6EthernetcablewithRJ45connectorsinto
thesocketontheEthernetShield.
2. PlugtheotherendofthecableintoanavailableEthernetportonyourrouter.
3. PlugtheArduinointoasuitablepowersupply(ifitisnotconnectedalready).

UsingPowerLineAdapters
UnlessyouhaveaverylongEthernetcable,itmaynotbeconvenienttocable

yourEthernetShielddirectlytoyourrouter.
PowerLineadaptersaredevicesthatplugintoelectricalsocketsandsend
computersignalsalongthepowerlinesinyourhome.Theyaresoldinpairs:one
istobepositionedneartotherouterandoneistobeusedwhereneeded.
TheseadaptersrequirenoconfigurationandworkwellwiththeArduinoEthernet
Shield.

ConnectingtheEthernetShieldthroughaBridged
Connection
UsingastandardEthernetcable(oracrossovercable,ifyouhaveareallyold
PC),youcanconnecttheEthernetShieldtoyourPCandshareitsnetwork
connection.
1. PlugoneendofaCAT5orCAT6EthernetcablewithRJ45connectorsinto
thesocketontheEthernetShield.
2. PlugtheotherendofthecableintoafreeEthernetportonyourPC.
3. PlugtheArduinointoasuitablepowersupply(ifitisnotconnectedalready).
Fortheshieldtobeabletoconnecttothenetwork,youmust“bridge”the
connectionthatyourPCusestoconnecttothenetworkwiththeconnectionthatis
madetotheEthernetShield.Theprocessfordoingthismaybedifferent
dependingontheoperatingsystemthatyouarerunning.
OnWindows8/7/Vista/XP:
1. PresstheWindowslogokey+R.
2. Typencpa.cplandpressEnter.
3. HolddowntheCtrlkeyandclickboththenetworkconnectionthatisusedby
yourPCtoconnecttothenetwork,andthenetworkconnectionthatis
connectedtotheEthernetShield.
4. Right-clickoneoftheselectedconnections,thenclickBridgeConnections.
OnMacOSXyoucanshareyourMac’sWi-FiconnectionwiththeArduino
EthernetShield:



1. OntheApplemenu,clickSystemPreferences,andthenclickSharing.
2. Onthesidebar,clickInternetSharing1 ,andchoosetheInternetconnection
youwanttosharefromthe“Shareyourconnectionfrom”menu.
3. Selectthecheckboxlabelled“Built-inEthernet”.
4. ClickStart.
IfyourPC’soperatingsystemwarnsyouthatithasdetectedanIPaddress
conflict,youmayhavetoconnecteitheryourPCortheArduinotothenetwork
usingastaticIPaddress.


EstablishingaNetworkConnection
TheRJ45socketontheEthernetShieldcontainstwolight-emittingdiodes(LEDs).
TheleftLEDisthelinkindicatorandglowsorblinksgreenifasuccessfullinkhas
beenmadetotherouter.YoucanalsofindthissameindicatorasasurfacemountedLEDjustabovetheRJ45socketontheshield.IfthelinkLEDisnotlitat
all,checkyourconnectionsandreplacetheEthernetcableifpossible.Insome
circumstances,itmayalsobeusefultorestartyourrouter.
AgreenLEDdoesnotmeanthattheArduinoisnowconnectedtothenetwork,
onlythatcommunicationbetweentheshieldandtherouterisworking.Toactually
makeafullconnectiontothenetwork,theArduinomustbeprogrammedwitha
sketchthatusestheEthernetlibrarytosetseveralconfigurationoptions.
Inthissectionyouwillseehowtocreateabasicsketchthatconnectstoyour
networkoverdynamichostconfigurationprotocol(DHCP),andhowtotestthat
yourArduinoisproperlyconnected.

StartingaNewSketch
IntheArduinointegrateddevelopmentenvironment(IDE),startanewsketch.
TheArduinotalkstotheEthernetShieldoverserialperipheralinterface(SPI),and
sotoworkwiththeshieldyoumustincludeboththeEthernetandSPIlibrariesin
yourproject.Todothis,addthefollowingtwolinestothetopofthesketch:

#include<SPI.h>
#include<Ethernet.h>

SpecifyingaMACAddress
Thenextpieceofinformationthatisusuallydefinedinthesketchisthemedia
accesscontrol(MAC)address.AMACaddressisa48-bitnumber(usually
expressedas6bytes)thatuniquelyidentifiesadeviceonalocalareanetwork.
Thesenumbersareusuallybuilt-intothedeviceandneverchange.Youcan
generallyfindtheMACaddressforyourArduinoEthernetShieldprintedona
stickerontheundersideoftheshield,orontheboxthattheshieldcamein.Butif
youdonothaveone,itisusuallyfinetomakeupsixrandomnumbersfrom0
through255.Itishighlyunlikelythatyouwillrandomlychooseanaddressthatis
currentlybeingusedbyanotherdeviceonyournetwork.
MACaddressescanalsobeboughtfromtheIEEERegistrationAuthority,oryou
canbuyaread-onlymemory(ROM)chipthatispre-programmedwithaunique
address.MicrochipTechnologyInc.andMaximIntegratedInc.offerarangeof
low-costchipsofthistype.


TheMACaddress(eitherrandomlygeneratedorpurchased)istypicallyincluded
intheArduinosketchasaglobalarrayofbytes:
bytemac[]={0x00,0xC3,0xA2,0xE6,0x3D,0x57};

Asitisunlikelythatyouwilleverneedtomodifythisaddresswhilethesketchis
running,youcanalsodefinetheMACaddressusingaconstantarray:
constbytemac[]={0x00,0xC3,0xA2,0xE6,0x3D,0x57};

CompletingtheSketch
ThefullArduinosketchisshownbelow.Thisexampleconnectstothenetwork
usingDHCP,duringwhichtherouterassignsconnectionpropertiestothe

EthernetShielddynamically,andthenthesketchsendstheconnectiondetailsto
theserialport.Youcanviewthisinformationintheserialportmonitorinthe
ArduinoIDE.
#include<SPI.h>
#include<Ethernet.h>
bytemac[]={0x00,0xC3,0xA2,0xE6,0x3D,0x57};
voidsetup(){
//D53onanArduinoMegamustbeanoutput.
pinMode(53,OUTPUT);

Serial.begin(9600);
while(!Serial);

Serial.print("Establishingnetworkconnection…");

if(Ethernet.begin(mac)==0){
Serial.println("FAILED!");
}
else{
Serial.println("OK!");

Serial.print("IPAddress:");
Serial.println(Ethernet.localIP());

Serial.print("DefaultGateway:");
Serial.println(Ethernet.gatewayIP());

Serial.print("SubnetMask:");
Serial.println(Ethernet.subnetMask());


Serial.print("DNSServer:");
Serial.println(Ethernet.dnsServerIP());
}
}
voidloop(){
}

Themethodbegin()intheEthernetlibrary’sEthernetclassattemptstoconnectto
thenetworkusingthedetailspassedintoitasarguments.
Thereareactuallyfourformsofthismethodthatyoucanuse,dependingonhow
muchinformationyouwanttospecify:
voidbegin(uint8_t*mac,IPAddressip)
voidbegin(uint8_t*mac,IPAddressip,IPAddressdns)
voidbegin(uint8_t*mac,IPAddressip,IPAddressdns,IPAddressgateway)


voidbegin(uint8_t*mac,IPAddressip,IPAddressdns,IPAddressgateway,IPAddresssubnet)

Atabareminimum,youmustcallbegin()andpassaMACaddressasanarrayof
bytes.IfyoudeclaretheMACaddresswiththekeywordconst,youwillneedto
castittoapointerofuint8_tvalues.Forexample:
Ethernet.begin((uint8_t*)mac);

IfyoupassanIPaddressthentheEthernetShieldwillmakeanetwork
connectionusingastaticIPaddress.IfyoudonotdefineanIPaddressthenthe
shieldwillobtainonefromtherouterusingDHCP.Formoreinformationabout
staticIPaddresses,seeUsingaStaticIPAddress.
Theremainingtwo,optionalparametersareusuallynotneededexceptwhen
workingwithcomplicatednetworks.Ifyouhavetospecifythegatewayaddress
thenyoumustuseastaticIPaddress.Ifyouneedtospecifythesubnetaddress

thenyoumustprovideallthreeoftheotherarguments,andconnecttothe
networkusingastaticIPaddress.
begin()willreturnthevalue1ifitconnectedsuccessfully,and0iftheconnection
failed.
Ifthesketchfailstoestablishaconnectionthenthereareafewthingstotry:
ChangethecodetouseadifferentMACaddress.
Checkthatthelinkindicator(asdescribedabove)issolidgreenorblinking.If
thereisnolightthenthisindicatesaproblemwithyourwiring.
Checkyourwiringcarefully.ReplacetheEthernetcable(ifpossible),andtrya
differentconnectionmethod–suchasdirectlytoyourrouter.
Whenthesketchsuccessfullyestablishesanetworkconnection,itcallsfour
methodsoftheEthernetclasstoretrievetheconfigurationsettingsthatwere
givenbytherouter.
Method

Description

dnsServerIP()

ReturnstheIPaddressoftheprimaryDNSserverusedto
lookupdomainnamestofindtheirIPaddresses.

gatewayIP()

ReturnstheIPaddressoftherouterdevicethatprovidesthe
otherswithnetworkaccess.

localIP()

ReturnstheIPaddressoftheEthernetShieldonthenetwork.


subnetMask()

Returnsthesubnetmaskusedbythenetworktosegregate
devicesintologicalgroups.

TheDNSserver,gateway,andsubnetmaskdetailssenttotheserialportshould
matchthoseusedbyotherdevicesonyournetwork.


TolearnhowtosettheIPaddressandothernetworkconfigurationparameters
manually,andrelatedtopicssuchasportforwardinganddynamicDNS,see
ArduinoasaWebServer.

TestingtheConnection
TocheckthattheArduinoisabletorespondtonetworktraffic,youcanpingit.
OnWindows8/7/Vista/XP:
1. PresstheWindowslogokey+R.
2. Typecmd,thenpressEnter.
3. Typeping,followedbyaspace,andthentheIPAddressdisplayedinthe
serialportmonitoroftheArduinoIDE.
4. PressEnter.

Figure4.AsuccessfulpingonWindows

OnMacOSX:
1. Onthedock,clickFinder.
2. Onthesidebar,clickApplications.
3. ClickUtilities,thendouble-clickNetworkUtility.
4. OnthePingtab,intheboxlabelled“Enterthenetworkaddresstoping”,type

theIPAddressdisplayedintheserialportmonitoroftheArduinoIDE.
5. ClickthePingbutton.


IntroducingWebClientsandWebServers
Oncomputernetworks,suchastheInternet,machinesanddevicescanbe
definedintermsoftherolestheyplaywhenexchanginginformation.Thereare
twodifferentroles:clientsandservers.
Clientsstartconnectionswithothermachinesinordertoaccesstheinformation
thatiscontainedonthem.Forexample,awebbrowserisaclientthatconnectsto
othermachinestorequestwebpagesorfilesfromthem.
Themachinethatstoresand“serves”theinformationthatisrequestedisknown
asaserver.Serverssitandwaituntilaclientstartsaconversationwiththem,and
theyaretypicallycapableoftalkingtomanythousandsofclientsatthesame
time.Iftheserveris“offline”,oritisinanywayinaccessible,thentheinformation
thatneedstobesharedwithclientsisunavailable.
Inmostmoderncomputersystems,amachinecanactasbothaserveranda
clientatthesametime.Itsroleintheexchangeofinformationdependsonthe
softwareitisrunning,anditcanrunbothclientsoftwareandserversoftwareif
youneeditto.ButtheArduino’srelativelylowhardwarespecifications,andits
lackofamulti-taskingoperatingsystem,largelypreventitfrombeingbotha
serverandaclientatthesametime.
WhenwritingArduinosketchesthatusetheEthernetShield,youwilloftenneedto
decidebetweenprogrammingaclientandprogrammingaserver.Thequestions
toaskare:
1. Doyouneedtosendrequeststoothersystems,forexampleTwitter,eBay,
Facebook,andotherstoaccomplishthetask?Ifyoudo,youwillcreatea
clientbecausethosesystemsareservers.
2. DoestheArduinogatherorholdinformationthatmultipleothermachines
needtoaccess?Ifso,youwillcreateaserver.

3. DoestheArduinostartconnections,orshoulditsitandwaitforothersto
connecttoit?Createaclientwhenyouneedtostarttheconnections,anda
serverwhenyouneedtowaitforincomingconnectionstobecreatedby
anotherdevice.
ForinformationaboutcreatingclientsusingtheArduinoEthernetShield,see
ArduinoasaWebClient.
ForinformationaboutcreatingserverprojectsusingtheArduinoEthernetShield,
seeArduinoasaWebServer.
1

InearlyversionsofMacOSX,clicktheInternettab.



UsingSDCards
TheArduinohasquiteasmallamountofon-boardstorageandmemory.Onits
own,itcannotstoreenoughinformationtoservealargeweb-basedinterfaceor
sendmanyfilestoconnectedclients.Andwhenactingasaclientitself,manyof
thefilesanArduinoprojectneedstodownloadaretoobigtobeheldinmemory.
TheArduinoEthernetShieldcomeswithabuilt-inSecureDigital(SD)cardsocket
thatyoucanaccessusingtheSDlibrary,SD.h.Thislibraryissuppliedwiththe
Arduinointegrateddevelopmentenvironment(IDE),andsupportsFAT16and
FAT32filesystemsonstandardSDcardsandhigh-capacitySDHCcards.
SD.hisawrapperthatsimplifiesaccesstotheSDcard.Itusesanotherlibrary,
SDFat.h,whichisnotcoveredinthisbook.SDFat.hismuchmorecomplicated,
containingmanymethodsanddatastructuresforworkingwiththeSDcardata
low-level,anditmaybeinterestingtoreaderswhoarealreadyexperiencedwith
SDcards.
InThisChapter
FormattingandInitializingSDCards

ReadingfromSDCards
WritingtoSDCards


×