You are on page 1of 12

ESP8266WEBSERVERANDCONNECTEDDEVICES

ESP8266WebServerandConnectedDevices

TheESP8266addsWiFiconnectivitytoanydeviceandcanbeconfiguredeitherasanAccessPoint,a
Stationorboth,providinggreatflexibilitywhendesigningaconnectedsetup.Connectionscanbe
establishedbetweenunitsandwiththeuser,eitherlimitedtothelocalnetworkoraccessiblefrom
outside,whichcreatesanendlessrangeofpossibilities.

Inapreviousdocumentwereviewedthemethodtoconnect,programandtesttheESP826601module,
eitherlinkedtoaPCorinastandaloneoperation.However,theWiFiconnectivity,therealvalueofthis
device,wasnotdiscussedatall;inthisdocumentwewillreviewhowtousetheESPWiFicapabilities.

Basicwebserver

CreatingabasicwebserverinLua,withintheNodeMCUenvironment,isquitesimple.Itonlyrequiresa
fewlines,asshownbelow:

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
conn:send("<h1>HelloWorld</h1>")
end)
conn:on("sent",function(conn)conn:close()end)
end)

UsingtheESPlorer(seepreviousdocument),savethisscriptasinit.luaintheESP8266(makesurethat
thereisnootherinstancerunningbydeletingallpreviousscriptsonthemoduleandrestarting,typing
node.restart()inthecommandwindowoftheESPlorerandclickingtheSendbutton,seefigure1).


FIGURE1ESPlorercommandwindow

Copyright2016MarceloMaggi Page1

ESP8266WEBSERVERANDCONNECTEDDEVICES

ClosetheconnectioninESPloreranddisconnecttheadaptercablefromthePC.Connecttheadapter
boardtoanexternal5Vpowersupply,asshowninfigure2.


FIGURE2Adapterboardconnectedtoanexternalpowersupply

Ifyouhavenopowersupplyavailable,youmayaswellusetheadaptercableandconnecttotheUSB
portofthePC.However,pleasenotethatwewillnotbeusingtheUSBconnectionthistime.

OpentheNetworkAdministratorinyourPCandenablewirelessconnections;youmaynoticethatthere
isanewwirelessaccesspoint,calledESP_81Axxx(youractualnamemaybeslightlydifferent).Connect
tothisnetwork.

Asyoumayhaveguessed,youarenowconnectedtoyourESP8266!

Now,letsseeifitrespondswiththemessageHelloWorldwhencalled,asitwasinstructedbythe
commandconn:send("<h1>HelloWorld</h1>").Inyourwebbrowsertypethisaddress:

192.168.4.1

Thebrowsershouldreturnthecontentsoffigure3.


FIGURE3ESPwebserverresponse

Congratulations!YouhaveconfiguredyourfirstwebserverusingtheESP8266.

YoumaywonderwhytheserveraddressistheoneImentioned(192.168.4.1),sincetherewasno
indicationofsuchinthewebserverscript?ThisaddressisfixedbytheESPfirmware;therearemethods
tochangeit,howeverIwillnotdiscussthemsincetheyareoutofthescopeofthisreview,andwewill
notbeusingthisconfigurationmuchinthefuture.

Copyright2016MarceloMaggi Page2

ESP8266WEBSERVERANDCONNECTEDDEVICES

Letstrysomethingelse;connectyourmobiledevice(phone,tablet)tothisnetwork,andtypethe
addressinthewebbrowser.Mostprobablyyouwillreceiveamessagelike:

Safaricannotopenthepagebecausethenetworkconnectionwaslostorsimply

Thenetworkconnectionwaslost

Nomatterhowmanytimesyoutry,youwillnotseethereplyfromtheESP.Thisissomethingexpected,
sincethebasicwebserverwecreateddoesnotfollowtheproperstructureofastandardserver;some
browsersmayacceptthisanddisplaythemessage,whileotherswillnot.

Properwebserver

Nowitistimetocreateawebserverwithalltheelementsrequiredtoberecognizedbyallthestandard
browsers,includingthoseavailableinmobiledevices.Deletethepreviousscript,restartthemoduleand
uploadthefollowingcodetotheESP;remembertonameitinit.luaifyouwantastandaloneoperation:

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
localmethod=""
localurl=""
localvars=""
conn:on("receive",function(conn,payload)
_,_,method,url,vars=string.find(payload,"([AZ]+)/([^?]*)%??(.*)HTTP")
ifurl=="favicon.ico"then
conn:send("HTTP/1.1404filenotfound")
return
end
conn:send("HTTP/1.1200OK\r\n\r\n")
end)
conn:on("sent",function(conn)
conn:send("<!DOCTYPEhtml><html><h1>HelloWorld</h1></html>")
conn:close()end)
end)

