Espressif Systems ESP8266 SDK User manual

ABeginner'sGuidetotheESP8266
PieterP, 08-03-2017
Sometimeago,IwroteaBeginner'sGuidetoArduinothatseemstobeverypopular,soIdecidedtocreateafollow-up:ABeginner's
GuidetotheESP8266.That'sright,atutorialonhowtousetheworld'smostpopular$3Wi-Fiboard.
Thisisgoingtobeaveryin-depthtutorial,coveringsomenetworkingconceptsaswell.Ifyou'reabeginner,andjustwanttogo
straighttothemoreexcitingWi-Fipart,feelfreetodoso,IincludedshortTL;DR'sinthelonger,moretechnicalparts.
AshortoverviewofwhatI'llcoverinthisarticle:
1. WhatisanESP8266?AshortoverviewofwhatanESP8266is,andwhatyoucandowithit
2. Decidingonwhatboardtobuy:There'sloadsofdifferentESP8266availablethesedays,findingtheonethat'sbestforyou
canbehard
3. Installingthesoftware:youneedtoinstallsomesoftwaretoprogramtheESP8266,andmaybeaUSBdriver
4. Settingupthehardware:somemodulesandboardsneedsomeexternalcomponents
5. TheESP8266asamicrocontroller:theESP8266canbeusedasanormalmicrocontroller,justlikeanArduino
6. Networkprotocols:BeforewestartusingtheWi-FicapabilitiesoftheESP8266,I'llteachyousomeofthenetworkprotocols
involved
7. SettingupaWi-Ficonnection:That'sprobablywhyyou'rereadingthis,right?
8. Nameresolution:FindtheESP8266onyourlocalnetworkusingmDNS
9. Settingupasimplewebserver:ThisenablesyoutoaddwebpagestotheESP8266,andbrowsethemfromyourcomputeror
phone
10. Settingupanadvancedwebserver:amoreadvancedserverwitharealfilesystemthatallowsyoutouploadnewfilesover
Wi-Fi
11. OTA-uploadingprogramsoverWi-Fi:Youdon'thavetouploadprogramsoverUSB,youcanuseWi-Fiinstead
12. WirelesslycontrollingyourRGBlighting:ChangethecolorofyourLEDstripsusingyourphoneorcomputer
13. Gettingthetime:ConnecttoatimeserverusingNTPandsynctheESP'sclock
14. Monitoringsensors:logthetemperatureinyourlivingroom,saveitinflashmemoryandshowitinafancygraphinyour
browser
15. Gettingemailnotifications:Turnonanotificationlightwhenyou'vegotunreademails
16. Advancedfeatures:useDNS,captiveportals,Wi-Ficonnectorlibraries,OSC...
ThisguideexpectssomebasicknowledgeofmicrocontrollersliketheArduino.Ifthat'ssomethingyou'renotalreadyfamiliarwith,I'd
recommendyoutoreadmyBeginner'sGuidetoArduinofirst,itcoversalotofthebasicsthatIwon'tgointointhisarticle.
IreallywanttofocusontheESP8266-specificthings,likeWi-Fiandothernetworkprotocols,theESP'shardware,software,IoT,etc...
WhatisanESP8266?
TheESP8266isaSystemonaChip(SoC),manufacturedbytheChinesecompanyEspressif.ItconsistsofaTensilicaL10632-bit
microcontrollerunit(MCU)andaWi-Fitransceiver.Ithas11GPIOpins*(GeneralPurposeInput/Outputpins),andananalog
inputaswell.ThismeansthatyoucanprogramitlikeanynormalArduinoorothermicrocontroller.Andontopofthat,yougetWi-Fi
communication,soyoucanuseittoconnecttoyourWi-Finetwork,connecttotheInternet,hostawebserverwithrealwebpages,let
yoursmartphoneconnecttoit,etc...Thepossibilitiesareendless!It'snowonderthatthischiphasbecomethemostpopularIOT
deviceavailable.
Therearemanydifferentmodulesavailable,standalonemodulesliketheESP-##seriesbyAIThinker,orcompletedevelopment
boardsliketheNodeMCUDevKitortheWeMosD1.Differentboardsmayhavedifferentpinsbrokenout,havedifferentWi-Fiantennas,
oradifferentamountofflashmemoryonboard.
(*)TheESP8266chipitselfhas17GPIOpins,but6ofthesepins(6-11)areusedforcommunicationwiththeon-boardflashmemorychip.
Programming
TherearedifferentwaystoprogramtheESP8266,butI'llonlycoverthemethodusingtheArduinoIDE.Thisisreallyeasyfor
beginners,andit'saveryfamiliarenvironmentifyou'veusedArduinoboardsbefore.
Justkeepinmindthatit'snotlimitedtothisoption:there'salsoanofficialSDKavailabletoprogramitinrealC,thisisveryusefulif
youwanttooptimizeyourcodeordosomeadvancedtricksthataren'tsupportedbytheArduinoIDE.Anotherpossibilityistoflashit
withaLUAinterpreter,soyoucanuploadandrunLUAscripts.Ormaybeyou'remorefamiliarwithPython?Thenyoushouldcheckout
theMicroPythonfirmwaretointerpretMicroPythonscripts.I'msurethere'sotherlanguagesavailableaswell,sojustdoaquickGoogle
searchandwriteyourcodeinthelanguageofyourchoice.
Requirements
You'llneedacoupleofthingsinordertofollowthisguide:
AnESP8266board
AcomputerthatcanruntheArduinoIDE(Windows,MacorLinux)
AUSB-to-Serialconverter,itisveryimportantthatyouusea3.3Vmodel*
AUSBcable
A3.3Vpowersupplyorvoltageregulator*
AWi-Finetworktoconnectto
(*)Yourboardmayalreadyincludethese.Moreinformationcanbefoundinthenextchapter.

