2015
PennState University
Chad RyanWeiss
ChibanSankari
Instructor: Dr. R. Gray
CONNECTING ARDUINO TO THE INTERNET
Thisdocumentwalksusersthroughthe processesinvolvedinconnectinganArduinoUnomicro-
controllertothe Internet. Specifically,thisdocumentwalksusersthroughthe processof uploadinga
TMP36 sensor’sdata tothe webas well asforthe processof settingupa serverthat allowsfor
controllingelectronicdevicessuchasRGB LEDs from a local web-basedclient. Inadditiontothe actual
experiment,userswill learnagreatdeal about the computernetworksandthe communication
protocolsthatwere establishedinordertosupport one of the greatestinventionsknowntoman,i.e.
the World Wide Web.
1 | P a g e
Table of Contents
Content Page No.
Introduction……………………………………………………………………………………………………………………………………3
History……………………………………………………………………………………………………………………………….3
Topology…………………………………………………………………………………………………………………………….3
Networks……………………………………………………………………………………………………………………………4
Protocols…………………………………………………………………………………………………………………………...4
ClientsandServers……………………………………………………………………………………………………….……5
Microcontrollers…………………………………………………………………………………………………………………5
Shields………………………………………………………………………………………………………………………………..5
Methods………………………………………………………………………………………………………………………………………….6
ConnectingArduinotothe Network………………………………………………………………………………….6
ArduinoServer……………………………………………………………………………………………………………………7
Results………………………………………………………………………………………………………………………………..7
Summary…………………………………………………………………………………………………………………………………………10
DiscussionandAnalysis……………………………………………………………………………………………………….10
Conclusion…………………………………………………………………………………………………………………………..12
References………………………………………………………………………………………………………………………….12
Figures Page No.
Figure 1: Simple LAN Physical Topology…………………………………………………………………………………………..3
Figure 2: OSI Model………………………………………………………………………………………………………………………...4
Figure 3: MicrocontrollerandSubsystems………………………………………………………………………………………5
Figure 4: ArduinoUno Microcontroller…………………………………………………………………………………………….5
Figure 5: ArduinoUno and WiFi Shield……………………………………………………………………………………………..6
Figure 6: TMP36 Sensorw/RGB LED Circuit……………………………………………………………………………………..7
Figure 7: TMP36 SensorCircuitSchematic……………………………………………………………………………………….7
Figure 8: ArduinoSerial MonitorConnectionStatus………………………………………………………………………..8
Figure 9: ArduinoSerial MonitorWaitingforClient………………………………………………………………………….8
Figure 10: Website URL(IP AddressForm)……………………………………………………………………………………….9
Figure 11: ArduinoServerLocal NetworkWebsite…………………………………………………………………………..9
Appendices Page No.
Appendix A: ArduinoServerCode…………………………………………………………………………………………………….13
2 | P a g e
Equipment Used
ArduinoUno
USB Cable
WiFi shield101
TMP36 temperature sensor
RGB LED
220Ω Resistors(x3)
Jumperwires
Breadboard
3 | P a g e
Figure 1: Simple LAN Physical Topology
Introduction
History ofthe Internet
In the early1970’s communicationprotocolswere developedsothatindividual stations(i.e.computers
and otherdevices) couldinteractwith eachotheronthe networkandhence,formingalocal area
network(LAN). These networkswere ultimatelyestablishedtoallow stationstoshare informationand
resourceswith one another.
Later, the U.S. Departmentof Defense’sAdvancedResearchProjectsAgency(DARPA)startedto
experimentwithwide areanetworks(WAN). These networks were toeventuallyspanacrossthe United
States. The original intentof thisprogramwasto linkgovernmentaffiliations,educational institutions
and researchlaboratoriestogetherinhopesof sharingdata;however,itdidnottake longforDARPA to
realize the potential of sucha WAN and the possibilitiesof providingthesenetworksacrossthe globe.
In orderto establishsuchanetwork,aframeworkhadto be developed. DARPA continuedtoresearch
and fundARPANET(the WAN project) until thisfeathadbeenaccomplished. The resultof this
accomplishmentwasaframework thatwassoonto be knownasthe TransmissionControl Protocol and
the InternetProtocol (TCP/IP). These protocolsare still inuse today andcurrently constitutethe basic
setof rulesusedtocommunicate over acomputernetwork.
NetworkTopology
There are twotypesof layoutsas far as computernetworksare concerned. The twodifferentkindsof
layoutsare calledtopologiesandforeachnetworkthere can be a physical orlogical topology. Topology
isdefinedasthe interrelation betweenpartsin a givensystem. Visual representationsof such
topologiesare usuallygeometricinnature.
Althoughthere are manywaysto connectto the Internet,whetherit isbyEthernet,TokenRing, Fiber
DistributedDataInterfaces(FDDI) orWiFi,all of the followingrequire apiece of hardware knownasa
routerto connectthe individual stationtothe Internet. Occasionallyamodemisrequiredfor
Cable/Ethernetconversions.
Physical topologyreferstothe physical structuringof devices
withinacomputernetworkandthe connectionsestablished
therein. See Fig.1. Logical topologyreferstothe pathsthat the
data takesthroughthe networkwithoutrestrictiontothe
physical layoutof the devices.
Furthermore,there are manydifferentconfigurationsregarding
physical topologieswithincomputernetworksingeneral. Such
configurationsinclude the following: point-to-point,bus,star,
ringor circular,mesh,tree,hybridordaisychain configurations.
4 | P a g e
Local and Global Area Networks
Computernetworksare characterizedbytheirorganizational purpose aswell astheirphysical capacity
for devices. Theycan vary insizesincludinganythingfromnanoscale networkstoglobal areanetworks.
The most commonlyknownnetworksare LANsandWANsbothof whichhave subsystemsof theirown.
LANs,alsoknownas local area networks,are networksconfinedwithinacertaindistance of a local
router. These networksmayinclude personal areanetworks (PANs)orhome areanetworks(HANs).
WANs,alsoknownas wide areanetworks,are networksthatcoverlargerareassuch as cities,states,
countriesoreveninternational distances. Some examplesof thistype of networkwouldbe campus
area networks(CANs) ormetropolitanareanetworks(MANs).
CommunicationProtocols
Protocolsare rulesusedto define the methodsof communicationwithinanycomputernetwork. Fig.2.
shownbelowrepresentsthe stackedprotocolsusedwhencommunicatingoverthe Internet. This
particularmodel iscalledthe OSImodel.
Figure 2: OSI Model
The model isbrokendownintosevenlayersstartingwiththe surface workingitswaydowntothe core.
At the lowestlevel,thereare protocolsthatregulate andstandardize the methodforcommunicating
individualbitsof information. Several examplesof these protocolscanbe seeninthe righthand column
of the OSImodel. For example HTTP,orthe HypertextTransferProtocol,isshowninthe uppermost
layerof the model. Itisusedwhenconnectingclientsandserverstoone another. HTML, or Hypertext
Markup Language,isshowninthe followinglayer. Thisstandarddefinesthe methodforpresentingdata
ina web-like format;hence,itisthe standardizedcodinglanguageforformattingwebpages.
Furthermore,there are protocolsfororganizingdata, transferringdata,packetizingdata,framingdata
and constructingdata. At leastone protocol isused foreach layerwhilstcommunicatingovera
network.
5 | P a g e
Clients and Servers
In typical communicationsessions,thereisalwaysasenderanda receiverof the original message,
whetherornot that message isaquestionora demand. For Internetcommunicationnetworks,there
are clientsandservers. Serversserveclientsinformationwheninformationisrequestedandclientsare
devicesthatrequest dataandobtainresponsesfromthe server.
Microcontrollers
A microcontrollerisa programmable mini-computerthatcan interface withelectrical or
electromechanical systems,includingcomputernetworks. Furthermore,microcontrollershave the
abilitytomanipulate datathroughtheirpreinstalledA/Dconverters(analog-digital). Despite havingsix
analogoutputpins,the microcontrollerismostlyadigital communicator;however,itdoeshave the
abilitytoproduce pulse-widthmodulatedsignalswhichare satisfactoryformostof the applications.
Microcontrollersare usuallybehindthe scenesdoingmostof the work. Theycan be foundinindustrial,
residentialandcommercial aswell asintransportation applications. Governmentagenciesandprivate
sectorcompaniesuse controllersandmicrocontrollersinawide variety of ways. Some applications
include renewableenergyprojects,asinsuntrackingPV solar systemswhileothersare implementedin
automationsystems,sensornetworksorsecurity units,etc.
Shields
Shieldsare add-ondevices thatallowamicrocontrollertointerface withaspecifiedenvironment. For
example,the ArduinoWiFi shieldisaseparable componentthatcanbe attached to anycompatible
Arduinobasedmicrocontroller. Thisshield,inparticular,hasanintegratedWiFi antennathatallowsthe
controllertoconnectto a WiFi network. Ineffect,addingthisshieldtoacontrollerincreasesitsnumber
of operatingenvironments,thusincreasingitsfunctionality. Furthermore,shieldsare stackable andif
one wantedto adda solarshieldtoharnessenergyfromthe sunandconvertit to electricity,one could
do so withthe use of the right shield.
Figure 3: Microcontroller and Subsystems Figure 4: Arduino Uno Microcontroller
6 | P a g e
Methods
Connecting Arduino to a Network
In connectingArduinotothe Internet,the firststepistoconnectthe WiFi101 shield tothe ArduinoUno
microcontroller. The layoutsof the pinsare exactlythe same for the Uno as for the shield;therefore,
the Uno female connectorsshouldreceivethe WiFi101shield’smale connectorswithoutcomplication.
Afterconnectingthe shieldinwiththe controller,the Unoisnow WiFi compatible. (Lateron,we will
attach sensorsandothercomponentstothe systembutfor rightnow,we will focusonconnectingto
the network).
Afterinitial setup,make sure the connectionsare secure,andthenplugthe ArduinoUnointoa
computerusinga USB cable and the ports locatedonbothdevices,(i.e.the computerandthe
controller). Furthermore,openupthe ArduinoIDEandprepare toconnectto the network.
Figure 5: Arduino Uno and WiFi Shield
Now,dependingonthe type of networksecurity,whetheritisWEPor WPA encrypted,the computer
program will vary. Forthe case of a WPA encryptednetwork,we willuse the code listedinAppendix A.
The elementsneededtoaccessthisnetworkinclude:
SSID (NetworkName)
Password
Once these twoelementsare addedtothe code inthe appropriate character,the WiFi101 shieldwill
displaythe networkconnectionstatusinthe serial monitor. Once itconnects,the serial monitorwill
display,“You’re connected to the network”as well asthe networkandWiFi data.
7 | P a g e
Arduino Server
Nowthat the Arduinohasbeensuccessfullyconnectedtothe network,we willconfigure the Arduinoto
act like a simple server. Todo this,we will firstsetupourcircuit ina way that itis able toprovide
meaningful data. Forthe purposesof thisproject,we will utilize aTMP36 temperature sensorin
conjunctionwiththe WiFi networktotransmitdatato a webpage (client).
Since the WiFi101 shieldisnearlyidentical inregardstothe controller pinout,the temperaturesensor
and RGB LED can be connectedintothe WiFi101shieldjustas isfor the ArduinoUno.
**Note:Do not use digital pins 7 and10 onthe shield!Thesepinsare reservedfor the shield-controller
connectioninterface.
Once thiscircuithas beenconnected,we willthenuse the code listedinAppendix A toconfigure the
Uno like a serverandthenupload datato the Internet. Furthermore,uponmakingthe proper
connectionswiththe rightcode,the Arduinoshouldbe able tocontrol the RGB LED from the same
website.
Results
Afterrunningthe code listedinAppendixA andtypinginthe networkSSIDand password.The following
screenwill appearwhenthe serial monitorisopened. Fig.8.showsthe processesthatthe Arduinois
running. Itbeginsbyattemptingtoconnectto the specifiednetworkandprintsthe resultof this
attemptedconnection. If noshieldispresentitwill display,“NoShield”;if connectionwasnot
establisheditwill display,“ConnectionFailed”;if itconnects thenitwill display,“Youare connected”.
Figure 6: TMP36 Sensor w/ RGB LED Circuit Figure 7: TMP36 Sensor Circuit Schematic
8 | P a g e
Figure 8: Arduino Serial Monitor Connection Status
Afterestablishingasecure connection,the Arduinowill printthe WiFi datausingthe
printWifiData()function. Furthermore,the currentnetworkwill be displayedaswell withthe
printCurrentNet()function. Withthat,we have successfullyconnectedtothe local WiFi network.
Once connectedtoa network,we modifiedthe code tothe one listedinAppendix A touploadsensor
data and control LEDs via the Internet. The IPaddressacquiredfromthe networkconnectionwill actas
the IP addressof our site.
Upon runningthe code listedinAppendix A,the serial monitordisplaysthe following. See Fig.9.
Figure 9: Arduino Serial Monitor Waiting for Client
9 | P a g e
Fig.9. shows the serial monitorandthe currentstate of the Arduino. Inthismoment,the Arduinois
waitingfora clienttosendthe data to. To openup a new client,we usedGoogle Chrome andtypedin
the IP addressfoundduringnetworkconnection.
Figure 10: Website URL (IP Address Form)
Figure 11: Arduino Server Local Network Website
The website showninFig.11. utilizesthe HTML code place in the ArduinoIDE(See Appendix B).
Furthermore,the microcontrollerreceivesdatafroma TMP36 temperature sensorand uploadsthe data
ontothissite usingsimple HTTPrequests. Inadditiontothe uploadeddata,the website was
constructedwithHTML formelementstocreate “ON”“OFF”buttonsthat can be usedtocontrol a RGB
LED that isconnectedtothe correspondingArduino. Inessence,the Arduinodoesthree things:it
connectsto a local networkviaWiFi,itservesupa webpage anddata whenthe clientispresentandit
performstaskswhenthe client,i.e.the webpage,requestsitwithstandardHTTPrequestssuchas GET.
10 | P a g e
Summary
Discussionand Analysis
How didwe connectthe ArduinoUno andWiFi101 shieldtothe Internet? Byusingthe code listedin
Appendix A withourtemperature sensorandLED network,were we able toaccomplishsuchatask.
Constructingthe circuitsrequiredlittle tonoeffortatall,the real challenge wasinunderstandinghow
clientsandserverscommunicate overthe Internetusingvariouscommunicationprotocols;furthermore,
usingthisknowledgetoprogramthe Arduinomicrocontrollersothatit would performthistask,i.e.
servingawebpage toa local IPaddress/webbasedclient,provedtobe the mostchallengingpartof this
project. See the code listedinAppendix A.
The firstheaderfile isthe serial peripheral interfaceheader #include <SPI.h> andis usedfor
connectingthe WiFi101shieldtothe Arduino. Followingthisheaderisthe WiFi101headerfile
#include <WiFi101.h>, whichenablesthe Arduinotoutilize the pre-installedlibraryfunctions
associatedwiththe WiFi101shield. Withouteitherof these twokeylinesof code,the wholeprogram
wouldfall apart.
The nextlinesof code are usedfor the purposesof storing ournetwork’sname andpasswordintotwo
separate characterarray variables, ssid[]forstoringthe network’sname and pass[]forstoringthe
password. These twovariableswill be calleduponlaterwhenconnectingtothe network.
The integervariable status is usedtoreturn the state of the networkconnection;inthislineof code
it hasbeeninitiallysettoidle. WiFiServerisusedtocreate a serverthatlistensforincoming
connectionsona specifiedport;the standardport beingport80 forEthernetand WiFi.
Nowthat the headerfilesandglobal variableshave been discussed,we beginwiththe void setup()
functionof our program. In thisfunction,we simply definedthe RGBconnectorpinsasoutputsand
startedthe serial monitorwiththe pinMode()andSerial.begin()functions. Furthermore,we
displayedthe networkstatusandconnectedtothe networkusingthe WiFi.begin()function. This
functiontooktwoarguments,i.e.the onesthatwe storedinour SSIDand passwordcharacterarrays.
We thenstartedthe serverandprintedthe WiFi statuswiththe printWiFiStatus()command,
whichisits ownfunctioncall.
The majorityof our computerprogram lieswithinthe nextfunction,i.e.the void loop()function.
Firstwe check if there are any clientstowhichthe servercan be made available withthe WiFiClient
and server.available()functions. If aclientisdetected,thenthe Arduinowill print“NEW
CLIENT” to the serial monitor. Furthermore,while the clientisconnected,the Arduinowill enterthe
while loopandrunthe program; if there isno clientconnected,the Arduinowill bypassthisloopand
move onto the nextrelevantpartof the program.
11 | P a g e
Once inside the while loop,the programwill checkwhetherthe clientisstill readilyavailable withthe
client.available()function. If the clientisavailable,we thendefineacharacter variable ‘c’to
holdthe value of client.read(). We thenuse the Serial.write()commandtodisplaythe
value of our character variable ‘c’inthe serial monitor. Thiswill allowustosee the requestbeingmade
by the clientinreal time viathe serial monitor.
The nextline of code isused to check if the Arduinoisfinishedwritingthe contentsof ourcharacter
variable ‘c’to the serial monitor. Once the Arduinoisfinishedprintingthe contentsof ‘c’, i.e.the
requestsof the client, itwill thencheckforablankline andproceedwith the followingcode. Upon
seeingthatthe clienthasfinishedmakingitsrequestor if (c == ‘n’),the Arduinowill senda
HTTP response headeranda HTML-formattedwebpage.
The HTTP response headerisanincrediblyimportantpartof the communication processasitdefines
the type of contentbeingsent. Afterreceivingthe initialrequest,made bythe client,the serverwill
senda 404 errorif the requestwasnotreceivedora 200 response indicatingthe requesthasbeen
successfullyreceived. Therefore,the firstlineof code usedinthe HTTP response headeris
client.println(“HTTP/1.1 200 OK”); followedby
client.println(“Content-Type:text/html”);
These twolinesof code tell the clientthatitsrequesthasbeenreceivedandthe response will be i nthe
formof an html textfile. Furthermore,the followinglinessimplyterminatethe connectionafter
transmission(i.e. client.println(“Connection: close”);) andrefreshthe html/text
documentbeingsenteveryfive seconds( i.e. client.println(“Refresh: 5”);). The HTTP
response headeristhenterminatedwiththe use of ablankline or client.println();.
FollowingthisHTTPheader,the Arduinoserverwill feedthe HTML textdocumenttothe clientbyusing
the client.println()command. Line byline the serverwill feedthe clientuntil the entire web
documenthasbeenserved. Once the serverprintsablankline,the connectionwillbe terminated.
At the endof the transmission,the break;functionisusedtoexitthe current loopandreturnto the
outside loop. A problemthatwasfacedingettingthisprogramto work wasthe issue of loadingthe new
URL afterhavingpressedabuttonsuch as RED LED OFFor GREEN LED ON. The problemwasthatthe
formelementusedinthe HTML textfile,createdasubmitbuttonthatwhenpressed,appendedthe GET
variable name andvalue tothe endof the pre-existingURL. Once the new contenthadbeenappended
to the oldURL, the servernolongerrecognizedthe client’srequestandthe page couldnotbe loaded.
To fix thisproblem,we usedastringvariable called currentLinetostore the oldURL withthe
appendedrequest whichallowedusto serve new responsesinregardstothat particularrequest. The
code utilizedseveral if statementswhich toggledthe operationalstate of the LEDs basedonthe type of
request.
For example, the original URLwas192.168.1.18 withoutanyappendedHTTPrequestsfromthe client.
However,whenthe REDLED “ON”buttonhad beenpressed,whichwascomprisedof the following
code:
12 | P a g e
//RedToggle ButtonHigh
client.println("<form action='' method='get'>");
client.println("<input type='hidden' name='L' value='6_H' />");
client.println("<input type='submit' value='ON' />");
client.println("</form>");
The newURL wouldprintout192.168.1.18/?L=6_H, whichwas unrecognizable bythe server. Initially,
our serverhadonlybeenprogrammedtoserve the followingclient,i.e.192.168.1.18. Afteraddingthe
followingcode,whichcanbe seentowardstoendof AppendixA,the programcorrecteditself.
if (currentLine.endsWith(“GET /?L=6_H”)) {
digitalWrite(6, HIGH);
}
To solve thisproblem,we simplyassignedeachclientHTTPrequestURL to a distinctArduinoserver
commandand programmedthe servertorecognize these appendedURLswiththe use of a string
variable. Afterthat,we terminatedthe client connectionwith the client.stop()commandto
avoidcontinuousloopingandprintedthe line “DISCONNECTED”tothe serial monitor.
Conclusion
We setout to connectour favorite microcontrollertothe Internetforthe purposesof uploadingdata
and controllinganetworkof LEDs. A lotwas learnedaboutcomputernetworking,communication
protocolsandthe Internetingeneral.
Afterconductingthisexperiment,we were abletoconnecta temperature sensornetworktoalocal web
basedclientbyutilizingserver-clientinteractionsaswell asHTTPand HTML. Furthermore,we were able
to connecta RGB LED to the networkthroughthe same techniques.
ConnectingArduinotothe Internetisafieldthat isfastgrowingand has huge potential forgrowthas
microcontrollersare becomingmore andmore ubiquitous andassocietycontinuouslyadvances.
References
https://www.arduino.cc/en/Reference/WiFiServer
https://www.arduino.cc/en/Tutorial/Wifi101ConnectWithWPA
https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi
https://en.wikipedia.org/wiki/Computer_network
https://en.wikipedia.org/wiki/OSI_model