Oncethecodeisuploadedandrunning,youmayconnecttotheESPaccesspoint.Nowtypetheaddress
inthebrowserofyourmobiledevice,192.168.4.1.

Copyright2016MarceloMaggi Page3

ESP8266WEBSERVERANDCONNECTEDDEVICES

YoushouldnowreceivethemessageHelloWorld,formattedinboldtype.Theadditionsinthecodeare
actuallytheminimumrequirementsforaproperdialogwhenawebpageisrequestedbythebrowser.
Infactthecodesendsacompletewebpageinthisline:

conn:send("<!DOCTYPEhtml><html><h1>HelloWorld</h1></html>")

YoumaytestthiscodebyopeninganewdocumentwithNotepad;type:

<!DOCTYPEhtml>
<html>
<h1>HelloWorld</h1>
</html>

Saveitastest.html.OpenitwithanybrowserandyouwillseethewordsHelloWorldinbold.

BacktotheESP,whilethisscriptworks,itisnotquiteusefulwhenyouhavetosendmoreelaborate
pages,e.g.withbuttonsandcommands.Notonlyitiscumbersometowritethehtmlcodeinsidethe
function,itwilldefinitelyfailwhentryingtosendlongpages,andtheESPmayresetitself.Thesolution
istowriteaproperhtmlpageoutsidethescript,andcallitwhenrequired.

Independenthtmlpage

Howtowritehtmlcodeisbeyondthescopeofthisdocument;howeverIwillshowsomeexamplesof
workingwebpagesthatwewillcallfromtheESPserverscript.LetsputtheHelloWorldpageoutside
thescriptandcallit.

Firstcreatethepage;letsusethetest.htmlfilecreatedabove.UploadittotheESP(asalways,remove
allpreviousfilesandrestartfirst).Onceuploaded,theESPlorerwillshowanerror:

test.html:1:unexpectedsymbolnear'<'
stacktraceback:
[C]:infunction'dofile'
stdin:1:inmainchunk
>

Thisisnormal,sincetheESPistryingtorunsomethingthatisnotwritteninLua.Now,uploadthe
followingLuascripttotheESP,savedasinit.lua(withoutremovingthehtml):

Copyright2016MarceloMaggi Page4

ESP8266WEBSERVERANDCONNECTEDDEVICES

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
localresponseBytes=0
localmethod=""
localurl=""
localvars=""
conn:on("receive",function(conn,payload)
_,_,method,url,vars=string.find(payload,"([AZ]+)/([^?]*)%??(.*)HTTP")
ifurl=="favicon.ico"then
conn:send("HTTP/1.1404filenotfound")
responseBytes=1
return
end
url="test.html"
responseBytes=0
conn:send("HTTP/1.1200OK\r\n\r\n")
end)
conn:on("sent",function(conn)
ifresponseBytes>=0andmethod=="GET"then
iffile.open(url,"r")then
file.seek("set",responseBytes)
localline=file.read()
file.close()
iflinethen
conn:send(line)
responseBytes=responseBytes+string.len(line)
return
end
end
end
conn:close()end)
end)

Restartthemoduleandconnecttotheaccesspoint;type192.168.4.1inthebrowser.Youshould
receiveHelloWorldasresponse.

Asyoucansee,thetextHelloWorldisnowhereintheLuascript;itiswritteninthehtmlfile.Thescript
loadsthehtmlpagenameinavariable(url="test.html")andlatercallsitwithintheconnfunction.The
functionreadsthepagelinebylineandsendsittothebrowser.

Copyright2016MarceloMaggi Page5

ESP8266WEBSERVERANDCONNECTEDDEVICES

ControllingtheESPhardwarefromawebbrowser

NowthatwecanuseanindependenthtmlpagetobedisplayedwhentheESPisaccessed,therangeof
possibilitiesincreasesexponentially.Notonlycanweshowmessagesbutwecansendcommandsback
totheESP,controllingthehardware,usingagraphicalinterface.

ThehardwareintheESP826601isquitesimple;wehavejust2portsaccessible,GPIO0andGPIO2.We
reviewedhowtocontroltheportsinapreviousdocument,andusingtheadapterboardwehavethe
additionaladvantagethateachportcanbeconnectedtoanLED.Theobjectivenowwillbetocontrol
theLEDsfromthebrowser,withacoupleofbuttonsperLED,basicallytheONandOFFstatus.