Hardware
Decidingonwhatboardtobuy
ESP8266isjustthenameofthechip,manycompanieshavedesignedtheirownboardsthatusethischip,sotherearemanydifferent
ESP8266boardsonthemarket.Ifyoudon'tknowthedifferencebetweenallthesedifferentmodels,youmighthaveahardtime
decidingonwhatboardtobuy.
Theeasiest(andfastest)waytogetanESP8266boardistobuyonefromawell-knownelectronicsshoplikeAdafruitorSparkFun,but
ifyouwantitcheap,youshouldcheckoutEbayorothersiteswhereyoucanorderthemdirectlyfromChina.
Developmentboards
Someboardshaveallkindsoffeatureson-boardtohelpdevelopingESP8266hardwareandsoftware:forexample,aUSBtoSerial
converterforprogramming,a3.3Vregulatorforpower,on-boardLEDsfordebugging,avoltagedividertoscaletheanaloginput...
Ifyou'reabeginner,Iwoulddefinitelyrecommendadevelopmentboard.It'seasiertogetstartedifyoudon'thavetoworryaboutall
thesethings.
Bare-bonesAIThinkerboards
IfyouwanttoaddanESP8266toasmallproject,orifyouwantacheaper*board,youmightwanttobuyaboardthatdoesn'thave
thesefeatures.Inthatcase,youcanbuyoneofthemanyESP-##modulesdevelopedbyAIThinker.TheycontainjusttheESP8266
andthenecessarycomponentstorunit.
Toprogramtheboard,you'llneedanexternalUSB-to-Serialconverter.
Withsomemodules,yougetanon-boardantenna(PCBorceramic)andanLED,someboardshavejustanantennaconnector,orno
LEDsatall.Theyalsodifferinphysicalsize,andflashmemorysize.Animportantthingtonotice,isthatsomeboardsdonotbreak
outallGPIOpins.Forexample,theESP-01onlyhas2I/Opinsavailable(apartfromtheTXandRXpins),whileothermoduleslikethe
ESP-07orESP-12breakoutallavailableI/Opins.
(*)Theboarditselfischeaper,butyou'llhavetospendmoreonexternalparts.
Overview
Here'satablewithsomeofthemostpopularESP8266developmentboardsandtheirfeatures:
Board GPIO 3.3V
Vreg
USB-to-
Serial
Auto-
Reset
Auto-
Program Flash ADC
range Extra
SparkFunESP8266Thing 11 + - + ±* 512KB(4Mb) 0-1V Batterycharger,cryptoelement,
temperaturesensor,lightsensor
SparkFunESP8266Thing
-DevBoard 11 + + + + 512KB(4Mb) 0-1V
NodeMCU 11 + + + + 4MB(32Mb) 0-3.3V
AdafruitFeatherHUZZAH
withESP8266 11 + + + + 4MB(32Mb) 0-1V Batterycharger
AdafruitHUZZAH
ESP8266Breakout 11 + - - - 4MB(32Mb) 0-1V 5V-tolerantRXandResetpins
ESP-## 4-
11 - - - - 512KB(4Mb)–
4MB(32Mb) 0-1V Smallandcheap
YoucanfindthefulllistofESP-##moduleshere.
Asyoucansee,boththeNodeMCUandtheAdafruitFeatherHUZZAHaresolidchoices.
(*)Whenauto-programontheSparkFunESP8266Thingisenabled,youcan'tusetheSerialMonitor.
Gettingthehardwareready
TherearetwomaincategoriesofESP8266boards:developmentboardswithaUSBinterface(USB-to-Serialconvertor)on-board,and
boardswithoutaUSBconnection.
DevelopmentboardswithaUSBinterface
Forexample:NodeMCU,SparkFunESP8266Thing-DevBoard,SparkFunBlynkBoard,AdafruitFeatherHUZZAHwithESP8266Wi-Fi...
TheseboardswillshowupinDevicemanager(Windows)orinlsusb(Linux)assoonasyouplugthemin.
Theyhavea3.3Vregulatoron-board,andcanbeprogrammedoverUSBdirectly,soyoudon'tneedanyexternalcomponentstogetit
working.
Theonlythingyoumayneedtodo,issolderonsomeheaders.
Bare-bonesboardsandboardswithoutaUSBinterface
Thiscategoryhas2sub-categories:boardswitha3.3Vregulatoron-board,andboardswithjusttheESP8266andaflashmemory
chip,without3.3Vregulator.Ifyourboarddoesn'thavea5Vto3.3Vregulator,buyoneseparately.YoucoulduseanLM1117-3.3for
example.Theon-board3.3VregulatorofmostArduinoboardsisnotpowerfulenoughtopowertheESP.
Toprogramtheboard,you'llneedaUSB-to-Serialconverter.TheFTDIFT232RLisquitepopular,becauseitcanswitchbetween5Vand
3.3V.ItisessentialthattheUSB-to-Serialconverteryoubuyoperatesat3.3V.Ifyoubuya5Vmodel,youwilldamage
theESP8266.
ConnectingtheUSB-to-Serialconverter

1. Connecttheground(GND)oftheUSB-to-SerialconvertertothegroundoftheESP8266.
2. ConnecttheRX-pinoftheUSB-to-SerialconvertertotheTXDpinoftheESP8266.(Onsomeboards,it'slabelledTXinsteadof
TXD,butit'sthesamepin.)
3. ConnecttheTX-pinoftheUSB-to-SerialconvertertotheRXDpinoftheESP8266.(Onsomeboards,it'slabelledRXinsteadof
RXD,butit'sthesamepin.)
4. IfyourESP8266boardhasaDTRpin,connectittotheDTRpinoftheUSB-to-Serialconverter.Thisenablesauto-resetwhen
uploadingasketch,moreonthatlater.
Enablingthechip
Ifyou'reusingabare-boneESP-##boardbyAIThinker,youhavetoaddsomeresistorstoturnontheESP8266,andtoselecttheright
bootmode.
1. EnablethechipbyconnectingtheCH_PD(ChipPowerDown,sometimeslabeledCH_ENorchipenable)pintoVCCthrougha10KΩ
resistor.
2. DisableSD-cardbootbyconnectingGPIO15togroundthrougha10KΩresistor.
3. SelectnormalbootmodebyconnectingGPIO0toVCCthrougha10KΩresistor.
4. PreventrandomresetsbyconnectingtheRST(reset)pintoVCCthrougha10KΩresistor.
5. Makesureyoudon'thaveanythingconnectedtoGPIO2(moreinformationinthenextchapter).
Addingresetandprogrambuttons
IfyourESP8266boarddoesn'thavearesetbutton,youcouldaddonebyconnectingapushbuttontobetweentheRSTpinand
ground.
Toputthechipintoprogrammingmode,youhavetopullGPIO0lowduringstartup.That'swhywealsoneedaprogrambutton.
Becauseit'spossibletouseGPIO0asanoutput,wecan'tdirectlyshortittoground,thatcoulddamagethechip.Topreventthis,
connect470Ωresistorinserieswiththeswitch.It'simportantthatthisresistanceislowenough,otherwise,itwillbepulledhighbythe
10KΩresistorweaddedinthepreviousparagraph.
Connectingthepowersupply
IftheESP8266moduleyouhavedoesn'thavea3.3Vvoltageregulatoronboard,youhavetoaddoneexternally.Youcouldusean
LM1117-3.3forexample.
1. Connectthefirstpinoftheregulatortoground.
2. Placea10µFcapacitorbetweenpin2(Vout)andground.Watchthepolarity!
3. Placea10µFcapacitorbetweenpin3(Vin)andground.
4. Connectpin2tothe3.3VorVCCoftheESP8266.
5. Connectpin3toa5Vpowersource,aUSBport,forexample.


Beforeyoubegin...
There'safewthingsyouhavetolookoutforwhenusinganESP8266:Themostimportantthingisthatitrunsat3.3V,soifyou
connectittoa5Vpowersupply,you'llkillit.Unlikesome3.3VArduinoorTeensyboards,theESP8266'sI/Opinsarenot5V
tolerant,soifyouusea5VUSB-to-Serialconverter,or5Vsensorsetc.you'llblowitup.
AsecondthingtokeepinmindisthattheESP8266canonlysourceorsink12mAperoutputpin,comparedto20-40mAformost
Arduinos.
TheESP8266hasoneanalogtodigitalconverter,butithasastrangevoltagerange:0-1V,voltagesabove1Vmightdamagethe
board.
OnelastthingtokeepinmindisthattheESP8266hastosharethesystemresourcesandCPUtimebetweenyoursketchandtheWi-Fi
driver.Also,featureslikePWM,interruptsorI²Careemulatedinsoftware,mostArduinosontheotherhand,havededicatedhardware
partsforthesetasks.
Formostapplicationshowever,thisisnottoomuchofanissue.

Software
Installationoftherequiredsoftware
ThefirststepistodownloadandinstalltheArduinoIDE.IexplainedthisinABeginner'sGuidetoArduino.(AsofFebruary7th2017,
thelateststableversionoftheIDEis1.8.1.)
ToprogramtheESP8266,you'llneedapluginfortheArduinoIDE,itcanbedownloadedfromGitHubmanually,butitiseasiertojust
addtheURLintheArduinoIDE:
1. OpentheArduinoIDE.
2. GotoFile>Preferences.
3. PastetheURLhttp://arduino.esp8266.com/stable/package_esp8266com_index.jsonintotheAdditionalBoardManagerURLsfield.
(YoucanaddmultipleURLs,separatingthemwithcommas.)
4. GotoTools>Board>BoardManagerandsearchfor'esp8266'.Selectthenewestversion,andclickinstall.(AsofFebruary7th
2017,thelateststableversionis2.3.0.)
Youcancheckouttheofficialinstallguidehere.
Drivers
IfyouareusingaboardwiththeCH340(G)USB-to-Serialchip,liketheNodeMCU,you'llprobablyhavetoinstalltheUSBdriversforit.
TheycanbefoundonGitHub.
IfyouareusingaboardwiththeCP2104USB-to-Serialchip,liketheAdafruitFeatherHUZZAHboard,you'llprobablyhavetoinstall
USBdriversaswell.YoucanfindthemontheSiliconLabswebsite.
BoardswithanFTDIchipshouldworkrightoutofthebox,withouttheneedofinstallinganydrivers.
Python
IfyouwanttouseOverTheAirupdatesonWindows,youhavetoinstallPython2.7.Youcandownloaditfrompython.org.Duringthe
installation,youhavetoselecttheoptiontoaddPythontoyourpath.Ifyoudon'tdothis,theArduinoIDEwon'tbeabletofindthe
Pythonexecutable.
Examples
YoucanfindallexamplesusedinthisarticleonmyGitHub.Justdownloaditasa.ZIPfile,unzipittoaconvenientlocation,andyou're
goodtogo!

TheESP8266asamicrocontroller-Hardware
WhiletheESP8266isoftenusedasa‘dumb’Serial-to-WiFibridge,it’saverypowerfulmicrocontrolleronitsown.Inthischapter,we’ll
lookatthenon-Wi-FispecificfunctionsoftheESP8266.
DigitalI/O
JustlikeanormalArduino,theESP8266hasdigitalinput/outputpins(I/OorGPIO,GeneralPurposeInput/Outputpins).Asthename
implies,theycanbeusedasdigitalinputstoreadadigitalvoltage,orasdigitaloutputstooutputeither0V(sinkcurrent)or3.3V
(sourcecurrent).
Voltageandcurrentrestrictions
TheESP8266isa3.3Vmicrocontroller,soitsI/Ooperatesat3.3Vaswell.Thepinsarenot5Vtolerant,applyingmorethan3.6V
onanypinwillkillthechip.
ThemaximumcurrentthatcanbedrawnfromasingleGPIOpinis12mA.
Usablepins
TheESP8266has17GPIOpins(0-16),however,youcanonlyuse11ofthem,because6pins(GPIO6-11)areusedtoconnectthe
flashmemorychip.Thisisthesmall8-leggedchiprightnexttotheESP8266.Ifyoutrytouseoneofthesepins,youmightcrashyour
program.
GPIO1and3areusedasTXandRXofthehardwareSerialport(UART),soinmostcases,youcan’tusethemasnormalI/Owhile
sending/receivingserialdata.
Bootmodes
Asmentionedinthepreviouschapter,someI/Opinshaveaspecialfunctionduringboot:Theyselect1of3bootmodes:
GPIO15 GPIO0 GPIO2 Mode
0V 0V 3.3V UartBootloader
0V 3.3V 3.3V Bootsketch(SPIflash)
3.3V x x SDIOmode(notusedforArduino)
Note:youdon’thavetoaddanexternalpull-upresistortoGPIO2,theinternaloneisenabledatboot.
Wemadesurethattheseconditionsaremetbyaddingexternalresistorsinthepreviouschapter,ortheboardmanufacturerofyour
boardaddedthemforyou.Thishassomeimplications,however:
GPIO15isalwayspulledlow,soyoucan’tusetheinternalpull-upresistor.YouhavetokeepthisinmindwhenusingGPIO15asan
inputtoreadaswitchorconnectittoadevicewithanopen-collector(oropen-drain)output,likeI²C.
GPIO0ispulledhighduringnormaloperation,soyoucan’tuseitasaHi-Zinput.
GPIO2can’tbelowatboot,soyoucan’tconnectaswitchtoit.
Internalpull-up/-downresistors
GPIO0-15allhaveabuilt-inpull-upresistor,justlikeinanArduino.GPIO16hasabuilt-inpull-downresistor.
PWM
UnlikemostAtmelchips(Arduino),theESP8266doesn’tsupporthardwarePWM,however,softwarePWMissupportedonalldigital
pins.ThedefaultPWMrangeis10-bits@1kHz,butthiscanbechanged(upto>14-bit@1kHz).
Analoginput
TheESP8266hasasingleanaloginput,withaninputrangeof0-1.0V.Ifyousupply3.3V,forexample,youwilldamagethechip.
SomeboardsliketheNodeMCUhaveanon-boardresistivevoltagedivider,togetaneasier0-3.3Vrange.Youcouldalsojustusea
trimpotasavoltagedivider.
TheADC(analogtodigitalconverter)hasaresolutionof10bits.
Communication
Serial
TheESP8266hastwohardwareUARTS(Serialports):
UART0onpins1and3(TX0andRX0resp.),andUART1onpins2and8(TX1andRX1resp.),however,GPIO8isusedtoconnectthe
flashchip.ThismeansthatUART1canonlytransmitdata.
UART0alsohashardwareflowcontrolonpins15and13(RTS0andCTS0resp.).ThesetwopinscanalsobeusedasalternativeTX0
andRX0pins.
I²C
TheESPdoesn’thaveahardwareTWI(TwoWireInterface),butitisimplementedinsoftware.Thismeansthatyoucanusepretty
muchanytwodigitalpins.Bydefault,theI²Clibraryusespin4asSDAandpin5asSCL.(ThedatasheetspecifiesGPIO2asSDAand
GPIO14asSCL.)Themaximumspeedisapproximately450kHz.
SPI

TheESP8266hasoneSPIconnectionavailabletotheuser,referredtoasHSPI.ItusesGPIO14asCLK,12asMISO,13asMOSIand15
asSlaveSelect(SS).ItcanbeusedinbothSlaveandMastermode(insoftware).
GPIOoverview
GPIO Function State Restrictions
0 Bootmodeselect 3.3V NoHi-Z
1 TX0 - NotusableduringSerialtransmission
2Bootmodeselect
TX1 3.3V(bootonly) Don’tconnecttogroundatboottime
Sendsdebugdataatboottime
3 RX0 - NotusableduringSerialtransmission
4 SDA(I²C) - -
5 SCL(I²C) - -
6-11 Flashconnection x Notusable,andnotbrokenout
12 MISO(SPI) - -
13 MOSI(SPI) - -
14 SCK(SPI) - -
15 SS(SPI) 0V Pull-upresistornotusable
16 Wakeupfromsleep - Nopull-upresistor,butpull-downinstead
ShouldbeconnectedtoRSTtowakeup
TheESP8266asamicrocontroller-Software
MostofthemicrocontrollerfunctionalityoftheESPusesexactlythesamesyntaxasanormalArduino,makingitreallyeasytoget
started.
DigitalI/O
JustlikewitharegularArduino,youcansetthefunctionofapinusingpinMode(pin,mode);wherepinistheGPIOnumber*,andmodecan
beeitherINPUT,whichisthedefault,OUTPUT,orINPUT_PULLUPtoenablethebuilt-inpull-upresistorsforGPIO0-15.Toenablethepull-
downresistorforGPIO16,youhavetouseINPUT_PULLDOWN_16.
(*)NodeMCUusesadifferentpinmapping,readmorehere.ToaddressaNodeMCUpin,e.g.pin5,useD5:forinstance:pinMode(D5,
OUTPUT);
Tosetanoutputpinhigh(3.3V)orlow(0V),usedigitalWrite(pin,value);wherepinisthedigitalpin,andvalueeither1or0(orHIGH
andLOW).
Toreadaninput,usedigitalRead(pin);
ToenablePWMonacertainpin,useanalogWrite(pin,value);wherepinisthedigitalpin,andvalueanumberbetween0and1023.
Youcanchangetherange(bitdepth)ofthePWMoutputbyusinganalogWriteRange(new_range);
ThefrequencycanbechangedbyusinganalogWriteFreq(new_frequency);.new_frequencyshouldbebetween100and1000Hz.
Analoginput
JustlikeonanArduino,youcanuseanalogRead(A0)togettheanalogvoltageontheanaloginput.(0=0V,1023=1.0V).
TheESPcanalsousetheADCtomeasurethesupplyvoltage(VCC).Todothis,includeADC_MODE(ADC_VCC);atthetopofyoursketch,and
useESP.getVcc();toactuallygetthevoltage.
Ifyouuseittoreadthesupplyvoltage,youcan’tconnectanythingelsetotheanalogpin.
Communication
Serialcommunication
TouseUART0(TX=GPIO1,RX=GPIO3),youcanusetheSerialobject,justlikeonanArduino:Serial.begin(baud).
Tousethealternativepins(TX=GPIO15,RX=GPIO13),useSerial.swap()afterSerial.begin.
TouseUART1(TX=GPIO2),usetheSerial1object.
AllArduinoStreamfunctions,likeread,write,print,println,...aresupportedaswell.
I²CandSPI
YoucanjustusethedefaultArduinolibrarysyntax,likeyounormallywould.
SharingCPUtimewiththeRFpart
OnethingtokeepinmindwhilewritingprogramsfortheESP8266isthatyoursketchhastoshareresources(CPUtimeandmemory)
withtheWi-Fi-andTCP-stacks(thesoftwarethatrunsinthebackgroundandhandlesallWi-FiandIPconnections).
Ifyourcodetakestoolongtoexecute,anddon’tlettheTCPstacksdotheirthing,itmightcrash,oryoucouldlosedata.It’sbestto
keeptheexecutiontimeofyouloopunderacoupleofhundredsofmilliseconds.
Everytimethemainloopisrepeated,yoursketchyieldstotheWi-FiandTCPtohandleallWi-FiandTCPrequests.
Ifyourlooptakeslongerthanthis,youwillhavetoexplicitlygiveCPUtimetotheWi-Fi/TCPstacks,byusingincludingdelay(0);or
yield();.Ifyoudon’t,networkcommunicationwon’tworkasexpected,andifit’slongerthan3seconds,thesoftWDT(WatchDog
Timer)willresettheESP.IfthesoftWDTisdisabled,afteralittleover8seconds,thehardwareWDTwillresetthechip.

Fromamicrocontroller’sperspectivehowever,3secondsisaverylongtime(240millionclockcycles),sounlessyoudosome
extremelyheavynumbercrunching,orsendingextremelylongstringsoverSerial,youwon’tbeaffectedbythis.Justkeepinmind
thatyouaddtheyield();insideyourfororwhileloopsthatcouldtakelongerthan,say100ms.
Sources
ThisiswhereIgotmostofmyinformationtowritthisarticle,there’ssomemoredetailsontheGitHubpages,ifyou’reintosomemore
advancedstuff,likeEEPROMordeepsleepetc.
https://github.com/esp8266/Arduino/issues/2942
https://github.com/esp8266/Arduino/pull/2533/files
https://github.com/esp8266/Arduino/blob/master/doc/libraries.md
https://github.com/esp8266/Arduino/blob/master/doc/reference.md
https://github.com/esp8266/Arduino/blob/master/doc/boards.md

Wi-Fi
UsingtheESP8266asasimplemicrocontrollerisgreat,butthereasonwhymostpeopleuseit,isitsWi-Ficapabilities.Inthischapter,
we'lldiveintothewonderfulworldofnetworkprotocols,likeWi-Fi,TCP,UDP,HTTP,DNS...Alltheseacronymsmightintimidateyou,
butI'lltrymybesttoexplainthemstep-by-stepandinaneasyway.
Someparagraphsareinitalic.Theseprovidesomeextrainformation,butarenotcriticaltounderstandingtheESP'sWi-Fifunctions,so
don'tgetfrustratediftherearethingsyoudon'tunderstand.
It'sreallyhardtogiveaclearexplanation,withoutover-complicatingthingsandwhilekeepingitshortenoughaswell.Ifyou'vegot
anyfeedbackorremarks,besuretoleaveacommenttohelpimprovethisarticle.Thanks!
TheTCP/IPstack
Thesystemmostpeoplerefertoas'TheInternet'isn'tjustoneprotocol:it'sanentirestackoflayersofprotocols,oftenreferredtoas
theTCP/IPstack.We'llgooverthesedifferentlayers,becauseweneedtounderstandhowourESP8266communicateswithother
devicesonthenetwork.
Layer Protocols
Application HTTP,FTP,mDNS,WebSocket,OSC...
Transport TCP,UDP
Internet IP
Link Ethernet,Wi-Fi...
TheLinklayer
Thelinklayercontainsthephysicallinkbetweentwodevices,anEthernetcable,forexample,oraWi-Ficonnection.Thisisthelayer
thatisclosesttothehardware.
ToconnectanESP8266tothenetwork,youhavetocreateaWi-Filink.Thiscanhappenintwodifferentways:
1. TheESP8266connectstoawirelessaccesspoint(WAPorsimplyAP).TheAPcanbebuilt-intoyourmodemorrouter,for
example.
Inthisconfiguration,theESPactslikeawirelessstation.
2. TheESP8266actsasanaccesspointandwirelessstationscanconnecttoit.Thesestationscouldbeyourlaptop,a
smartphone,orevenanotherESPinstationmode.
OncetheWi-Filinkisestablished,theESP8266ispartofalocalareanetwork(LAN).AlldevicesonaLANcancommunicatewith
eachother.
Mostofthetime,theAPisconnectedtoaphysicalEthernetnetworkaswell,thismeansthattheESP8266canalsocommunicatewith
devicesthatareconnectedtotheAP(modem/router)viaawiredEthernetconnection(desktopcomputers,gamingconsolesandset-
topboxes,forinstance).
IftheESP8266isinaccesspointmode,itcancommunicatewithanystationthatisconnectedtoit,andtwostations(e.g.alaptopand
asmartphone)canalsocommunicatewitheachother.
TheESPcanbeusedinAP-only,station-only,orAP+stationmode.
TL;DR
Thelinklayeristhephysicallinkbetweendevices:inthecaseoftheESP8266,thisisaWiFiconnection.TheESPcanactasastation
andconnecttoanaccesspoint,oractasanaccesspointandletotherdevicesconnecttoit.
TheInternetorNetworklayer
Althoughthedevicesarenowphysicallyconnected(eitherthroughactualwires(Ethernet)orthroughradiowaves(Wi-Fi)),theycan't
actuallytalktoeachotheryet,becausetheyhavenowayofknowingwheretosendthemessageto.
That'swheretheInternetProtocol(IP)comesin.EverydeviceonthenetworkhasapersonalIPaddress.TheDHCPserver(Dynamic
HostConfigurationProtocolServer)makessurethattheseaddressesareunique.
Thismeansthatyoucannowsendamessagetoaspecificaddress.
TherearetwoversionsoftheInternetProtocol:IPv4andIPv6.IPv6isanimprovedversionofIPv4andhasmuchmoreaddressesthan
IPv4(becausetherearemuchmoredevicesthanavailableIPv4addresses).Inthisarticle,we'llonlytalkaboutIPv4addresses,since
mostLANsstillusethem.
TheIPaddressconsistsof4numbers,forexample192.168.1.5isavalidIPv4address.Itactuallyconsistsoftwoparts:thefirstpartis
192.168.1,thisistheaddressofthelocalnetwork.Thelastdigit,5inthiscase,isspecifictothedevice.
ByusingIPaddresses,wecanfindtheESP8266onthenetwork,andsendmessagestoit.TheESPcanalsofindourcomputerorour
phone,ifitknowstheirrespectiveIPaddresses.
Sub-netmask(optional)
ThissubdivisionoftheIPaddressisdeterminedbythesub-netmask,oftenwrittenas255.255.255.0.Youcanseethatitconsistsof
fournumbers,justliketheIPaddress.Ifapartofthesub-netmaskis255,itmeansthatthecorrespondingpartoftheIPaddressis
partofthenetworkaddress,ifit's0,thecorrespondingIPpartispartoftheaddressofthespecificaddress.Adifferentnotationto"IP:
192.168.1.5,sub-netmask:255.255.255.0"wouldbe"192.168.1.5/24",becausethebinaryrepresentationofthesub-netmaskis
11111111.11111111.11111111.00000000,andithas24ones.
Ifyouwanttoknowmoreaboutsub-nets,I'drecommendyoutoreadtheWikipediaarticle.
(Aquicktiptohelpyouremember:it'scalledthesub-netmask,becauseifyouperformabitwiseANDoperationontheIPaddressand
thesub-netmask(i.e.usethesub-netmaskasamaskfortheIPaddress),yougettheaddressofthesub-net.)