Letsstartbycreatingthehtmlpage,whichwillbenamedleds.html:

<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf8">
<title>MagusPortaMINI</title>
<styletype="text/css">
body{
backgroundcolor:#616161;
}
#container{
width:1024px;
height:auto;
marginright:auto;
marginleft:auto;
zindex:1;
}
#text{
position:absolute;
top:10px;
width:994px;
zindex:2;
backgroundcolor:#005CB9;
paddingright:10px;
paddingleft:10px;
borderradius:20px20px20px20px;
fontfamily:Verdana,Arial,Helvetica,sansserif;
height:auto;
fontsize:medium;
textalign:center;
color:#FFFFFF;

Copyright2016MarceloMaggi Page6

ESP8266WEBSERVERANDCONNECTEDDEVICES

}
#copyright{
position:fixed;
height:18px;
zindex:300;
backgroundcolor:#0066CC;
fontfamily:Arial,Helvetica,sansserif;
fontsize:14px;
fontweight:bolder;
color:rgba(255,255,255,1);
textalign:center;
verticalalign:middle;
margin:0px;
top:auto;
left:0%;
width:100%;
bottom:0px;
}
</style>
</head>
<body>
<divid="container"align='center'>
<divid="text">
<h3>IoTtest:LEDcontrolusingESP8266</h3>
<formaction=''method='get'>
<strong>LED1</strong><br><br>
<inputtype="submit"name="LED1"id="1"value="TURNON">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<inputtype="submit"name="LED1"id="2"value="TURNOFF">
</form>
<h3></h3>
<formaction=''method='get'>
<strong>LED2</strong><br><br>
<inputtype="submit"name="LED2"id="1"value="TURNON">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<inputtype="submit"name="LED2"id="2"value="TURNOFF">
</form>
<h3></h3>
</div>

<divid="copyright">Copyright&copy;2016MagusPorta</div>
</body>
</html>

Copyright2016MarceloMaggi Page7

ESP8266WEBSERVERANDCONNECTEDDEVICES

ThislooksabitmorecomplexthantheHelloWorldexample,butmainlybecauseIamcreatinganice
formatandbackgroundforthepage.Theimportantpartisatthebottom,whereIdefinethebuttons,
actions,namesandvalues.YoumayseethatthenamesLED1andLED2appearhere,aswellasthe
valuesTURNONandTURNOFF.Thisisessential,sincewewillbeexpectingthesekeywordsinthe
Luascripttoperformtheproperactionswiththehardware,i.e.controllingtheLEDs.

DeleteallfilesintheESPanduploadthishtmlpage(leds.html).

Nowsavethisscriptasinit.lua:

gpio.mode(3,gpio.OUTPUT)
gpio.mode(4,gpio.OUTPUT)
gpio.write(3,gpio.LOW)
gpio.write(4,gpio.LOW)

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
localresponseBytes=0
localmethod=""
localurl=""
localvars=""
conn:on("receive",function(conn,payload)
_,_,method,url,vars=string.find(payload,"([AZ]+)/([^?]*)%??(.*)HTTP")
parse_wifi_credentials(vars)
ifurl=="favicon.ico"then
conn:send("HTTP/1.1404filenotfound")
responseBytes=1
return
end
url="leds.html"
responseBytes=0
conn:send("HTTP/1.1200OK\r\n\r\n")
end)
conn:on("sent",function(conn)
ifresponseBytes>=0andmethod=="GET"then
iffile.open(url,"r")then
file.seek("set",responseBytes)
localline=file.read()
file.close()
iflinethen
conn:send(line)
responseBytes=responseBytes+string.len(line)
return
end

Copyright2016MarceloMaggi Page8

ESP8266WEBSERVERANDCONNECTEDDEVICES

end
end
conn:close()
end)
end)

functionparse_wifi_credentials(vars)
ifvars==nilorvars==""then
returnfalse
end
ifvars=="LED1=TURN+ON"then
gpio.write(3,gpio.HIGH)
end
ifvars=="LED1=TURN+OFF"then
gpio.write(3,gpio.LOW)
end
ifvars=="LED2=TURN+ON"then
gpio.write(4,gpio.HIGH)
end
ifvars=="LED2=TURN+OFF"then
gpio.write(4,gpio.LOW)
end
returntrue
end

Thislastportionofthescriptreadsthekeywordssentbythebrowserwheneachbuttonispressed,and
controlsthestatusoftheportsaccordingly.