MACaddressesandARP(optional)
ItisactuallyimpossibletosendpacketsdirectlytoanothermachineusingonlytheIPaddress.Tosendapackettoaspecificdeviceon
theLAN(Wi-FiorEthernet),youhavetoknowitsMAC-address.TheMACaddressisauniquenumberthatisuniqueforeverynetwork
device,anditneverchanges,it'shardwiredinthenetworkchip.ThismeansthateveryESP8266,everynetworkcard,every
smartphone...evermade,hasadifferentMACaddress.
SobeforetheESPcansendapackettoyoursmartphoneforexample,ithastoknowitsMACaddress.Itdoesn'tknowthisyet,theESP
onlyknowstheIPaddressofthesmartphone,say192.168.1.6.Todothis,theESPsendsabroadcastmessage(i.e.amessage
addressedtoalldevicesontheLAN)saying"I'mlookingfortheMACaddressofthedevicewiththeIPaddress192.168.1.6".TheESP
alsoincludesitsownIPandMACaddresswiththemessage.Whenthesmartphonereceivesthisbroadcastmessage,itrecognizesits
ownIPaddress,andrespondstotheESPbysendingitsownMACaddress.NowtheESPandthephonebothknoweachother'sIPand
MACaddresses,andtheycancommunicateusingIPaddresses.ThismethodiscalledtheAddresResolutionProtocol,orARP.
WhatabouttheInternet?
Asyoumighthavenoticed,Ionlytalkedaboutthelocalareanetwork,thesearethecomputersinyourownhouse.Sohowcanthe
ESP8266communicatewiththeInternet,youmayask?Well,there'salotofnetworkinfrastructureinvolvedin'TheInternet',andthey
allobeytheIPrules,tomakesuremostofyourpacketsarriveattheredestination.It'snotthatsimpleofcourse,there'salotofthings
goingon,likeroutingandNetworkAddressTranslation(NAT),butthatfallsoutsidethescopeofthisarticle,andit'snotreally
somethingmostpeoplehavetoworryabout.
TL;DR
TheInternetlayerusesIPaddressesinordertoknowwhereitshouldsendthedata.Thismeansthattwodevicescannowsend
packetsofdatatoeachother,evenovertheInternet.
TheTransportlayer
ThedifferentdevicesinthenetworkdotheirbesttodelivertheseIPpacketstotheaddressee,however,it'snotuncommonfora
packettogetlost,soitwillneverarrive.Orthepacketmightgetcorruptedontheway:thedataisnolongercorrect.IPalsocan't
guaranteethatthepacketsarriveinthesameordertheyweresentin.
Thismeansthatwecan'treliablysendmessagesyetbyonlyusingthelinkandtheInternetlayer,sincewecanneverknowwhenand
whetherapacketwillarrive,orknowforcertainthatareceivedpacketiscorrect.
WeneedathirdlayerontopoftheInternetlayer:theTransportlayer.
Therearemainlytwoprotocolsthatmakeupthisthirdlayer:theTransmissionControlProtocol(TCP)andtheUserDatagramProtocol
(UDP).
TCPmakessurethatallpacketsarereceived,thatthepacketsareinorder,andthatcorruptedpacketsarere-sent.Thismeans
thatitcanbeusedforcommunicationbetweenmultipleapplications,withouthavingtoworryaboutdataintegrityorpacket
loss.Thisiswhyit'susedforthingslikedownloadingwebpages,sendingemail,uploadingfilesetc.
UDPontheotherhand,doesn'tguaranteethateverypacketreachesitsdestination,itdoescheckforerrorshowever,but
whenitfindsone,itjustdestroysthepacket,withoutre-sendingit.Thismeansthatit'snotasreliableasTCP,butit'sfaster,
andhasamuchlowerlatency,becauseitdoesn'trequireanopenconnectiontosendmessages,likeTCPdoes.That'swhyit's
usedinvoiceandvideochats,andforexampleinonlinegames.
IfyouwanttoknowmoreaboutthedifferencesbetweenTCPandUDP,checkoutthisvideo.
TL;DR
TheIPprotocolisnotreliable,andhasnoerrorchecking.TCPsolvesthisbyre-sendinglostorcorruptpackages,andorderspackets
thatarereceivedinthewrongorder.UDPalsochecksforcorruptpackages,butdoesn'tre-sendthem,soithaslesslatencythanTCP.
TheApplicationlayer
WenowhavereliablecommunicationusingTCP,butthere'sstilloneproblem.Thinkofitthisway:youaresendingaletter,andTCP
guaranteesthatitwillarriveatitsdestination,butifthereceiverdoesn'tunderstandthelanguageit'swrittenin,hewon'tknowwhat
todowithit.
Inotherwords,weneedafourthlayerofprotocols,fortwoprogramstobeabletocommunicatewitheachother.
There'slotsofdifferentprotocolsoutthere,butwe'llmostlyfocusontheprotocolsforwebserversandbrowsers.
HyperTextTransferProtocol
TheHyperTextTransferProtocol,orHTTP,istheprotocol(cfr.language)thatisusedbybothwebserversandwebclientsinorderto
communicate.Itusestexttoperformsendrequestsandresponsesfromtheclienttotheserverandbackagain.
Forexample,whenyoutypehttp://www.google.comintotheaddressbarofawebbrowser(client),itwillsendanHTTPGETrequestto
theGooglewebserver.TheserverunderstandsthisHTTPrequest,andwillsendtheGooglewebpageasaresponse.Orwhenyou
uploadanimagetoInstagram,yourbrowsersendsanHTTPPOSTrequestwithyourselfieattachedtotheInstagramserver.The
serverunderstandstherequest,savestheimageandaddsitintothedatabase,sendstheURLofthenewimagebacktoyourbrowser,
andthebrowserwilladdtheimageonthewebpage.
Asyoucansee,neithertheclientnortheserverhastoworryabouttheintegrityofthemessagestheysend,andtheyknowthatthe
recipientunderstandstheirlanguage,andthatitwillknowwhattodowithacertainHTTPrequest.
MostmodernsitesuseasecureversionofHTTP,calledHTTPS.Thissecureconnectionencryptsthedata,forsecurityreasons.(You
don'twantanyonereadingthepacketsfromyourmailserver,orthepacketsyousenttoyourbank,forinstance.)
WebSocket
HTTPisgreatforthingslikedownloadingwebpages,uploadingphotosetc.butit'squiteslow:everytimeyousendanHTTPrequest,
youhavetostartanewTCPconnectiontotheserver,thensendyourrequest,waitfortheservertorespond,anddownloadthe
response.Wouldn'titbegreatifwedidn'thavetoopenanewconnectioneverytimewewanttosendsomedata,andifwecould
sendandreceivedataatthesametimeatanymomentwe'dlike?That'swhereWebSocketcomestotherescue:youcankeeptheTCP
connectionwiththeserveropenatalltimes,yougetperfectTCPreliability,andit'sprettyfast.
OpenSoundControl

HTTPandWebSocketbothuseTCPconnections.Whatifyouwantlowerlatency?Well,OpenSoundControl,orOSC,usesUDPtosend
smallpiecesofdata,likeints,floats,shorttextetc...withverylowlatency.Itwasoriginallydesignedforcontrollinglowlatencyaudio
applications,butit'saveryflexibleprotocol,soit'softenusedforlow-latencytasksotherthanaudiocontrol.
DomainNameSystem
Asmentionedbefore,youcanonlysendamessagetoanothercomputerifyouknowitsIPaddress.ButwhenyoubrowsetheInternet,
youonlyknowawebsite'sdomainname(e.g.www.google.com).YourcomputerusestheDomainNameSystemtotranslatethis
domainnametotherightIPaddress.Moreonthislater.
Sources
https://en.wikipedia.org/wiki/Internet_protocol_suite
https://en.wikipedia.org/wiki/Port_(computer_networking)
https://en.wikipedia.org/wiki/Transmission_Control_Protocol
https://en.wikipedia.org/wiki/Internet_Protocol
https://en.wikipedia.org/wiki/User_Datagram_Protocol

UploadingsketchestotheESP8266
TheuploadprocedureforESP8266boardsisalittledifferentfromthenormalArduinoprocedure.MostArduinoswillautomatically
resetwhenanewprogramisbeinguploaded,andwillautomaticallyenterprogrammingmode.
OnsomeESPboardsyouhavetomanuallyenterprogrammingmode,andonthebare-bonesmodules,youevenhavetoresetthem
manually.
However,therearesomesimplecircuitsyoucanusetogetautomaticuploads.
Auto-reset
Thisonlyappliestoboardswithoutanon-boardUSB-to-Serialconverter.
IftheUSB-to-Serialconverteryou'reusinghasaDTRflowcontrolline,youcanautomatetheresetsignal.Whensendingdatatothe
ESP,theDTRlinegoeslow,andstayslowforsometime.ToresettheESP,weneedalowpulseontheRSTpin.Theproblemisthatthe
DTRpinstayslow.Tosolvethis,we'regoingtobuildacrudeedgedetectorcircuit,usingacapacitor.Takealookatthefollowing
schematic:
Youmightrecognizethatthisisbasicallyalow-cutfilter.Innormalconditions,DTRishigh(3.3V),andtheresetlineisalsohigh,
becauseofthepull-upresistorR2.Thismeansthatthevoltageacrossthecapacitoris0V.WhenDTRsuddenlydrops(to0V),the
voltageacrossthecapacitorisstill0V,meaningthattheresetlinewillbeat0V+0V=0V,andaresetistriggered.
However,C1immediatelystartschargingthroughR2,andreaches3.3V.Atthispoint,DTRisstillat0V,meaningthatthere'snow3.3V
acrossthecapacitor.WhenDTRrisesagain,theresetlinewillbeat3.3V+3.3V=6.6V,andthenimmediatelystartstodischarge
throughR2,finallyreaching3.3Vagain,with0VacrossC1.
Thisisaproblem:6.6VcandamagetheESP,sowehavetofindawaytogetridofthepositivepeak.
OneglanceatthisMATLABsimulationshowsustheproblemevenbetter:

ThebluesignalisthevoltageontheDTRpin,andtheyellowsignalisthevoltageontheresetpin.
Thesolutionistoaddadiode:whilechargingthecapacitor,itshouldn'tchangeanything,soitshouldbereversebiased(justafancy
wayofsayingthatit'snotconductinganycurrentbecausethepolarityistheotherwayaround),andwhilethecapacitoris
discharging,itshoulddischargethecapacitor"immediately".
Here'swhatthatlookslike:
Let'srunthesimulationagaintocheckifourproblemissolved:

Asyoucansee,the6.6Vpeakisnowverynarrow,justlikewewanted.It'simpossibletodischargethecapacitorinstantly,thatwould
requireacapacitorandadiodewith0Ωofseriesresistance,andaninfinitecurrent,whichisimpossible,obviously.There'salsoa
smallerbutrelativelywidepeakofapproximately3.9V.Thisisbecauseadiodeonlyconductswhenthevoltageacrossitishigherthan
~600mV.Thismeansthatthelast0.6Vthat'sleftinthecapacitor(from3.9to3.3V)willstillbedischargedthroughR2only.
Nevertheless,thevoltagepeakismuchlowerandnarrowerthanwithoutthediode,andit'ssafetoconnecttotheESP8266.
ThisexactcircuitisalsousedintheArduinoUno,forexample.
Note:ifyoufollowedtheinstructionsinthehardwarestepcorrectly,youshouldalreadyhaveaddedR2toyourESP.
HowtouseAuto-reset
Tousethisauto-resetcircuit,connectittotheDTRlineofyourUSB-to-Serialconverter,andtotheresetlineoftheESP,asshownin
thediagram.Thenclickcompile(justbecausethefirstcompilationcantakequitesometime).GotoTools>Resetandselect'ck'.
Whenit'sdonecompiling,holddowntheprogrambuttonweaddedinthehardwarestep,andclickupload.Waitforittosay
"Uploading..."andthenreleasetheprogrambutton.
Auto-resetandAuto-program
Thisonlyappliestoboardswithoutanon-boardUSB-to-Serialconverter.
Themethodabovestillrequiresyoutopressabuttontouploadanewsketch.IfyourUSB-to-SerialconverterhasaRTSlineaswellas
aDTRline,youcanautomatetheentireprocess.

Youmayfindoutthatthe4.7kΩresistordoesn'tworkforyou.Inthatcase,trysomeothervalue,like10kΩ,forexample.
ThismethodwasfirstusedintheNodeMCU,sogotoTools>ResetMethod,andselect"nodemcu".ThiswilldrivetheDTR&RTSpins
highandlowintherightsequencetogetitinprogrammingmodebeforeuploading.
Thisisbyfarthebestmethod,buttheproblemisthatyouneedaccesstoboththeRTSandDTRpins,whilemostUSB-to-Serial
adaptersbreakoutonlyoneofthetwo.
Manualresetandmanualprogram
Thisonlyappliestoboardswithoutanon-boardUSB-to-Serialconverter.
Ifyoudon'thaveaUSB-to-SerialconverterwithDTRandRTSlines,youcouldalsojustusetheresetandprogrambuttonsweaddedin
thehardwarechapter.TogettheESPinprogrammode,GPIO0mustbelowwhilebooting:
1. pressandholdtheresetbutton
2. pressandholdtheprogrambutton
3. releasetheresetbutton,theESPwillbootinprogrammode
4. releasetheprogrambutton
5. uploadthesketch
Ifyouwanttogetoutofprogrammodewithoutuploading,justpressreset(withoutpressingtheprogrambutton).
Boardoptions
IfyourspecificboardisintheTools>Boardlist(e.g.NodeMCU,SparkFunandAdafruitboards),youcanjustselectit,andyouwillget
therightsettings.Whenyourboardisn'tinthelist,you'llhavetoselectaGenericESP8266.Inthatcasethere'slotsofnewoptionsin
theToolsmenuoftheArduinoIDE,solet'sgooverthemandpicktherightsettings.
FlashMode
LikeIsaidbefore,theESP8266usesanexternalflashchipforstorage.Youcancommunicatewiththischipover2datalines(DIO),or
overall4datalines(QIO).Using4linesistwotimesfasterthan2lines,soinmostcases,youshouldchooseQIO.(Ifyou'redoingsome
advancedstuffandyouneed2moreGPIOpins,youcoulduse2linesinsteadof4,andusethe2linesasI/O.Mostmodulesdon'tgive
youaccesstothesepins,though.)
FlashSize
Differentboards/moduleshavedifferentsizesofflashchipsonboard.Thereareboardswith512kB,1MB,2MBand4MBofflash.To

knowhowmuchflashyourboardhas,youcantrytheExamples>ESP8266>CheckFlashConfigtoseeifyourflashsettingiscorrect,
oryoucancheckthespecificationsofyourspecificboardonline.
YoucanalsoselecttheSPIFFS(SPIFlashFileSystem)size.TheSPIFFSpartitionisasmallfilesystemtostorefiles.Ifyou'renotusing
it,youcanselecttheminimum.Lateroninthearticle,we'lluseSPIFFS,andI'llremindyoutoselectalargerSPIFFSsize,butfornow,
itdoesn'treallymatter.
Debugport
There'saloadofthingsgoingonwhentheESPisrunning:ThingslikeWi-Ficonnections,TCPconnections,DNSlookups...younameit.
Allthesesmalltasksproduceawholelotofdebugoutputtohelpyoutroubleshoot.However,inanormalsituation,whereyour
programisbehavingasexpected,youdon'tneedallthosedebugmessagestofloodtheSerialMonitor,soyoucanjustturnthemoff
byselecting'Disabled'.
Ifyoudowishtoreceivedebugmessages,youcanselecttheporttosendthemto.(Serialonpins1and3,orSerial1onpin2)
Debuglevel
Thisallowsyoutochoosewhatkindofdebugmessagesyouwanttoshow.
ResetMethod
Asmentionedintheparagraphsabove,therearedifferentmethodsforauto-resetandauto-program.Ifyou'reusingthefirstmethod
(usingtheedgedetector),youshoulduse'ck',ifyouusethetwo-transistorcircuit,select'nodemcu'.
FlashFrequency
Ifyouneedsomeextramemoryspeed,youcouldchangetheflashfrequencyfrom40MHzto80MHz.Thisistheclockfrequencyofthe
SPI/SDIOlink.
CPUFrequency
IfyouneedsomeextraCPUperformance,youcandoubletheclockspeedfrom80MHzto160MHz.It'sactuallyanoverclock,butI've
neverhadanyissuesorinstability.
UploadSpeed
ThebaudrateforuploadingtotheESP.Thedefaultis115200baud,butyoucangohigher(ifyou'rechangingyoursketchalot,it
mightbetooslow).921600baudworksmostofthetime,butyoumaygetanerrorsometimes,ifthat'sthecase,switchingbackto
115200willprobablysolveallproblems.

EstablishingaWi-Ficonnection
LikeImentionedinthepreviouschapter,theESP8266canoperateinthreedifferentmodes:Wi-Fistation,Wi-Fiaccesspoint,andboth
atthesametime.We'llstartbylookingattheconfigurationofaWi-Fistation.
Stationmode
Connectingtoonespecificnetwork
#include<ESP8266WiFi.h>//IncludetheWi-Filibrary
constchar*ssid="SSID";//TheSSID(name)oftheWi-Finetworkyouwanttoconnectto
constchar*password="PASSWORD";//ThepasswordoftheWi-Finetwork
voidsetup(){
Serial.begin(115200);//StarttheSerialcommunicationtosendmessagestothecomputer
delay(10);
Serial.println('\n');
WiFi.begin(ssid,password);//Connecttothenetwork
Serial.print("Connectingto");
Serial.print(ssid);Serial.println("...");
inti=0;
while(WiFi.status()!=WL_CONNECTED){//WaitfortheWi-Fitoconnect
delay(1000);
Serial.print(++i);Serial.print('');
}
Serial.println('\n');
Serial.println("Connectionestablished!");
Serial.print("IPaddress:\t");
Serial.println(WiFi.localIP());//SendtheIPaddressoftheESP8266tothecomputer
}
voidloop(){}
Thecodetoconnecttoawirelessaccesspointisrelativelystraightforward:entertheSSIDandthepasswordofthenetworkyouwant
toconnectto,andcalltheWiFi.beginfunction.Thenwaitfortheconnectiontocomplete,etvoilà,yourESP8266isnowconnectedto
yourLocalAreaNetwork.
Don'tbelieveme?I'llproveittoyou:opentheSerialmonitor(CTRL+SHIFT+M)anduploadthesketch.Youshouldseesomethinglike
this:
ConnectingtoSSID...
123456...
Connectionestablished!
IPaddress: 192.168.1.3
Nowgotoyourcomputerandopenupaterminal:OnWindows,searchfor"CommandPrompt",onMacorLinux,searchfor"Terminal".
Youcouldalsousetheshortcuts:onWindows,hit +R,type"cmd"andhitenter,onLinux,useCTRL+ALT+T.
Next,typeping,andthentheIPaddressyoureceivedintheSerialmonitor.Ifyou'reonMacorLinux,useCTRL+Ctostopitaftera
coupleoflines.Theoutputshouldlooksomethinglikethis:
user@computername:~$ ping192.168.1.3
PING192.168.1.3(192.168.1.3)56(84)bytesofdata.
64bytesfrom192.168.1.3:icmp_seq=1ttl=128time=6.38ms
64bytesfrom192.168.1.3:icmp_seq=2ttl=128time=45.2ms
64bytesfrom192.168.1.3:icmp_seq=3ttl=128time=69.1ms
64bytesfrom192.168.1.3:icmp_seq=4ttl=128time=94.0ms
64bytesfrom192.168.1.3:icmp_seq=5ttl=128time=20.5ms
64bytesfrom192.168.1.3:icmp_seq=6ttl=128time=7.37ms
^C
---192.168.1.3pingstatistics---
6packetstransmitted,6received,0%packetloss,time5003ms
rttmin/avg/max/mdev=6.384/40.463/94.047/32.588ms
ThepingcommandsendssmallpacketstotheIPaddressoftheESP8266.WhentheESPreceivessuchapacket,itsendsitbacktothe
sender.PingispartofthesecondlayeroftheTCP/IPstack,theInternetlayer.ItreliesonboththeDataLinklayer(Wi-Fi)andthe
InternetProtocol*.
Youcanseethatintheexampleabove,wesent6packetstotheESP,andwealsoreceived6response(echo)packets.Thistellsus
thattheDataLink,theWi-Ficonnection,andtheInternetProtocolareworkingcorrectly.
WenowknowthattheESPcansuccessfullycommunicatewithotherdevicesonthenetwork,andifyourlocalnetworkisonline(ifitis
connectedtotheInternetviayourmodem),theESPcanalsocommunicatewithanydeviceontheweb!
PingisagreattooltocheckiftheESP(oranydevice,really)isstillconnectedtothenetwork,andifit'sstillworkingfine.
OnedrawbackisthatIPaddressescanchangeovertime,butthat'saproblemwe'lladdressinoneofthefollowingchapters...
(*)I'msimplifyingthingsabithere.Actually,pingispartoftheInternetControlMessageProtocol(ICMP),that'salsopartofthesecondlayer,justliketheInternet
Protocol.Don'tworrytoomuchaboutit,justrememberthatifyoucansendpingpacketstoadevice,youcanalsosendIPpackets.

Thedevicewiththeantennaservesmanydifferentpurposes:
Accesspoint:OtherWi-Fidevicescanconnecttoit,tobepartofthelocalnetwork.
Router:ItroutesIPpacketstotherightsub-netssothattheywillarriveattheirdestination.E.g.ifthecomputersendsa
messagethatismeantfortheESPovertheEthernetsub-net,therouterwillsendthepackettotheWi-Fisub-net,becauseit
knowsthat'swheretheESPis.
Modem:iftheroutercan'tfindtheaddresseeonthelocalnetwork,thepacketwillbepassedontotheintegratedmodem,andit
willbesenttotheInternetServiceProvideroveraDSLline,headingfortheInternet,wherelotsofotherrouterswilltrytogetthe
packettotherightdestination.
Butinreality,youdon'thavetoworrytoomuchaboutit,becauseit'salldoneforyou,inafractionofasecondwithoutyoueven
noticingit!
Automaticallyconnecttothestrongestnetwork
Thesketchabovemightbeenoughforyourspecificapplication,butifyouneedtobeabletoconnecttomultipleWi-Finetworks,for
exampletheWi-FiathomeandtheWi-Fiattheoffice,itwon'twork.
Tosolvethisproblem,we'llusetheWi-Fi-Multilibrary:Youcanaddasmanynetworksasyoulike,anditautomaticallyconnectstothe
onewiththestrongestsignal.
#include<ESP8266WiFi.h>//IncludetheWi-Filibrary
#include<ESP8266WiFiMulti.h>//IncludetheWi-Fi-Multilibrary
ESP8266WiFiMultiwifiMulti;//CreateaninstanceoftheESP8266WiFiMulticlass,called'wifiMulti'
voidsetup(){
Serial.begin(115200);//StarttheSerialcommunicationtosendmessagestothecomputer
delay(10);
Serial.println('\n');
wifiMulti.addAP("ssid_from_AP_1","your_password_for_AP_1");//addWi-Finetworksyouwanttoconnectto
wifiMulti.addAP("ssid_from_AP_2","your_password_for_AP_2");
wifiMulti.addAP("ssid_from_AP_3","your_password_for_AP_3");
Serial.println("Connecting...");
inti=0;
while(wifiMulti.run()!=WL_CONNECTED){//WaitfortheWi-Fitoconnect:scanforWi-Finetworks,andconnecttothestrongestof
thenetworksabove
delay(1000);
Serial.print('.');
}
Serial.println('\n');
Serial.print("Connectedto");
Serial.println(WiFi.SSID());//Telluswhatnetworkwe'reconnectedto
Serial.print("IPaddress:\t");
Serial.println(WiFi.localIP());//SendtheIPaddressoftheESP8266tothecomputer
}
voidloop(){}
AccessPointmode

ToconfiguretheESP8266asanaccesspoint,toallowotherdeviceslikesmartphonesorlaptopstoconnecttoit,youcanusethe
softAPfunction:
#include<ESP8266WiFi.h>//IncludetheWi-Filibrary
constchar*ssid="ESP8266AccessPoint";//ThenameoftheWi-Finetworkthatwillbecreated
constchar*password="thereisnospoon";//Thepasswordrequiredtoconnecttoit,leaveblankforanopennetwork
voidsetup(){
Serial.begin(115200);
delay(10);
Serial.println('\n');
WiFi.softAP(ssid,password);//Starttheaccesspoint
Serial.print("AccessPoint\"");
Serial.print(ssid);
Serial.println("\"started");
Serial.print("IPaddress:\t");
Serial.println(WiFi.softAPIP());//SendtheIPaddressoftheESP8266tothecomputer
}
voidloop(){}
Toseeifitworks,opentheWi-Fisettingsonyourcomputer,lookforanetworkcalled"ESP8266AccessPoint",enterthepassword
"thereisnospoon",andconnecttoit.Thenopenaterminal,andpingto192.168.4.1(thisisthedefaultIPaddressofourESPAP).You'll
seethattheESPrespondstoyourpings.
However,ifyoutrytogotoanonlinewebsite,you'llgetatimeoutoraDNSerror.ThisisbecausetheESPitselfisnotconnectedtothe
internet.Thesub-netthatconsistsoftheESPandthecomputerisnotconnectedtoanyothernetworks,sothere'snowayforapacket
onthisnetworktomakeittotheInternet.
IfyouconnectedasecondstationtotheESPaccesspointontheotherhand,youwouldbeabletopingfromonestationtotheother
withoutproblems,becausethey'reonthesamenetwork.
Other manuals for ESP8266 SDK
3
Table of contents
Other Espressif Systems Single Board Computer manuals