RestarttheESP,connectthePCtotheaccesspointandtypetheaddressinthebrowser;figure4shows
thereturnedpage.

Copyright2016MarceloMaggi Page9

ESP8266WEBSERVERANDCONNECTEDDEVICES


FIGURE4WebpagetocontroltheESP826601ports

PressingeachbuttonwillhaveanactionontheESP,turningonoroffeachoneoftheLEDs.
Congratulations!YounowhaveremotecontroloftheESPhardware,thereforeanythingconnectedtoit.

ESP8266asstation

SofarwehavebeenworkingwiththeESP8266configuredasanaccesspoint;whileitisadequatefor
apointtopointconnection,ithassomelimitationsifwewanttoestablishmoreelaborateconnections.
AnotherwaytoconfiguretheESPWiFiconnectionisasastation.Inthisway,theESPwillappearas
anotherdeviceinyourhomenetwork,connectedtotherouter.

Thestationconfigurationisquitesimple;only2linesneedtobeaddedatthebeginningoftheLua
script:

wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","password")

WhereitsaysSSIDyoujustputthenameofyourhomenetwork;passwordisobviouslyyournetwork
password.

Copyright2016MarceloMaggi Page10

ESP8266WEBSERVERANDCONNECTEDDEVICES

HowdoyouaccesstheESPnow?InDHCPmode,themostcommonconfigurationofarouter,theESP
willhaveanIPaddressautomaticallyassigned.Youmaylookforitontherouterpage,orbyaddinga
lineinyourLuascript:

print(wifi.sta.getip())

ThislinewillshowinESPlorertheIPassignedbytheroutertotheESP.Youmayputitimmediatelyafter
the2linesshownbefore.

Aquicknotehere:thefirsttimeyourunthisscript,configuringthestationmode,theprintlinemay
returnnil.Theprocessrunsveryfast,sothereisnotimefortheroutertoassignanIPbeforetheprint
commandisexecuted.OncetherouterassignedtheIP,thisisstoredinnonvolatilememory,sonext
timeyourunthescriptorresetthemoduletheprintcommandwillshowtheassignedIPaddress:

>dofile("init.lua")
192.168.1.23 255.255.255.0 192.168.1.1
>

Asyoucansee,inthiscasetheIPis192.168.1.23,anditisfollowedbythesubnetmaskandDNSserver.

IfyoutypethisIPinyourbrowser,youwillseethesamescreenshowninfigure4before,andyoucan
controlthestatusofbothLEDs.

StaticIP

SometimesitisquiteusefultohaveaconstantIPassignedtotheESP,soyoualwaysknowwheretocall.
Thisiseasytoachievewithjustafewlines:

SSID="SSID"
PW="password"
IPADR="192.168.1.49"
IPROUTER="192.168.1.1"
wifi.setmode(wifi.STATION)
wifi.sta.setip({ip=IPADR,netmask="255.255.255.0",gateway=IPROUTER})
wifi.sta.config(SSID,PW)

Forclarity,afewvariableshavebeenadded,butonlyonenewfunctionispresent,wifi.sta.setip().This
functionrequesttherouter,locatedat192.168.1.1,toassigntheESPtheIPaddress192.168.1.49.
AlwaysmakesurethattherequestedaddressiswithintherangeyouhavesetinyourrouterforvalidIP
addresses,andthatitisnotcurrentlyusedbyanyotherdeviceinyournetwork.

Copyright2016MarceloMaggi Page11

ESP8266WEBSERVERANDCONNECTEDDEVICES

YoumayalsosetastaticIPfortheESPinyourrouter,knowingtheMACaddressofthemodule.Itisup
toyouwhichmethodyouuse,althoughIprefertheformersoIdonothavetodealwiththerouter
setup.

ThisconcludestheseconddocumentontheESP8266;atthispointyoushouldbeabletosetuptheESP,
configureawebserverandcontrolthehardwareviawebcommands,fromagraphicalwebpage.The
samewayanLEDisturnedonandoff,arelaymaybeconnectedtotheGPIOoutput(withtheproper
protectionandcurrentamplifiersetup,i.e.transistoranddiode),soamuchlargerelectricalloadcanbe
controlled.AtypicalapplicationistocontrolaremoteACoutlet,soyoumayturnonandoffanything
pluggedtoit.Younowhavetheknowledgetodoit,sodonotbeafraidtoexperiment;however,as
usual,beextremelycautiouswhenworkingwithhighvoltagesand/orcurrents.

Copyright2016MarceloMaggi Page12

You might also like