Beruflich Dokumente
Kultur Dokumente
2015 data:text/html,<htmlcontenteditable>
NodeMCUAPI
Instruction
version0.9.5build20150213
INDEX
ChangeLog
NewGPIOMap
OldGPIOMap
nodemodule
node.restart()
node.dsleep()
node.info()
node.chipid()
node.flashid()
node.heap()
node.key()deprecated
node.led()deprecated
node.input()
node.output()
node.readvdd33()deprecated,movedto
adc.readvdd33()
node.compile()
node.setcpufreq()
filemodule
file.remove()
file.open()
file.close()
file.readline()
file.writeline()
data:text/html,<htmlcontenteditable> 1/127
29.6.2015 data:text/html,<htmlcontenteditable>
file.read()
file.write()
file.flush()
file.seek()
file.list()
file.format()
file.rename()
file.fsinfo()
wifimodule
wifi.setmode()
wifi.getmode()
wifi.getchannel()Addedon07/16/2015
wifi.setphymode()Addedon07/16/2015
wifi.getphymode()Addedon07/16/2015
wifi.startsmart()
wifi.stopsmart()
wifi.sleeptype()
wifi.stasubmodule
wifi.sta.getconfig()Addedon07/16/2015
wifi.sta.config()Updatedon07/16/2015
wifi.sta.connect()
wifi.sta.disconnect()
wifi.sta.autoconnect()
wifi.sta.getip()
wifi.sta.setip()
wifi.sta.getmac()Updatedon07/16/2015
wifi.sta.setmac()Updatedon07/16/2015
wifi.sta.getap()Updatedon07/16/2015
wifi.sta.status()
wifi.sta.getbroadcast()
wifi.apsubmodule
wifi.ap.config()
wifi.ap.getip()
data:text/html,<htmlcontenteditable> 2/127
29.6.2015 data:text/html,<htmlcontenteditable>
wifi.ap.setip()
wifi.ap.getmac()
wifi.ap.setmac()Updatedon07/16/2015
wifi.ap.getbroadcast()
timermodule
tmr.delay()
tmr.now()
tmr.alarm()
tmr.stop()
tmr.wdclr()
tmr.time()
gpiomodule
gpio.mode()
gpio.read()
gpio.write()
gpio.trig()
pwmmodule
pwm.setup()
pwm.close()
pwm.start()
pwm.stop()
pwm.setclock()
pwm.getclock()
pwm.setduty()
pwm.getduty()
netmodule
net.createServer()
net.createConnection()
net.serversubmodule
data:text/html,<htmlcontenteditable> 3/127
29.6.2015 data:text/html,<htmlcontenteditable>
net.server:listen()
net.server:close()
net.socketsubmodule
net.socket:connect()
net.socket:send()
net.socket:on()
net.socket:close()
net.socket:dns()
i2cmodule
i2c.setup()
i2c.start()
i2c.stop()
i2c.address()
i2c.write()
i2c.read()
adcmodule
adc.read()
adc.readvdd33()
uartmodule
uart.setup()
uart.on()
uart.write()
1wiremodule
ow.setup()
ow.reset()
ow.skip()
ow.select()
ow.write()
ow.write_bytes()
data:text/html,<htmlcontenteditable> 4/127
29.6.2015 data:text/html,<htmlcontenteditable>
ow.read()
ow.read_bytes()
ow.depower()
ow.reset_search()
ow.target_search()
ow.search()
ow.crc8()
ow.check_crc16()
ow.crc16()
bitmodule
bit.bnot()
bit.band()
bit.bor()
bit.bxor()
bit.lshift()
bit.rshift()
bit.arshift()
bit.bit()
bit.set()
bit.clear()
bit.isset()
bit.isclear()
spimodule
spi.setup()
spi.send()
spi.recv()
mqttmodule
mqtt.Client()
mqtt.clientsubmodule
mqtt.client:lwt()
mqtt.client:connect()
data:text/html,<htmlcontenteditable> 5/127
29.6.2015 data:text/html,<htmlcontenteditable>
mqtt.client:close()
mqtt.client:publish()
mqtt.client:subscribe()
mqtt.client:on()
WS2812module
ws2812.writergb()
cjsonmodule
cjson.encode()
cjson.decode()
u8gmodule
u8g.ssd1306_128x64_i2c()
u8g.ssd1306_128x64_spi()
u8g.pcd8544_84x48()
u8g.dispsubmodule
u8g.disp:begin()
u8g.disp:drawBitmap()
u8g.disp:drawBox()
u8g.disp:drawCircle()
u8g.disp:drawDisc()
u8g.disp:drawEllipse()
u8g.disp:drawFilledEllipse()
u8g.disp:drawFrame()
u8g.disp:drawHLine()
u8g.disp:drawLine()
u8g.disp:drawPixel()
u8g.disp:drawRBox()
u8g.disp:drawRFrame()
u8g.disp:drawStr()
u8g.disp:drawStr90()
u8g.disp:drawStr180()
u8g.disp:drawStr270()
data:text/html,<htmlcontenteditable> 6/127
29.6.2015 data:text/html,<htmlcontenteditable>
u8g.disp:drawTriangle()
u8g.disp:drawVLine()
u8g.disp:drawXBM()
u8g.disp:firstPage()
u8g.disp:getColorIndex()
u8g.disp:getFontAscent()
u8g.disp:getFontDescent()
u8g.disp:getFontLineSpacing()
u8g.disp:getHeight()
u8g.disp:getMode()
u8g.disp:getWidth()
u8g.disp:getStrWidth()
u8g.disp:nextPage()
u8g.disp:setColorIndex()
u8g.disp:setDefaultBackgroundColor()
u8g.disp:setDefaultForegroundColor()
u8g.disp:setFont()
u8g.disp:setFontLineSpacingFactor()
u8g.disp:setFontPosBaseline()
u8g.disp:setFontPosBottom()
u8g.disp:setFontPosCenter()
u8g.disp:setFontPosTop()
u8g.disp:setFontRefHeightAll()
u8g.disp:setFontRefHeightExtendedText()
u8g.disp:setFontRefHeightText()
u8g.disp:setRot90()
u8g.disp:setRot180()
u8g.disp:setRot270()
u8g.disp:setScale2x2()
u8g.disp:sleepOn()
u8g.disp:sleepOff()
u8g.disp:undoRotation()
u8g.disp:undoScale()
dhtmodule
dht.read()
dht.read11()
dht.readxx()
data:text/html,<htmlcontenteditable> 7/127
29.6.2015 data:text/html,<htmlcontenteditable>
BacktoIndex
Summary
Easytoaccesswirelessrouter
BasedonLua5.1.4,Developersaresupposed
tohaveexperiencewithLuaProgramlanguage.
EventDriveprogrammingmodal.
Buildinfile,timer,pwm,i2c,net,gpio,wifi,uart,
adcmodule.
SerialPortBaudRate:9600
RemappedGPIOpin,usetheindextoprogram
gpio,i2c,pwm.
GPIOMapTable:
GPIONEWTABLE(Build
20141219andlater)
new_gpio_map
IOindex ESP8266pin IOindex
0[*] GPIO16
1 GPIO5
2 GPIO4
3 GPIO0
4 GPIO2
5 GPIO14
6 GPIO12
**[]D0(GPIO16)canonlybeusedasgpio
read/write.nointerruptsupported.nopwm/i2c/ow
supported.*
Example
data:text/html,<htmlcontenteditable> 8/127
29.6.2015 data:text/html,<htmlcontenteditable>
gpio={[0]=3,[1]=10,[2]=4,[3]=9,[4]=1,[5]=2
pin=gpio[2]connectthesignalwiretopin4
BacktoIndex
GPIOOLDTABLE(Before
build20141212)
old_gpio_map
IOindex ESP8266pin IOindex
0 GPIO12
1 GPIO13
2 GPIO14
3 GPIO15
4 GPIO3
5 GPIO1
BacktoIndex
Burn/FlashFirmware
Address
nodemcu_512k.bin:0x00000
SeeNodeMCUflashtool:
nodemcuflasher
nodemodule
data:text/html,<htmlcontenteditable> 9/127
29.6.2015 data:text/html,<htmlcontenteditable>
node.restart()
Description
restartthechip.
Syntax
node.restart()
Parameters
nil
Returns
nil
Example
node.restart();
Seealso
BacktoIndex
node.dsleep()
Description
Enterdeepsleepmode,wakeupwhentimedout.
Syntax
node.dsleep(us,option)
Note:Thisfunctioncanonlybeusedinthecondition
thatesp8266PIN32(RST)andPIN8(XPD_DCDC
akaGPIO16)areconnectedtogether.Usingsleep(0)
willsetnowakeuptimer,connectaGPIOtopin
data:text/html,<htmlcontenteditable> 10/127
29.6.2015 data:text/html,<htmlcontenteditable>
RST,thechipwillwakeupbyafallingedgeonpin
RST.
option=0,initdatabyte108isvaluable
option>0,initdatabyte108isvalueless.
Moredetailsasfollows:
0,RF_CALornotafterdeepsleepwakeup,
dependsoninitdatabyte108.
1,RF_CALafterdeepsleepwakeup,therewill
belargecurrent.
2,noRF_CALafterdeepsleepwakeup,therewill
onlybesmallcurrent.
4,disableRFafterdeepsleepwakeup,justlike
modemsleep,therewillbethesmallestcurrent.
Parameters
us:number(Integer)ornil,sleeptimeinmicro
second.Ifus=0,itwillsleepforever.Ifus=nil,
willnotsetsleeptime.
option:number(Integer)ornil.Ifoption=nil,it
willuselastalivesettingasdefaultoption.
Returns
nil
Example
donothing
node.dsleep()
sleeps
node.dsleep(1000000)
setsleepoption,thensleeps
node.dsleep(1000000,4)
setsleepoptiononly
node.dsleep(nil,4)
Seealso
BacktoIndex
data:text/html,<htmlcontenteditable> 11/127
29.6.2015 data:text/html,<htmlcontenteditable>
node.info()
Description
returnNodeMCUversion,chipid,flashid,flashsize,
flashmode,flashspeed.
Syntax
node.info()
Parameters
nil
Returns
majorVer(number)
minorVer(number)
devVer(number)
chipid(number)
flashid(number)
flashsize(number)
flashmode(number)
flashspeed(number)
Example
majorVer,minorVer,devVer,chipid,flashid,flashsize,flashmode,flashspeed
print("NodeMCU"..majorVer.."."..minorVer.."."
Seealso
BacktoIndex
node.chipid()
Description
data:text/html,<htmlcontenteditable> 12/127
29.6.2015 data:text/html,<htmlcontenteditable>
returnchipID
Syntax
node.chipid()
Parameters
nil
Returns
number:chipID
Example
id=node.chipid();
Seealso
BacktoIndex
node.flashid()
Description
returnflashidID
Syntax
node.flashid()
Parameters
nil
Returns
number:flashID
Example
data:text/html,<htmlcontenteditable> 13/127
29.6.2015 data:text/html,<htmlcontenteditable>
flashid=node.flashid();
Seealso
BacktoIndex
node.heap()
Description
returntheremainHEAPsizeinbytes
Syntax
node.heap()
Parameters
nil
Returns
number:systemheapsizeleftinbytes
Example
heap_size=node.heap();
Seealso
BacktoIndex
node.key()
Description
definebuttonfunction,buttonisconnectedto
GPIO16.
data:text/html,<htmlcontenteditable> 14/127
29.6.2015 data:text/html,<htmlcontenteditable>
Syntax
node.key(type,function())
Parameters
type:typeiseitherstring"long"or"short".long:press
thekeyfor3seconds,short:pressshortly(lessthan
3seconds)
function():userdefinedfunctionwhichiscalledwhen
keyispressed.Ifnil,canclingtheuserdefined
function.
Defaultfunction:long:changeLEDblinkingrate,
short:resetchip
Returns
nil
Example
node.key("long",function()print('helloworld
Seealso
node.led
BacktoIndex
node.led()
Description
setuptheon/offtimeforled,whichconnectedto
GPIO16,multiplexingwithnode.key()
Syntax
node.led(low,high)
data:text/html,<htmlcontenteditable> 15/127
29.6.2015 data:text/html,<htmlcontenteditable>
Parameters
Low:LEDofftime,LEDkeepsonwhenlow=0.Unit:
milliseconds,timeresolution:80~100ms
High:LEDontime.Unit:milliseconds,time
resolution:80~100ms
Returns
nil
Example
turnledonforever.
node.led(0);
Seealso
node.key
BacktoIndex
node.input()
Description
acceptastringandputthestringintoLuainterpretor.
sameaspcall(loadstring(str))butsupportmulti
seperatedline.
Syntax
node.input(str)
Parameters
str:Luachunk
Returns
nil
data:text/html,<htmlcontenteditable> 16/127
29.6.2015 data:text/html,<htmlcontenteditable>
Example
neverusenode.input()inconsole.noeffect.
sk:on("receive",function(conn,payload)node.
Seealso
BacktoIndex
node.output()
Description
directoutputfromluainterpretortoacallback
function.
Syntax
node.output(function(str),serial_debug)
Parameters
function(str):afunctionaccepteveryoutputasstr,
andcansendtheoutputtoasocket.
serial_debug:1outputalsoshowinserial.0:no
serialoutput.
Returns
nil
Example
functiontonet(str)
sk:send(str)
print(str)WRONG!!!nevereverprintsomethinginthisfunction
becausethiswillcausearecursivefunctioncall!!!
end
data:text/html,<htmlcontenteditable> 17/127
29.6.2015 data:text/html,<htmlcontenteditable>
node.ouput(tonet,1)serialalsogettheluaoutput.
asimpletelnetserver
s=net.createServer(net.TCP)
s:listen(2323,function(c)
con_std=c
functions_output(str)
if(con_std~=nil)
thencon_std:send(str)
end
end
node.output(s_output,0)redirectoutputtofunctions_ouput.
c:on("receive",function(c,l)
node.input(l)workslikepcall(loadstring(l))butsupportmultiplese
end)
c:on("disconnection",function(c)
con_std=nil
node.output(nil)unregisttheredirectoutputfunction,outputgoesto
end)
end)
Seealso
BacktoIndex
node.readvdd33()
Description
Readingvdd33pinvoltage
Syntax
node.readvdd33()
Parameters
noparameters
data:text/html,<htmlcontenteditable> 18/127
29.6.2015 data:text/html,<htmlcontenteditable>
Returns
mV
Example
print(node.readvdd33())
output
3345
v=node.readvdd33()/1000
print(v)
v=nil
output
3.315
Seealso
BacktoIndex
node.compile()
Description
compileluatextfileintoluabytecodefile,andsaveit
as.lcfile.
Syntax
node.compile("file.lua")
Parameters
luatextfileendwith".lua"
data:text/html,<htmlcontenteditable> 19/127
29.6.2015 data:text/html,<htmlcontenteditable>
Returns
nil
Example
file.open("hello.lua","w+")
file.writeline([[print("hellonodemcu")]])
file.writeline([[print(node.heap())]])
file.close()
node.compile("hello.lua")
dofile("hello.lua")
dofile("hello.lc")
Seealso
BacktoIndex
node.setcpufreq()
Description
ChangetheworkingCPUFrequency
Syntax
node.setcpufreq(speed)
Parameters
speed:node.CPU80MHZornode.CPU160MHZ
Returns
returntargeCPUFrequency
Example
data:text/html,<htmlcontenteditable> 20/127
29.6.2015 data:text/html,<htmlcontenteditable>
node.setcpufreq(node.CPU80MHZ)
Seealso
BacktoIndex
filemodule
file.remove()
Description
removefilefromfilesystem.
Syntax
file.remove(filename)
Parameters
filename:filetoremove
Returns
nil
Example
remove"foo.lua"fromfilesystem.
file.remove("foo.lua")
Seealso
file.open()
file.close()
BacktoIndex
data:text/html,<htmlcontenteditable> 21/127
29.6.2015 data:text/html,<htmlcontenteditable>
file.open()
Description
openfile.
Syntax
file.open(filename,mode)
Parameters
filename:filetobeopened,directoriesarenot
supported
mode:
"r":readmode(thedefault)
"w":writemode
"a":appendmode
"r+":updatemode,allpreviousdatais
preserved
"w+":updatemode,allpreviousdataiserased
"a+":appendupdatemode,previousdatais
preserved,writingisonlyallowedattheendof
file
Returns
nil:filenotopened,ornotexists.true:fileopenedok.
Example
open'init.lua',printthefirstline.
file.open("init.lua","r")
print(file.readline())
file.close()
Seealso
file.close()
data:text/html,<htmlcontenteditable> 22/127
29.6.2015 data:text/html,<htmlcontenteditable>
file.readline()
BacktoIndex
file.close()
Description
closethefile.
Syntax
file.close()
Parameters
nil
Returns
nil
Example
open'init.lua',printthefirstline.
file.open("init.lua","r")
print(file.readline())
file.close()
Seealso
file.open()
file.readline()
BacktoIndex
file.readline()
Description
data:text/html,<htmlcontenteditable> 23/127
29.6.2015 data:text/html,<htmlcontenteditable>
readonelineoffilewhichisopenedbefore.
Syntax
file.readline()
Parameters
nil
Returns
filecontentinstring,linebyline,includeEOL('\n')
returnnilwhenEOF.
Example
printthefirstlineof'init.lua'
file.open("init.lua","r")
print(file.readline())
file.close()
Seealso
file.open()
file.close()
BacktoIndex
file.writeline()
Description
writestringtofileandadda'\n'attheend.
Syntax
file.writeline(string)
Parameters
data:text/html,<htmlcontenteditable> 24/127
29.6.2015 data:text/html,<htmlcontenteditable>
string:contenttobewritetofile
Returns
true:writeok.nil:thereiserror
Example
open'init.lua'in'a+'mode
file.open("init.lua","a+")
write'foobar'totheendofthefile
file.writeline('foobar')
file.close()
Seealso
file.open()
file.write()
BacktoIndex
file.read()
Description
readcontentoffilewhichisopenedbefore.
Syntax
file.read()
Parameters
ifnothingpassedin,readallbyteinfile.ifpassa
numbern,thenreadnbytefromfile,orEOFis
reached.ifpassastring"q",thenreaduntil'q'or
EOFisreached.
Returns
filecontentinstring
data:text/html,<htmlcontenteditable> 25/127
29.6.2015 data:text/html,<htmlcontenteditable>
returnnilwhenEOF.
Example
printthefirstlineof'init.lua'
file.open("init.lua","r")
print(file.read('\r'))
file.close()
printthefirst5byteof'init.lua'
file.open("init.lua","r")
print(file.read(5))
file.close()
Seealso
file.open()
file.close()
BacktoIndex
file.write()
Description
writestringtofile.
Syntax
file.write(string)
Parameters
string:contenttobewritetofile.
Returns
true:writeok.nil:thereiserror
Example
data:text/html,<htmlcontenteditable> 26/127
29.6.2015 data:text/html,<htmlcontenteditable>
open'init.lua'in'a+'mode
file.open("init.lua","a+")
write'foobar'totheendofthefile
file.write('foobar')
file.close()
Seealso
file.open()
file.writeline()
BacktoIndex
file.flush()
Description
flushtofile.
Syntax
file.flush()
Parameters
nil
Returns
nil
Example
open'init.lua'in'a+'mode
file.open("init.lua","a+")
write'foobar'totheendofthefile
file.write('foobar')
file.flush()
file.close()
Seealso
data:text/html,<htmlcontenteditable> 27/127
29.6.2015 data:text/html,<htmlcontenteditable>
file.open()
file.writeline()
BacktoIndex
file.seek()
Description
Setsandgetsthefileposition,measuredfromthe
beginningofthefile,tothepositiongivenbyoffset
plusabasespecifiedbythestringwhence.
Syntax
file.seek(whence,offset)
Parameters
whence:
"set":baseisposition0(beginningofthefile)
"cur":baseiscurrentposition(defaultvalue)
"end":baseisendoffile
offset:default0
Returns
success:returnsthefinalfileposition
fail:returnsnil
Example
open'init.lua'in'a+'mode
file.open("init.lua","a+")
write'foobar'totheendofthefile
file.write('foobar')
file.flush()
file.seek("set")
print(file.readline())
file.close()
data:text/html,<htmlcontenteditable> 28/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
file.open()
file.writeline()
BacktoIndex
file.list()
Description
listallfiles.
Syntax
file.list()
Parameters
nil
Returns
aluatablewhichcontainsthe{filename:filesize}
pairs
Example
l=file.list();
fork,vinpairs(l)do
print("name:"..k..",size:"..v)
end
Seealso
file.remove()
BacktoIndex
file.format()
data:text/html,<htmlcontenteditable> 29/127
29.6.2015 data:text/html,<htmlcontenteditable>
Description
formatfilesystem.
Syntax
file.format()
Parameters
nil
Returns
nil
Example
file.format()
Seealso
file.remove()
BacktoIndex
file.rename()
Description
renameafile.NOTE:thecurrentopenedfilewillbe
closed.
Syntax
file.rename(oldname,newname)
Parameters
oldname:oldfilename,directoriesarenotsupported
newname:newfilename,directoriesarenot
data:text/html,<htmlcontenteditable> 30/127
29.6.2015 data:text/html,<htmlcontenteditable>
supported
Returns
false:renamefailed.true:renameok.
Example
renamefile'temp.lua'to'init.lua'.
file.rename("temp.lua","init.lua")
Seealso
file.close()
BacktoIndex
file.fsinfo()
Description
Getfilesysteminfo
Syntax
file.fsinfo()
Parameters
nil
Returns
remaining(number)
used(number)
total(number)
Example
getfilesysteminfo
remaining,used,total=file.fsinfo()
data:text/html,<htmlcontenteditable> 31/127
29.6.2015 data:text/html,<htmlcontenteditable>
print("\nFilesysteminfo:\nTotal:"..total..
Seealso
BacktoIndex
wifimodule
CONSTANT
wifi.STATION,wifi.SOFTAP,wifi.STATIONAP
wifi.setmode()
Description
setupwifioperationmode.
wifi.STATIONiswhenthedeviceisconnected
toanotherwifirouter.Thisisoftendonetogive
thedeviceaccesstotheinternet.
wifi.SOFTAPiswhenthedeviceisactingas
ONLYanaccesspoint.Thismodewillallowyou
toseethedeviceinthelistofwifinetworks.In
thismodeyourcomputercanconnecttothe
devicecreatingalocalareanetwork.Unlessyou
changethevalue,theESP8266devicewillbe
givenalocalIPaddressof192.168.4.1and
assignyourcomputerthenextavailableIP,such
as:192.168.4.2.
wifi.STATIONAPisacombinationof
wifi.STATIONandwifi.SOFTAP.Itallowsyouto
createalocalwificonnectionANDconnectto
anotherwifirouter.
Syntax
data:text/html,<htmlcontenteditable> 32/127
29.6.2015 data:text/html,<htmlcontenteditable>
wifi.setmode(mode)
Parameters
mode:valueshouldbe:
wifi.STATION
wifi.SOFTAP
wifi.STATIONAP
Returns
currentmodeaftersetup
Example
wifi.setmode(wifi.STATION)
Seealso
wifi.getmode()
BacktoIndex
wifi.getmode()
Description
getwifioperationmode.
Syntax
wifi.getmode()
Parameters
nil
Returns
wifioperationmode
data:text/html,<htmlcontenteditable> 33/127
29.6.2015 data:text/html,<htmlcontenteditable>
Example
print(wifi.getmode())
Seealso
wifi.setmode()
BacktoIndex
wifi.getchannel()
Description
getcurrentwifichannel.
Syntax
wifi.getchannel()
Parameters
nil
Returns
currentwifichannel
Example
print(wifi.getchannel())
Seealso
BacktoIndex
wifi.setphymode()
Description
data:text/html,<htmlcontenteditable> 34/127
29.6.2015 data:text/html,<htmlcontenteditable>
Setupwifiphysicalmode.
wifi.PHYMODE_B802.11b,Morerange,Low
Transferrate,Morecurrentdraw
wifi.PHYMODE_G802.11g,Mediumrange,
Mediumtransferrate,Mediumcurrentdraw
wifi.PHYMODE_N802.11n,Leastrange,Fast
transferrate,Leastcurrentdraw(STATION
ONLY)InformationfromtheEspressifdatasheet
v4.3
Parameters
Tx802.11b,CCK11Mbps,POUT=+17dBm
Tx802.11g,OFDM54Mbps,POUT=+15dBm
Tx802.11n,MCS765Mbps,POUT=+13dBm
Rx802.11b,1024bytespacketlength,80dBm
Rx802.11g,1024bytespacketlength,70dBm
Rx802.11n,1024bytespacketlength,65dBm
Syntax
wifi.setphymode(mode)
Parameters
mode:valueshouldbe:
wifi.PHYMODE_B
wifi.PHYMODE_G
wifi.PHYMODE_N
Returns
Currentphysicalmodeaftersetup
Example
STATION
wifi.setphymode()
data:text/html,<htmlcontenteditable> 35/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
wifi.getphymode()
BacktoIndex
wifi.getphymode()
Description
getwifiphysicalmode.
Syntax
wifi.getmode()
Parameters
nil
Returns
wifiphysicalmode
1:wifi.PHYMODE_B
2:wifi.PHYMODE_G
3:wifi.PHYMODE_N
Example
print(wifi.getphymode())
Seealso
wifi.setphymode()
BacktoIndex
wifi.startsmart()
data:text/html,<htmlcontenteditable> 36/127
29.6.2015 data:text/html,<htmlcontenteditable>
Description
startstoautoconfiguration,ifsuccesssetupssid
andpwdautomatically.
Syntax
wifi.startsmart(channel,functionsucceed_callback())
Parameters
channel:1~13,startupchannelforsearching,ifnil,
defaultto6.20secondsforeachchannel.
succeed_callback:callbackfunctioncalledafter
configuration,whichiscalledwhengotpassword
andconnectedtoAP.
Returns
nil
Example
wifi.startsmart(6,function()end)
Seealso
wifi.stopsmart()
BacktoIndex
wifi.stopsmart()
Description
stoptheconfiguringprocess.
Syntax
wifi.stopsmart()
data:text/html,<htmlcontenteditable> 37/127
29.6.2015 data:text/html,<htmlcontenteditable>
Parameters
nil
Returns
nil
Example
wifi.stopsmart()
Seealso
wifi.startsmart()
BacktoIndex
wifi.sleeptype()
Description
configthesleeptypeforwifimodem.
Syntax
type_actual=wifi.sleeptype(type_need)
Parameters
type_need:
wifi.NONE_SLEEP,wifi.LIGHT_SLEEP,
wifi.MODEM_SLEEP
Returns
type_actual:
wifi.NONE_SLEEP,wifi.LIGHT_SLEEP,
wifi.MODEM_SLEEP
Example
data:text/html,<htmlcontenteditable> 38/127
29.6.2015 data:text/html,<htmlcontenteditable>
realtype=wifi.sleeptype(wifi.MODEM_SLEEP)
Seealso
node.dsleep()
BacktoIndex
wifi.sta.getconfig()
Description
Getwifistationconfiguration.
Note:Ifbssid_setisequalto0thenbssidis
irrelevant
Syntax
ssid,password,bssid_set,bssid=wifi.sta.getconfig()
Parameters
nil
Returns
ssid,password,bssid_set,bssid
Example
GetcurrentStationconfiguration
ssid,password,bssid_set,bssid=wifi.sta.getconfig
print("\nCurrentStationconfiguration:\nSSID:
.."\nPassword:"..password
.."\nBSSID_set:"..bssid_set
.."\nBSSID:"..bssid.."\n")
ssid,password,bssid_set,bssid=nil,nil,nil,
Seealso
data:text/html,<htmlcontenteditable> 39/127
29.6.2015 data:text/html,<htmlcontenteditable>
wifi.sta.connect()
wifi.sta.disconnect()
BacktoIndex
wifi.sta.config()
Description
Setwifistationconfiguration
Syntax
wifi.sta.config(ssid,password)
wifi.sta.config(ssid,password,auto)
wifi.sta.config(ssid,password,bssid)
wifi.sta.config(ssid,password,auto,bssid)
Parameters
ssid:stringwhichislessthan32bytes.
password:stringwhichislessthan64bytes.
auto:valueof0or1(Defaultis1)
0:Disableautoconnectandremain
disconnectedfromAccessPoint
1:Enableautoconnectandconnectto
AccessPoint.
bssid:StringthatcontainstheMACaddressof
theAccessPoint,(optional).
Youcansetbssidifyouhavemultiple
AccessPointswiththesamessid.
Note:ifyousetbssidforaspecificSSID
andwouldliketoconfigurestationto
connecttothesamessidonlywithoutthe
bssidrequirement,youMUSTfirstconfigure
tostationtoadifferentssidfirst,then
connecttothedesiredssid
Thefollowingformatsarevalid:
"DEC1A551F1ED"
"AC1D1CB10B22"
data:text/html,<htmlcontenteditable> 40/127
29.6.2015 data:text/html,<htmlcontenteditable>
"DEADBEEF7AC0"
Returns
nil
Example
ConnecttoAccessPointautomaticallywheninrange
wifi.sta.config("myssid","password")
ConnecttoAccessPoint,Userdecideswhentoconnect/disconnectto/fromAP
wifi.sta.config("myssid","mypassword",0)
wifi.sta.connect()
dosomewifistuff
wifi.sta.disconnect()
ConnecttospecificAccessPointautomaticallywheninrange
wifi.sta.config("myssid","mypassword","12:34:56:78:90:12
ConnecttospecificAccessPoint,Userdecideswhentoconnect/disconnectto/fromAP
wifi.sta.config("myssid","mypassword",0,"12:34:56:78:90:12
wifi.sta.connect()
dosomewifistuff
wifi.sta.disconnect()
Seealso
wifi.sta.connect()
wifi.sta.disconnect()
BacktoIndex
wifi.sta.connect()
Description
connecttoAPinstationmode.
Syntax
wifi.sta.connect()
data:text/html,<htmlcontenteditable> 41/127
29.6.2015 data:text/html,<htmlcontenteditable>
Parameters
nil
Returns
nil
Example
wifi.sta.connect()
Seealso
wifi.sta.disconnect()
wifi.sta.config()
BacktoIndex
wifi.sta.disconnect()
Description
disconnectfromAPinstationmode.
Syntax
wifi.sta.disconnect()
Parameters
nil
Returns
nil
Example
wifi.sta.disconnect()
data:text/html,<htmlcontenteditable> 42/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
wifi.sta.config()
wifi.sta.connect()
BacktoIndex
wifi.sta.autoconnect()
Description
autoconnecttoAPinstationmode.
Syntax
wifi.sta.autoconnect(auto)
Parameters
auto:0todisableautoconnecting.1toenableauto
connecting
Returns
nil
Example
wifi.sta.autoconnect()
Seealso
wifi.sta.config()
wifi.sta.connect()
wifi.sta.disconnect()
BacktoIndex
wifi.sta.getip()
data:text/html,<htmlcontenteditable> 43/127
29.6.2015 data:text/html,<htmlcontenteditable>
Description
getip,netmask,gatewayaddressinstationmode.
Syntax
wifi.sta.getip()
Parameters
nil
Returns
ip,netmask,gatewayaddressinstring,for
example:"192.168.0.111"
returnnilifip="0.0.0.0".
Example
printcurrentip,netmask,gateway
print(wifi.sta.getip())
192.168.0.111255.255.255.0192.168.0.1
ip=wifi.sta.getip()
print(ip)
192.168.0.111
ip,nm=wifi.sta.getip()
print(nm)
255.255.255.0
Seealso
wifi.sta.getmac()
BacktoIndex
wifi.sta.setip()
Description
setip,netmask,gatewayaddressinstationmode.
data:text/html,<htmlcontenteditable> 44/127
29.6.2015 data:text/html,<htmlcontenteditable>
Syntax
wifi.sta.setip(cfg)
Parameters
cfg:tablecontainip,netmask,andgateway
{
ip="192.168.0.111",
netmask="255.255.255.0",
gateway="192.168.0.1"
}
Returns
trueifsuccess,falseiffail.
Example
cfg=
{
ip="192.168.0.111",
netmask="255.255.255.0",
gateway="192.168.0.1"
}
wifi.sta.setip(cfg)
Seealso
wifi.sta.setmac()
BacktoIndex
wifi.sta.getmac()
Description
getmacaddressinstationmode.
Syntax
data:text/html,<htmlcontenteditable> 45/127
29.6.2015 data:text/html,<htmlcontenteditable>
wifi.sta.getmac()
Parameters
nil
Returns
macaddressinstring,forexample:"183344FE55
BB"
Example
printcurrentmacaddress
print(wifi.sta.getmac())
Seealso
wifi.sta.getip()
BacktoIndex
wifi.sta.setmac()
Description
setmacaddressinstationmode.
Syntax
wifi.sta.setmac(mac)
Parameters
macaddressinstring,for
example:"DE:AD:BE:EF:7A:C0"
Returns
trueifsuccess,falseiffail.
data:text/html,<htmlcontenteditable> 46/127
29.6.2015 data:text/html,<htmlcontenteditable>
Example
print(wifi.sta.setmac("DE:AD:BE:EF:7A:C0"))
Seealso
wifi.sta.setip()
BacktoIndex
wifi.sta.getap()
Description
scanandgetaplistasaluatableintocallback
function.
Syntax
wifi.sta.getap(function(table))wifi.sta.getap(cfg,
function(table))wifi.sta.getap(format,function(table))
wifi.sta.getap(cfg,format,function(table))
Parameters
cfg:tablethatcontainsscanconfiguration
ssid:ssid==nil,don'tfilterssid.
bssid:bssid==nil,don'tfilterbssid.
channel:channel==0,scanallchannels,
otherwisescansetchannel.(Defaultis0)
show_hidden:show_hidden==1,getinfo
forrouterwithhiddenssid.(Defaultis0)
format:Selectoutputtableformat,0or1isvalid.
(0isDefault)
0:Oldformat(SSID:Authmode,RSSI,
BSSID,Channel)
NOTE:Whenusingoldformatfortable
output,anyduplicateSSIDswillbe
data:text/html,<htmlcontenteditable> 47/127
29.6.2015 data:text/html,<htmlcontenteditable>
discarded.
1:Newformat(BSSID:SSID,RSSI,
Authmode,Channel)
function(table):acallbackfunctiontoreceiveap
tablewhenscanisdone
Thisfunctionreceivesatable,thekeyisthe
ssid,valueisotherinfoinformat:
authmode,rssi,bssid,channel
Ifyouareusingthenewoutputformat,the
keyisthebssid,valueisotherinfoin
format:ssid,rssi,authmode,channel
Returns
nil
Example
printaplist
functionlistap(t)
fork,vinpairs(t)do
print(k..":"..v)
end
end
wifi.sta.getap(listap)
PrintAPlistthatiseasiertoread
functionlistap(t)(SSID:Authmode,RSSI,BSSID,Channel)
print("\n\t\t\tSSID\t\t\t\t\tBSSID\t\t\tRSSI
forssid,vinpairs(t)do
localauthmode,rssi,bssid,channel=string.match
print(string.format("%32.s",ssid).."\t"..bssid
end
end
wifi.sta.getap(listap)
NOTE:Therestoftheexamplesusethenewstyleoutputformat
printaplist
functionlistap(t)
fork,vinpairs(t)do
print(k..":"..v)
end
end
data:text/html,<htmlcontenteditable> 48/127
29.6.2015 data:text/html,<htmlcontenteditable>
wifi.sta.getap(1,listap)
PrintAPlistthatiseasiertoread
functionlistap(t)(SSID:Authmode,RSSI,BSSID,Channel)
print("\n\t\t\tSSID\t\t\t\t\tBSSID\t\t\tRSSI
forbssid,vinpairs(t)do
localssid,rssi,authmode,channel=string.match
print(string.format("%32.s",ssid).."\t"..bssid
end
end
wifi.sta.getap(1,listap)
checkforspecificAP
functionlistap(t)
print("\n\t\t\tSSID\t\t\t\t\tBSSID\t\t\tRSSI
forbssid,vinpairs(t)do
localssid,rssi,authmode,channel=string.match
print(string.format("%32.s",ssid).."\t"..bssid
end
end
scan_cfg={}
scan_cfg.ssid="myssid"
scan_cfg.bssid="AA:AA:AA:AA:AA:AA"
scan_cfg.channel=0
scan_cfg.show_hidden=1
wifi.sta.getap(scan_cfg,1,listap)
getRSSIforcurrentlyconfiguredAP
functionlistap(t)
forbssid,vinpairs(t)do
localssid,rssi,authmode,channel=string.match
print("CURRENTRSSIIS:"..rssi)
end
end
ssid,tmp,bssid_set,bssid=wifi.sta.getconfig()
scan_cfg={}
scan_cfg.ssid=ssid
ifbssid_set==1thenscan_cfg.bssid=bssidelsescan_cfg.
scan_cfg.channel=wifi.getchannel()
scan_cfg.show_hidden=0
ssid,tmp,bssid_set,bssid=nil,nil,nil,nil
wifi.sta.getap(scan_cfg,1,listap)
Seealso
wifi.sta.getip()
data:text/html,<htmlcontenteditable> 49/127
29.6.2015 data:text/html,<htmlcontenteditable>
BacktoIndex
wifi.sta.status()
Description
getcurrentstatusinstationmode.
Syntax
wifi.sta.status()
Parameters
nil
Returns
number0~5
0:STATION_IDLE,
1:STATION_CONNECTING,
2:STATION_WRONG_PASSWORD,
3:STATION_NO_AP_FOUND,
4:STATION_CONNECT_FAIL,
5:STATION_GOT_IP.
Seealso
BacktoIndex
wifi.sta.getbroadcast()
Description
getgetbroadcastaddressinstationmode.
Syntax
data:text/html,<htmlcontenteditable> 50/127
29.6.2015 data:text/html,<htmlcontenteditable>
wifi.sta.getbroadcast()
Parameters
nil
Returns
getbroadcastaddressinstring,for
example:"192.168.0.255"
returnnilifip="0.0.0.0".
Example
bc=wifi.sta.getbroadcast()
print(bc)
192.168.0.255
Seealso
wifi.sta.getip()
BacktoIndex
wifi.apmodule
wifi.ap.config()
Description
setssidandpwdinapmode.Besuretomakethe
pwdvalueatleast8characters!Ifyoudon'tmake
thepwdvalue8characters,itwilldefaulttono
passwordandnotsetthevalueforssid.Itwillstill
workasanaccesspoint,butyouwillseeanamein
yourwifilistlike:ESP_9997C3
Syntax
data:text/html,<htmlcontenteditable> 51/127
29.6.2015 data:text/html,<htmlcontenteditable>
wifi.ap.config(cfg)
Parameters
cfg:luatabletosetupap.
Example:
cfg={}
cfg.ssid="myssid"
cfg.pwd="mypassword"
wifi.ap.config(cfg)
Returns
nil
Seealso
BacktoIndex
wifi.ap.getip()
Description
getip,netmask,gatewayinapmode.
Syntax
wifi.ap.getip()
Parameters
nil
Returns
ip,netmask,gatewayaddressinstring,for
example:"192.168.0.111"
data:text/html,<htmlcontenteditable> 52/127
29.6.2015 data:text/html,<htmlcontenteditable>
returnnilifip="0.0.0.0".
Example
printcurrentip,netmask,gateway
print(wifi.ap.getip())
192.168.4.1255.255.255.0192.168.4.1
ip=wifi.ap.getip()
print(ip)
192.168.4.1
ip,nm=wifi.ap.getip()
print(nm)
255.255.255.0
ip,nm,gw=wifi.ap.getip()
print(gw)
192.168.4.1
Seealso
wifi.ap.getmac()
BacktoIndex
wifi.ap.setip()
Description
setip,netmask,gatewayaddressinapmode.
Syntax
wifi.ap.setip(cfg)
Parameters
cfg:tablecontainip,netmask,andgateway
{
ip="192.168.1.1",
netmask="255.255.255.0",
gateway="192.168.1.1"
}
data:text/html,<htmlcontenteditable> 53/127
29.6.2015 data:text/html,<htmlcontenteditable>
Returns
trueifsuccess,falseiffail.
Example
cfg=
{
ip="192.168.1.1",
netmask="255.255.255.0",
gateway="192.168.1.1"
}
wifi.ap.setip(cfg)
Seealso
wifi.ap.setmac()
BacktoIndex
wifi.ap.getmac()
Description
getmacaddressinapmode.
Syntax
wifi.ap.getmac()
Parameters
nil
Returns
macaddressinstring,forexample:"1A3344FE55
BB"
Example
data:text/html,<htmlcontenteditable> 54/127
29.6.2015 data:text/html,<htmlcontenteditable>
wifi.ap.getmac()
Seealso
wifi.ap.getip()
BacktoIndex
wifi.ap.setmac()
Description
setmacaddressinapmode.
Syntax
wifi.ap.setmac(mac)
Parameters
macaddressinbytestring,forexample:"AC1D1C
B10B22"
Returns
trueifsuccess,falseiffail.
Example
print(wifi.ap.setmac("AC1D1CB10B22"))
Seealso
wifi.ap.setip()
BacktoIndex
wifi.ap.getbroadcast()
data:text/html,<htmlcontenteditable> 55/127
29.6.2015 data:text/html,<htmlcontenteditable>
Description
getgetbroadcastaddressinapmode.
Syntax
wifi.ap.getbroadcast()
Parameters
nil
Returns
getbroadcastaddressinstring,for
example:"192.168.0.255"
returnnilifip="0.0.0.0".
Example
bc=wifi.ap.getbroadcast()
print(bc)
192.168.0.255
Seealso
wifi.ap.getip()
BacktoIndex
timermodule
tmr.delay()
Description
delayusmicroseconds.
Syntax
data:text/html,<htmlcontenteditable> 56/127
29.6.2015 data:text/html,<htmlcontenteditable>
tmr.delay(us)
Parameters
us:delaytimeinmicrosecond
Returns
nil
Example
delay100us
tmr.delay(100)
Seealso
tmr.now()
BacktoIndex
tmr.now()
Description
returnthecurrentvalueofsystemcounter:uint31,
us.
Syntax
tmr.now()
Parameters
nil
Returns
uint31:valueofcounter
Example
data:text/html,<htmlcontenteditable> 57/127
29.6.2015 data:text/html,<htmlcontenteditable>
printcurrentvalueofcounter
print(tmr.now())
Seealso
tmr.delay()
BacktoIndex
tmr.alarm()
Description
alarmtime.
Syntax
tmr.alarm(id,interval,repeat,functiondo())
Parameters
id:0~6,alarmerid.Interval:alarmtime,unit:
millisecond
repeat:0onetimealarm,1repeat
functiondo():callbackfunctionforalarmtimedout
Returns
nil
Example
print"helloworld"every1000ms
tmr.alarm(0,1000,1,function()print("helloworld
Seealso
tmr.now()
data:text/html,<htmlcontenteditable> 58/127
29.6.2015 data:text/html,<htmlcontenteditable>
BacktoIndex
tmr.stop()
Description
stopalarm.
Syntax
tmr.stop(id)
Parameters
id:0~6,alarmerid.
Returns
nil
Example
print"helloworld"every1000ms
tmr.alarm(1,1000,1,function()print("helloworld
somethingelse
stopalarm
tmr.stop(1)
Seealso
tmr.now()
BacktoIndex
tmr.wdclr()
Description
data:text/html,<htmlcontenteditable> 59/127
29.6.2015 data:text/html,<htmlcontenteditable>
clearsystemwatchdogcounter.
Syntax
tmr.wdclr()
Parameters
nil.
Returns
nil
Example
fori=1,10000do
print(i)
tmr.wdclr()shouldcalltmr.wdclr()inalonglooptoavoidhardwareresetcaused
end
Seealso
tmr.delay()
BacktoIndex
tmr.time()
Description
returnrtctimesincestartupinsecond,uint31form.
Syntax
tmr.time()
Parameters
nil.
data:text/html,<htmlcontenteditable> 60/127
29.6.2015 data:text/html,<htmlcontenteditable>
Returns
number
Example
Seealso
tmr.now()
BacktoIndex
GPIOmodule
CONSTANT
gpio.OUTPUT,gpio.INPUT,gpio.INT,gpio.HIGH,
gpio.LOW
gpio.mode()
Description
initializepintoGPIOmode,setthepinin/outmode,
internalpullup.
Syntax
gpio.mode(pin,mode,pullup)
Parameters
pin:0~12,IOindex
mode:gpio.OUTPUTorgpio.INPUT,or
gpio.INT(interruptmode)pullup:gpio.PULLUPor
gpio.FLOAT,default:gpio.FLOAT.
Returns
data:text/html,<htmlcontenteditable> 61/127
29.6.2015 data:text/html,<htmlcontenteditable>
nil
Example
setgpio0asoutput.
gpio.mode(0,gpio.OUTPUT)
Seealso
gpio.read()
BacktoIndex
gpio.read()
Description
readpinvalue.
Syntax
gpio.read(pin)
Parameters
pin:0~12,IOindex
Returns
number:0low,1high
Example
readvalueofgpio0.
gpio.read(0)
Seealso
gpio.mode()
data:text/html,<htmlcontenteditable> 62/127
29.6.2015 data:text/html,<htmlcontenteditable>
BacktoIndex
gpio.write()
Description
setpinvalue.
Syntax
gpio.write(pin)
Parameters
pin:0~12,IOindex
level:gpio.HIGHorgpio.LOW
Returns
nil
Example
setpinindex1toGPIOmode,andsetthepintohigh.
pin=1
gpio.mode(pin,gpio.OUTPUT)
gpio.write(pin,gpio.HIGH)
Seealso
gpio.mode()
gpio.read()
BacktoIndex
gpio.trig()
Description
data:text/html,<htmlcontenteditable> 63/127
29.6.2015 data:text/html,<htmlcontenteditable>
settheinterruptcallbackfunctionforpin.
Syntax
gpio.trig(pin,type,function(level))
Parameters
pin:1~12,IOindex,pinD0doesnotsupport
Interrupt.
type:"up","down","both","low","high",which
representrisingedge,fallingedge,bothedge,low
level,highleveltrigmodeseparately.
function(level):callbackfunctionwhentriggered.The
gpiolevelistheparam.Usepreviouscallback
functionifundefinedhere.
Returns
nil
Example
usepin0astheinputpulsewidthcounter
pulse1=0
du=0
gpio.mode(1,gpio.INT)
functionpin1cb(level)
du=tmr.now()pulse1
print(du)
pulse1=tmr.now()
iflevel==1thengpio.trig(1,"down")elsegpio.
end
gpio.trig(1,"down",pin1cb)
Seealso
gpio.mode()
gpio.write()
BacktoIndex
data:text/html,<htmlcontenteditable> 64/127
29.6.2015 data:text/html,<htmlcontenteditable>
PWMmodule
pwm.setup()
Description
setpintoPWMmode.Only3pinscanbesetto
PWMmodeatthemost.
Syntax
pwm.setup(pin,clock,duty)
Parameters
pin:1~12,IOindex
clock:1~1000,pwmfrequency
duty:0~1023,pwmdutycycle,max1023(10bit)
Returns
nil
Example
setpinindex1aspwmoutput,frequencyis100Hz,dutycycleishalf.
pwm.setup(1,100,512)
Seealso
pwm.start()
BacktoIndex
pwm.close()
Description
data:text/html,<htmlcontenteditable> 65/127
29.6.2015 data:text/html,<htmlcontenteditable>
quitPWMmodeforspecifiedpin.
Syntax
pwm.close(pin)
Parameters
pin:1~12,IOindex
Returns
nil
Example
pwm.close(1)
Seealso
pwm.start()
BacktoIndex
pwm.start()
Description
pwmstarts,youcandetectthewaveformonthe
gpio.
Syntax
pwm.start(pin)
Parameters
pin:1~12,IOindex
Returns
data:text/html,<htmlcontenteditable> 66/127
29.6.2015 data:text/html,<htmlcontenteditable>
nil
Example
pwm.start(1)
Seealso
pwm.stop()
BacktoIndex
pwm.stop()
Description
pausetheoutputofPWMwaveform.
Syntax
pwm.stop(pin)
Parameters
pin:1~12,IOindex
Returns
nil
Example
pwm.stop(1)
Seealso
pwm.start()
BacktoIndex
data:text/html,<htmlcontenteditable> 67/127
29.6.2015 data:text/html,<htmlcontenteditable>
pwm.setclock()
Description
setpwmfrequencyforpin.
Note:setuppwmfrequencywillsynchronously
changeothersifthereareany.OnlyonePWM
frequencycanbeallowedforthesystem.
Syntax
pwm.setclock(pin,clock)
Parameters
pin:1~12,IOindex.
clock:1~1000,pwmfrequency.
Returns
nil
Example
pwm.setclock(1,100)
Seealso
pwm.getclock()
BacktoIndex
pwm.getclock()
Description
getpwmfrequencyofpin.
Syntax
data:text/html,<htmlcontenteditable> 68/127
29.6.2015 data:text/html,<htmlcontenteditable>
pwm.getclock(pin)
Parameters
pin:1~12,IOindex.
Returns
number:pwmfrequencyofpin
Example
print(pwm.getclock(1))
Seealso
pwm.setclock()
BacktoIndex
pwm.setduty()
Description
setdutyclycleforpin.
Syntax
pwm.setduty(pin,duty)
Parameters
pin:1~12,IOindex
duty:0~1023,pwmdutycycle,max1023(10bit).
Returns
nil
Example
data:text/html,<htmlcontenteditable> 69/127
29.6.2015 data:text/html,<htmlcontenteditable>
pwm.setduty(1,512)
Seealso
pwm.getduty()
BacktoIndex
pwm.getduty()
Description
getdutyclycleforpin.
Syntax
pwm.getduty(pin)
Parameters
pin:1~12,IOindex
Returns
number:dutycycle,max1023.
Example
D1isconnectedtogreenled
D2isconnectedtoblueled
D3isconnectedtoredled
pwm.setup(1,500,512)
pwm.setup(2,500,512)
pwm.setup(3,500,512)
pwm.start(1)
pwm.start(2)
pwm.start(3)
functionled(r,g,b)
pwm.setduty(1,g)
pwm.setduty(2,b)
pwm.setduty(3,r)
end
led(512,0,0)setledtored
data:text/html,<htmlcontenteditable> 70/127
29.6.2015 data:text/html,<htmlcontenteditable>
led(0,0,512)setledtoblue.
Seealso
pwm.setduty()
BacktoIndex
netmodule
CONSTANT
net.TCP,net.UDP
net.createServer()
Description
createaserver.
Syntax
net.createServer(type,timeout)
Parameters
type:net.TCPornet.UDP
timeout:foraTCPserver,timeoutis1~28800
seconds,forainactiveclienttodisconnected.
Returns
net.serversubmodule
Example
net.createServer(net.TCP,30)30stimeout
data:text/html,<htmlcontenteditable> 71/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
net.createConnection()
BacktoIndex
net.createConnection()
Description
Createaclient.
Syntax
net.createConnection(type,secure)
Parameters
type:net.TCPornet.UDP
secure:1or0,1forssllink,0fornormallink
Returns
net.socketsubmodule
Example
net.createConnection(net.UDP,0)
Seealso
net.createServer()
BacktoIndex
net.servermodule
net.server:listen()
data:text/html,<htmlcontenteditable> 72/127
29.6.2015 data:text/html,<htmlcontenteditable>
Description
listenonportfrom[ip]address.
Syntax
net.server.listen(port,[ip],function(net.socket))
Parameters
port:portnumber
ip:ipaddressstring,canbeomitted
function(net.socket):callbackfunction,passtoCaller
functionasparamifaconnectioniscreated
successfully
Returns
nil
Example
createaserver
sv=net.createServer(net.TCP,30)30stimeoutforainactiveclient
serverlistenon80,ifdatareceived,printdatatoconsole,andsend"helloworld"
sv:listen(80,function(c)
c:on("receive",function(c,pl)print(pl)end
c:send("helloworld")
end)
Seealso
net.createServer()
BacktoIndex
net.server:close()
Description
closeserver.
data:text/html,<htmlcontenteditable> 73/127
29.6.2015 data:text/html,<htmlcontenteditable>
Syntax
net.server.close()
Parameters
nil
Returns
nil
Example
createaserver
sv=net.createServer(net.TCP,30)
closeserver
sv:close()
Seealso
net.createServer()
BacktoIndex
net.socketmodule
net.socket:connect()
Description
connecttoremote.
Syntax
connect(port,ip/domain)
Parameters
data:text/html,<htmlcontenteditable> 74/127
29.6.2015 data:text/html,<htmlcontenteditable>
port:portnumber
ip:ipaddressordomainnameinstring
Returns
nil
Seealso
net.socket:on()BacktoIndex
net.socket:send()
Description
senddatatoremoteviaconnection.
Syntax
send(string,function(sent))
Parameters
string:datainstringwhichwillbesenttoremote
function(sent):callbackfunctionforsendingstring
Returns
nil
Seealso
net.socket:on()
BacktoIndex
net.socket:on()
Description
registercallbackfunctionforevent.
data:text/html,<htmlcontenteditable> 75/127
29.6.2015 data:text/html,<htmlcontenteditable>
Syntax
on(event,functioncb())
Parameters
event:string,whichcanbe:"connection",
"reconnection","disconnection","receive","sent"
functioncb(net.socket,[string]):callback
function.Thefirstparamisthesocket.
Ifeventis"receive",thesecondparamisreceived
datainstring.
Returns
nil
Example
sk=net.createConnection(net.TCP,0)
sk:on("receive",function(sck,c)print(c)end
sk:connect(80,"192.168.0.66")
sk:send("GET/HTTP/1.1\r\nHost:192.168.0.66\r\n
Seealso
net.createServer()
BacktoIndex
net.socket:close()
Description
closesocket.
Syntax
close()
data:text/html,<htmlcontenteditable> 76/127
29.6.2015 data:text/html,<htmlcontenteditable>
Parameters
nil
Returns
nil
Seealso
net.createServer()
BacktoIndex
net.socket:dns()
Description
getdomainip
Syntax
dns(domain,function(net.socket,ip))
Parameters
domain:domainname.
function(net.socket,ip):callbackfunction.Thefirst
paramisthesocket,thesecondparamistheip
addressinstring.
Returns
nil
Example
sk=net.createConnection(net.TCP,0)
sk:dns("www.nodemcu.com",function(conn,ip)print
sk=nil
data:text/html,<htmlcontenteditable> 77/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
net.createServer()
BacktoIndex
i2cmodule
CONSTANT
i2c.SLOW,i2c.TRANSMITTER,i2c.RECEIVER.
FAST400kisnotsupportedfornow.
i2c.setup()
Description
initializei2c.
Syntax
i2c.setup(id,pinSDA,pinSCL,speed)
Parameters
id=0
pinSDA:1~12,IOindex
pinSCL:1~12,IOindex
speed:i2c.SLOW
Returns
speed:thesetedspeed.
Seealso
i2c.read()
BacktoIndex
data:text/html,<htmlcontenteditable> 78/127
29.6.2015 data:text/html,<htmlcontenteditable>
i2c.start()
Description
starti2ctransporting.
Syntax
i2c.start(id)
Parameters
id=0
Returns
nil
Seealso
i2c.read()
BacktoIndex
i2c.stop()
Description
stopi2ctransporting.
Syntax
i2c.stop(id)
Parameters
id=0
Returns
nil
data:text/html,<htmlcontenteditable> 79/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
i2c.read()
BacktoIndex
i2c.address()
Description
setupi2caddressandread/writemode.
Syntax
i2c.address(id,device_addr,direction)
Parameters
id=0
device_addr:deviceaddress.
direction:i2c.TRANSMITTERforwritingmode,i2c.
RECEIVERforreadingmode
Returns
true:getackfalse:noackget
Seealso
i2c.read()
BacktoIndex
i2c.write()
Description
writedatatoi2c,datacanbemultinumbers,stringor
luatable.
Syntax
data:text/html,<htmlcontenteditable> 80/127
29.6.2015 data:text/html,<htmlcontenteditable>
i2c.write(id,data1,data2,...)
Parameters
id=0
data:datacanbenumbers,stringorluatable.
Returns
number:numberofbyteswrote.
Example
i2c.write(0,"hello","world")
Seealso
i2c.read()
BacktoIndex
i2c.read()
Description
readdataforlenbytes.
Syntax
i2c.read(id,len)
Parameters
id=0
len:datalength
Returns
string:datareceived.
Example
data:text/html,<htmlcontenteditable> 81/127
29.6.2015 data:text/html,<htmlcontenteditable>
id=0
sda=1
scl=2
initializei2c,setpin1assda,setpin2asscl
i2c.setup(id,sda,scl,i2c.SLOW)
userdefinedfunction:readfromreg_addrcontentofdev_addr
functionread_reg(dev_addr,reg_addr)
i2c.start(id)
i2c.address(id,dev_addr,i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id,dev_addr,i2c.RECEIVER)
c=i2c.read(id,1)
i2c.stop(id)
returnc
end
getcontentofregister0xAAofdevice0x77
reg=read_reg(0x77,0xAA)
print(string.byte(reg))
Seealso
i2c.write()
BacktoIndex
adcmodule
CONSTANT
none
adc.read()
Description
data:text/html,<htmlcontenteditable> 82/127
29.6.2015 data:text/html,<htmlcontenteditable>
readadcvalueofid,esp8266hasonlyone10bit
adc,id=0,pinTOUT
Syntax
adc.read(id)
Parameters
id=0
Returns
adcvalue
Seealso
BacktoIndex
adc.readvdd33()
Description
Readingvdd33pinvoltage
Syntax
adc.readvdd33()
Parameters
noparameters
Returns
mV
Example
print(adc.readvdd33())
data:text/html,<htmlcontenteditable> 83/127
29.6.2015 data:text/html,<htmlcontenteditable>
output
3345
v=adc.readvdd33()/1000
print(v)
v=nil
output
3.315
Seealso
BacktoIndex
uartmodule
CONSTANT
none
uart.setup()
Description
setupuart'sbaud,databits,parity,stopbits,echo.
Syntax
uart.setup(id,baud,databits,parity,stopbits,echo)
Parameters
id=0,only1uartsupported.
baud=300,600,1200,2400,4800,9600,19200,
data:text/html,<htmlcontenteditable> 84/127
29.6.2015 data:text/html,<htmlcontenteditable>
38400,57600,74880,115200,230400,460800,
921600,1843200,2686400.
databits=5,6,7,8.
parity=0(none).
stopbits=1(1stopbit),2(2stopbit).
echo=0(closeechoback).
Returns
baud.
Seealso
BacktoIndex
uart.on()
Description
setthecallbackfunctiontotheuartevent,
"data"eventsupported,meansthereisdatainput
fromuart.
Syntax
uart.on(method,[number/end_char],[function],
[run_input])
Parameters
method="data",thereisdatainputfromuart.
number/end_char:ifpassinanumbernifn=0,will
receiveeverycharinbuffer.
ifpassinaonecharstring"c",thecallbackwillcalled
when"c"isencounterd,ormaxn=255received.
function:callbackfunction,event"data"hasa
callbacklikethis:function(data)end
run_input:0or1,0:inputfromuartwillnotgointo
data:text/html,<htmlcontenteditable> 85/127
29.6.2015 data:text/html,<htmlcontenteditable>
luainterpreter,canacceptbinarydata.
1:inputfromuartwillgointoluainterpreter,andrun.
Returns
nil
Example
when4charsisreceived.
uart.on("data",4,
function(data)
print("receivefromuart:",data)
ifdata=="quit"then
uart.on("data")
end
end,0)
when'\r'isreceived.
uart.on("data","\r",
function(data)
print("receivefromuart:",data)
ifdata=="quit\r"then
uart.on("data")
end
end,0)
Seealso
BacktoIndex
uart.write()
Description
writestringtouart.
Syntax
uart.write(id,string1,string2...)
data:text/html,<htmlcontenteditable> 86/127
29.6.2015 data:text/html,<htmlcontenteditable>
Parameters
id=0,only1uartsupported.
string1..n:stringwritetouart.
Returns
nil
Seealso
BacktoIndex
onewiremodule
CONSTANT
none
ow.setup()
Description
setapininonewiremode.
Syntax
ow.setup(pin)
Parameters
pin:1~12,IOindex
Returns
nil
data:text/html,<htmlcontenteditable> 87/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
BacktoIndex
ow.reset()
Description
Performa1Wireresetcycle.
Syntax
ow.reset(pin)
Parameters
pin:1~12,IOindex
Returns
number:Returns1ifadevicerespondswitha
presencepulse.Returns0ifthereisnodeviceorthe
busisshortedorotherwiseheldlowformorethan
250uS
Seealso
BacktoIndex
ow.skip()
Description
Issuea1Wireromskipcommand,toaddressallon
bus.
Syntax
data:text/html,<htmlcontenteditable> 88/127
29.6.2015 data:text/html,<htmlcontenteditable>
ow.skip(pin)
Parameters
pin:1~12,IOindex
Returns
nil
Seealso
BacktoIndex
ow.select()
Description
Issuea1Wireromselectcommand,makesureyou
dotheow.reset(pin)first.
Syntax
ow.select(pin,rom)
Parameters
pin:1~12,IOindex
rom:stringvalue,len8,romcodeofthesalvedevice
Returns
nil
Example
18b20Example
pin=9
ow.setup(pin)
count=0
data:text/html,<htmlcontenteditable> 89/127
29.6.2015 data:text/html,<htmlcontenteditable>
repeat
count=count+1
addr=ow.reset_search(pin)
addr=ow.search(pin)
tmr.wdclr()
until((addr~=nil)or(count>100))
if(addr==nil)then
print("Nomoreaddresses.")
else
print(addr:byte(1,8))
crc=ow.crc8(string.sub(addr,1,7))
if(crc==addr:byte(8))then
if((addr:byte(1)==0x10)or(addr:byte(1)==
print("DeviceisaDS18S20familydevice.")
repeat
ow.reset(pin)
ow.select(pin,addr)
ow.write(pin,0x44,1)
tmr.delay(1000000)
present=ow.reset(pin)
ow.select(pin,addr)
ow.write(pin,0xBE,1)
print("P="..present)
data=nil
data=string.char(ow.read(pin))
fori=1,8do
data=data..string.char(ow.read(pin))
end
print(data:byte(1,9))
crc=ow.crc8(string.sub(data,1,8))
print("CRC="..crc)
if(crc==data:byte(9))then
t=(data:byte(1)+data:byte(2)*256
t1=t/10000
t2=t%10000
print("Temperature="..t1.."."..t2.."Centigrade
end
tmr.wdclr()
untilfalse
else
print("Devicefamilyisnotrecognized.")
end
else
print("CRCisnotvalid!")
end
end
data:text/html,<htmlcontenteditable> 90/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
BacktoIndex
ow.write()
Description
Writeabyte.If'power'is1thenthewireisheldhigh
attheendforparasiticallypowereddevices.Youare
responsibleforeventuallydepoweringitbycalling
depower()ordoinganotherreadorwrite.
Syntax
ow.write(pin,v,power)
Parameters
pin:1~12,IOindex
v:bytetobewrittentosalvedevice
power:1forwirebeingheldhighforparasitically
powereddevices.
Returns
nil
Example
Seealso
BacktoIndex
ow.write_bytes()
data:text/html,<htmlcontenteditable> 91/127
29.6.2015 data:text/html,<htmlcontenteditable>
Description
Writemultibytes.If'power'is1thenthewireisheld
highattheendforparasiticallypowereddevices.
Youareresponsibleforeventuallydepoweringitby
callingdepower()ordoinganotherreadorwrite.
Syntax
ow.write_bytes(pin,buf,power)
Parameters
pin:1~12,IOindex
buf:stringtobewrittentosalvedevice
power:1forwirebeingheldhighforparasitically
powereddevices.
Returns
nil
Example
Seealso
BacktoIndex
ow.read()
Description
readabyte.
Syntax
ow.read(pin)
Parameters
data:text/html,<htmlcontenteditable> 92/127
29.6.2015 data:text/html,<htmlcontenteditable>
pin:1~12,IOindex
Returns
bytereadfromslavedevice.
Example
Seealso
BacktoIndex
ow.read_bytes()
Description
readmultibytes.
Syntax
ow.read_bytes(pin,size)
Parameters
pin:1~12,IOindex
size:numberofbytestobereadfromslavedevice.
Returns
string:bytesreadfromslavedevice.
Example
Seealso
BacktoIndex
data:text/html,<htmlcontenteditable> 93/127
29.6.2015 data:text/html,<htmlcontenteditable>
ow.depower()
Description
Stopforcingpowerontothebus.Youonlyneedto
dothisifyouusedthe'power'flagtoow.write()or
usedaow.write_bytes()andaren'tabouttodo
anotherreadorwrite.
Syntax
ow.depower(pin)
Parameters
pin:1~12,IOindex
Example
Returns
nil
Seealso
BacktoIndex
ow.reset_search()
Description
Clearthesearchstatesothatitwillstartfromthe
beginningagain.
Syntax
ow.reset_search(pin)
Parameters
data:text/html,<htmlcontenteditable> 94/127
29.6.2015 data:text/html,<htmlcontenteditable>
pin:1~12,IOindex
Returns
nil
Example
Seealso
BacktoIndex
ow.target_search()
Description
Setupthesearchtofindthedevicetype'family_code'
onthenextcalltoow.search()ifitispresent.
Syntax
ow.target_search(pin,family_code)
Parameters
pin:1~12,IOindex
family_code:byteforfamilycode.
Returns
nil
Example
Seealso
BacktoIndex
data:text/html,<htmlcontenteditable> 95/127
29.6.2015 data:text/html,<htmlcontenteditable>
ow.search()
Description
Lookforthenextdevice.
Syntax
ow.search(pin)
Parameters
pin:1~12,IOindex
Returns
ifsucceedreturnastringlengthof8,whichcontain
theromcodeofslavedevice.
iffailedinsearchingnextdevicereturnnil.
Example
Seealso
BacktoIndex
ow.crc8()
Description
ComputeaDallasSemiconductor8bitCRC,these
areusedintheROMandscratchpadregisters.
Syntax
ow.crc8(buf)
Parameters
data:text/html,<htmlcontenteditable> 96/127
29.6.2015 data:text/html,<htmlcontenteditable>
buf:stringvalue,datatobecalculatedchecksumin
string.
Returns
crcresultinbyte.
Example
Seealso
BacktoIndex
ow.check_crc16()
Description
Computethe1WireCRC16andcompareitagainst
thereceivedCRC.
Syntax
ow.check_crc16(buf,inverted_crc0,inverted_crc1,
crc)
Parameters
buf:stringvalue,datatobecalculatedchecksumin
string.
inverted_crc0:LSBofreceivedCRC.
inverted_crc1:MSBofreceivedCRC.
crc:crcstartingvalue(optional)
Returns
bool:true,iftheCRCmatchesfalsefordismatches.
Example
data:text/html,<htmlcontenteditable> 97/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
BacktoIndex
ow.crc16()
Description
ComputeaDallasSemiconductor16bitCRC.Thisis
requiredtochecktheintegrityofdatareceivedfrom
many1Wiredevices.NotethattheCRCcomputed
hereisnotwhatyou'llgetfromthe1Wirenetwork,
fortworeasons:
1)TheCRCistransmittedbitwiseinverted.
2)Dependingontheendiannessofyourprocessor,
thebinaryrepresentationofthetwobytereturnvalue
mayhaveadifferentbyteorderthanthetwobytes
yougetfrom1Wire.
Syntax
ow.crc16(buf,crc)
Parameters
buf:stringvalue,datatobecalculatedchecksumin
string.
crc:crcstartingvalue(optional)
Returns
returnTheCRC16,asdefinedbyDallas
Semiconductor.
Example
Seealso
data:text/html,<htmlcontenteditable> 98/127
29.6.2015 data:text/html,<htmlcontenteditable>
BacktoIndex
bitmodule
CONSTANT
none
bit.bnot()
Description
Bitwisenegation,equivalentto~valueinC.
Syntax
bit.bnot(value)
Parameters
value:thenumbertonegate.
Returns
number:thebitwisenegatedvalueofthenumber.
Example
Seealso
BacktoIndex
bit.band()
Description
data:text/html,<htmlcontenteditable> 99/127
29.6.2015 data:text/html,<htmlcontenteditable>
BitwiseAND,equivalenttoval1&val2&...&valnin
C.
Syntax
bit.band(val1,val2,...valn)
Parameters
val1:firstANDargument.
val2:secondANDargument.
valn:nthANDargument.
Returns
number:thebitwiseANDofallthearguments.
Example
Seealso
BacktoIndex
bit.bor()
Description
BitwiseOR,equivalenttoval1|val2|...|valninC.
Syntax
bit.bor(val1,val2,...valn)
Parameters
val1:firstORargument.
val2:secondORargument.
valn:nthORargument.
data:text/html,<htmlcontenteditable> 100/127
29.6.2015 data:text/html,<htmlcontenteditable>
Returns
number:thebitwiseORofallthearguments.
Example
Seealso
BacktoIndex
bit.bxor()
Description
BitwiseXOR,equivalenttoval1^val2^...^valnin
C.
Syntax
bit.bxor(val1,val2,...valn)
Parameters
val1:firstXORargument.
val2:secondXORargument.
valn:nthXORargument.
Returns
number:thebitwiseXORofallthearguments.
Example
Seealso
BacktoIndex
data:text/html,<htmlcontenteditable> 101/127
29.6.2015 data:text/html,<htmlcontenteditable>
bit.lshift()
Description
Leftshiftanumber,equivalenttovalue<<shiftinC.
Syntax
bit.lshift(value,shift)
Parameters
value:thevaluetoshift.
shift:positionstoshift.
Returns
number:thenumbershiftedleft
Example
Seealso
BacktoIndex
bit.rshift()
Description
Logicalrightshiftanumber,equivalentto(unsigned
)value>>shiftinC.
Syntax
bit.rshift(value,shift)
Parameters
value:thevaluetoshift.
data:text/html,<htmlcontenteditable> 102/127
29.6.2015 data:text/html,<htmlcontenteditable>
shift:positionstoshift.
Returns
number:thenumbershiftedright(logically).
Example
Seealso
BacktoIndex
bit.arshift()
Description
Arithmeticrightshiftanumberequivalenttovalue>>
shiftinC.
Syntax
bit.arshift(value,shift)
Parameters
value:thevaluetoshift.
shift:positionstoshift.
Returns
number:thenumbershiftedright(arithmetically).
Example
Seealso
BacktoIndex
data:text/html,<htmlcontenteditable> 103/127
29.6.2015 data:text/html,<htmlcontenteditable>
bit.bit()
Description
Generateanumberwitha1bit(usedformask
generation).Equivalentto1<<positioninC.
Syntax
bit.bit(position)
Parameters
position:positionofthebitthatwillbesetto1.
Returns
number:anumberwithonlyone1bitatposition(the
restaresetto0).
Example
Seealso
BacktoIndex
bit.set()
Description
Setbitsinanumber.
Syntax
bit.set(value,pos1,pos2,...,posn)
Parameters
value:thebasenumber.
data:text/html,<htmlcontenteditable> 104/127
29.6.2015 data:text/html,<htmlcontenteditable>
pos1:positionofthefirstbittoset.
pos2:positionofthesecondbittoset.
posn:positionofthenthbittoset.
Returns
number:thenumberwiththebit(s)setinthegiven
position(s).
Example
Seealso
BacktoIndex
bit.clear()
Description
Clearbitsinanumber.
Syntax
bit.clear(value,pos1,pos2,...,posn)
Parameters
value:thebasenumber.
pos1:positionofthefirstbittoclear.
pos2:positionofthesecondbittoclear.
posn:positionofthetnthbittoclear.
Returns
number:thenumberwiththebit(s)clearedinthe
givenposition(s).
Example
data:text/html,<htmlcontenteditable> 105/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
BacktoIndex
bit.isset()
Description
Testifagivenbitisset.
Syntax
bit.isset(value,position)
Parameters
value:thevaluetotest.
position:bitpositiontotest.
Returns
boolean:trueifthebitatthegivenpositionis1,false
otherwise.
Example
Seealso
BacktoIndex
bit.isclear()
Description
Testifagivenbitiscleared.
Syntax
data:text/html,<htmlcontenteditable> 106/127
29.6.2015 data:text/html,<htmlcontenteditable>
bit.isclear(value,position)
Parameters
value:thevaluetotest.
position:bitpositiontotest.
Returns
boolean:trueifthebitatthegivenpositionis0,false
othewise.
Example
Seealso
BacktoIndex
spimodule
CONSTANT
MASTER,SLAVE,CPHA_LOW,CPHA_HIGH,
CPOL_LOW,CPOL_HIGH,DATABITS_8,
DATABITS_16
spi.setup()
Description
setupspiconfiguration.
Syntax
spi.setup(id,mode,cpol,cpha,databits,clock)
data:text/html,<htmlcontenteditable> 107/127
29.6.2015 data:text/html,<htmlcontenteditable>
Parameters
id:spiidnumber.
mode:MASTERorSLAVE(notsupportedyet).
cpol:CPOL_LOWorCPOL_HIGH,clockpolarity.
cpha:CPHA_HIGHorCPHA_LOW,clockphase.
databits:DATABITS_8orDATABITS_16.
clock:spiclock(notsupportedyet).
Returns
number:1.
Example
Seealso
BacktoIndex
spi.send()
Description
senddatatospi.
Syntax
wrote=spi.send(id,data1,[data2],...,[datan])
Parameters
id:spiidnumber.
data:datacanbeeitherastring,atableoran8bit
number
Returns
number:byteswritencount.
data:text/html,<htmlcontenteditable> 108/127
29.6.2015 data:text/html,<htmlcontenteditable>
Example
Seealso
BacktoIndex
spi.recv()
Description
recvdatafromspi.
Syntax
read=spi.recv(id,size)
Parameters
id:spiidnumber.
size:datasizewanttoread.
Returns
string:stringbytesreadfromspi.
Example
Seealso
BacktoIndex
mqttmodule
CONSTANT
data:text/html,<htmlcontenteditable> 109/127
29.6.2015 data:text/html,<htmlcontenteditable>
mqtt.Client()
Description
CreateaMQTTclient.Theclientadherestoversion
3.1.1oftheMQTTprotocol,makesurethatyour
brokersupportsandiscorrectlyconfiguredfor
version3.1.1oftheMQTTprotocol.Theclientis
incompatiblewithbrokersrunningversion3.1ofthe
MQTTprotocol.
Syntax
mqtt.Client(clientid,keepalive,user,pass)
Parameters
clientid:theclientid.
keepalive:keepalivesecond,anumber.
user:username,astring.
pass:userpassword,astring.
Returns
mqttclient.
Example
initmqttclientwithkeepalivetimer120sec
m=mqtt.Client("clientid",120,"user","password
setupLastWillandTestament(optional)
Brokerwillpublishamessagewithqos=0,retain=0,data="offline"
totopic"/lwt"ifclientdon'tsendkeepalivepacket
m:lwt("/lwt","offline",0,0)
m:on("connect",function(con)print("connected")
m:on("offline",function(con)print("offline")end
onpublishmessagereceiveevent
m:on("message",function(conn,topic,data)
print(topic..":")
ifdata~=nilthen
data:text/html,<htmlcontenteditable> 110/127
29.6.2015 data:text/html,<htmlcontenteditable>
print(data)
end
end)
forsecure:m:connect("192.168.11.118",1880,1)
m:connect("192.168.11.118",1880,0,function(conn
subscribetopicwithqos=0
m:subscribe("/topic",0,function(conn)print("subscribesuccess
publishamessagewithdata=hello,QoS=0,retain=0
m:publish("/topic","hello",0,0,function(conn)print
m:close();
youcancallm:connectagain
Seealso
BacktoIndex
mqttclientmodule
mqtt.client:lwt()
Description
setupLastWillandTestament(optional)
Brokerwillpublishamessagewithqos=0,retain=
0,data="offline"
totopic"/lwt"ifclientdon'tsendkeepalivepacket.
Syntax
mqtt:lwt(topic,message,qos,retain)
Parameters
topic:thetopictopublishto,String.
data:text/html,<htmlcontenteditable> 111/127
29.6.2015 data:text/html,<htmlcontenteditable>
message:themessagetopublish,BufferorString.
qos:qoslevel,default0.
retain:retainflag,default0.
Returns
nil.
Example
Seealso
BacktoIndex
mqtt.client:connect()
Description
Connectstothebrokerspecifiedbythegivenhost,
port,andsecureoptions
Syntax
mqtt:connect(host,port,secure,function(client))
Parameters
host:hostdomainorip,string.
port:number,brokerport.
secure:0or1,default0.
function(client):whenconnected,callthisfunction.
Returns
nil.
Example
Seealso
data:text/html,<htmlcontenteditable> 112/127
29.6.2015 data:text/html,<htmlcontenteditable>
BacktoIndex
mqtt.client:close()
Description
closeconnectiontothebroker.
Syntax
mqtt:close()
Parameters
nil
Returns
nil.
Example
Seealso
BacktoIndex
mqtt.client:publish()
Description
Publishamessage
Syntax
mqtt:publish(topic,payload,qos,retain,
function(client))
data:text/html,<htmlcontenteditable> 113/127
29.6.2015 data:text/html,<htmlcontenteditable>
Parameters
topic:thetopictopublishto,string
message:themessagetopublish,string
qos:qoslevel,default0
retain:retainflag,default0
function(client):callbackfiredwhenPUBACK
received.
Returns
nil.
Example
Seealso
BacktoIndex
mqtt.client:subscribe()
Description
Subscribetoatopicortopics
Syntax
mqtt:subscribe(topic,qos,function(client,topic,
message))
Parameters
topic:astringtopictosubscribeto
qos:qossubscriptionlevel,default0
function(client,topic,message):callbackfiredwhen
messagereceived.
Returns
data:text/html,<htmlcontenteditable> 114/127
29.6.2015 data:text/html,<htmlcontenteditable>
nil.
Example
Seealso
BacktoIndex
mqtt.client:on()
Description
registercallbackfunctiontoevent.
Syntax
mqtt:on(event,function(client,[topic],[message]))
Parameters
event:string,whichcanbe:"connect","message",
"offline"
functioncb(client,[topic],[message]):callback
function.Thefirstparamistheclient.
Ifeventis"message",the2ndand3rdparamare
receivedtopicandmessageinstring.
Returns
nil.
Example
Seealso
WS2812Module
data:text/html,<htmlcontenteditable> 115/127
29.6.2015 data:text/html,<htmlcontenteditable>
ws2812.writergb()
Description
SendtheRGBDatain8bitstoWS2812
Syntax
ws2812.writergb(pin,
string.char(R1,G1,B1(,R2,G2,B2...)))
Parameters
pin=SupportedallthePINs(0,1,2...)
R1=ThefirstWS2812thoughtheline'sRed
Channel'sParameters0255
G1=ThefirstWS2812thoughtheline'sGreen
Channel'sParameters0255
B1=ThefirstWS2812thoughtheline'sBlue
Channel'sParameters0255
...YoucanconnectalotofWS2812...
R2,G2,B2isthenextWS2812'sRed,Greenand
BlueChannel'sParameters
Return
nil
cjson.encode()
Description
Encodetabletojsonstring
Syntax
cjson.encode(table)
Parameters
data:text/html,<htmlcontenteditable> 116/127
29.6.2015 data:text/html,<htmlcontenteditable>
table=datatoencode
Return
jsonstring
Example
print(cjson.encode({key="value"}))
cjson.decode()
Description
Decodejsonstringtotable
Syntax
cjson.decode(s)
Parameters
s=stringtodecode
Return
Luatable
Example
t=cjson.decode("{\"key\":\"value\"}")
fork,vinpairs(t)doprint(k,v)end
BacktoIndex
u8gmodule
data:text/html,<htmlcontenteditable> 117/127
29.6.2015 data:text/html,<htmlcontenteditable>
CONSTANT
u8g.DRAW_UPPER_RIGHT,
u8g.DRAW_UPPER_LEFT,
u8g.DRAW_LOWER_RIGHT,
u8g.DRAW_LOWER_LEFT,u8g.DRAW_ALL,
u8g.MODE_BW,u8g.MODE_GRAY2BIT
u8g.font_6x10,...
u8g.ssd1306_128x64_i2c()
Description
InitializeanSSD1306128x64displayviaI2C.
Syntax
u8g.ssd1306_128x64_i2c(sla)
Parameters
sla:I2Cslaveaddress.
Returns
u8gdisplay.
Example
sda=5
scl=6
i2c.setup(0,sda,scl,i2c.SLOW)
sla=0x3c
disp=u8g.ssd1306_128x64_i2c(sla)
Seealso
BacktoIndex
data:text/html,<htmlcontenteditable> 118/127
29.6.2015 data:text/html,<htmlcontenteditable>
u8g.ssd1306_128x64_spi()
Description
InitializeanSSD1306128x64displayviaSPI.
Syntax
u8g.ssd1306_128x64_spi(cs,dc,res)
Parameters
cs:GPIOpinfor/CS.
dc:GPIOpinforDC.
res:GPIOpinfor/RES.
Returns
u8gdisplay.
Example
spi.setup(1,spi.MASTER,spi.CPOL_LOW,spi.CPHA_LOW
cs=8GPIO15,pulldown10ktoGND
dc=4GPIO2
res=0GPIO16,RESisoptionalYMMV
disp=u8g.ssd1306_128x64_spi(cs,dc,res)
Seealso
BacktoIndex
u8gdisplaysub
module
TheLuabindingsforthislibrarycloselyfollow
u8glib'sobjectorientedC++API.Visittheu8glib
data:text/html,<htmlcontenteditable> 119/127
29.6.2015 data:text/html,<htmlcontenteditable>
homepagefortechnicaldetails.
u8g.disp:drawBitmap()
Description
Drawabitmapatthespecifiedx/yposition(upperleft
cornerofthebitmap).Partsofthebitmapmaybe
outsidethedisplayboundaries.Thebitmapis
specifiedbythearraybitmap.Aclearedbitmeans:
Donotdrawapixel.Asetbitinsidethearraymeans:
Writepixelwiththecurrentcolorindex.Fora
monochromedisplay,thecolorindex0willusually
clearapixelandthecolorindex1willsetapixel.
Syntax
disp.drawBitmap(x,y,cnt,h,bitmap)
Parameters
x:Xposition(leftpositionofthebitmap).
y:Yposition(upperpositionofthebitmap).
cnt:Numberofbytesofthebitmapinhorizontal
direction.Thewidthofthebitmapiscnt*8.
h:Heightofthebitmap.
bitmap:Bitmapdatasuppliedasstring.
Returns
nil
Example
lua_examples/u8glib/u8g_bitmaps.lua
Seealso
u8glibdrawBitmap()
BacktoIndex
data:text/html,<htmlcontenteditable> 120/127
29.6.2015 data:text/html,<htmlcontenteditable>
u8g.disp:drawXBM()
Description
DrawaXBMBitmap.Position(x,y)istheupperleft
cornerofthebitmap.XBMcontainsmonochrome,1
bitbitmaps.Thisprocedureonlydrawspixelvalues
1.Thecurrentcolorindexisusedfordrawing(see
setColorIndex).Pixelwithvalue0arenotdrawn
(transparent).
BitmapsandXBMsaresuppliedasstrings
todrawBitmap()anddrawXBM().Thisoffloadsalldata
handlingfromtheu8gmoduletogenericmethodsfor
binaryfiles.Incontrasttothesourcecodebased
inclusionofXBMsintou8glib,it'srequiredtoprovide
precompiledbinaryfiles.Thiscanbeperformed
onlinewithOnlineUtility'sImageConverter:Convert
fromXBMtoMONOformatanduploadthebinary
resultwithnodemcuuploader.py.
Syntax
disp.drawXBM(x,y,w,h,bitmap)
Parameters
x:Xposition(leftpositionofthebitmap).
y:Yposition(upperpositionofthebitmap).
w:Widthofthebitmap.
h:Heightofthebitmap.
bitmap:XBMdatasuppliedasstring.
Returns
nil
Example
lua_examples/u8glib/u8g_bitmaps.lua
data:text/html,<htmlcontenteditable> 121/127
29.6.2015 data:text/html,<htmlcontenteditable>
Seealso
u8glibdrawXBM()
BacktoIndex
u8g.disp:setFont()
Description
u8glibcomeswithawiderangeoffontsforsmall
displays.Sincetheyneedtobecompiledintothe
firmwareimage,you'dneedtoincludethem
inapp/include/u8g_config.handrecompile.Simply
addthedesiredfontstothefonttable:
#defineU8G_FONT_TABLE\
U8G_FONT_TABLE_ENTRY(font_6x10)\
U8G_FONT_TABLE_ENTRY(font_chikita)
They'llbeavailableasu8g.<font_name>inLua.
Syntax
disp.setFont(font)
Parameters
font:Constanttoindentifyprecompiledfont.
Returns
nil
Example
disp:setFont(u8g.font_6x10)
Seealso
data:text/html,<htmlcontenteditable> 122/127
29.6.2015 data:text/html,<htmlcontenteditable>
u8glibsetFont()
BacktoIndex
dhtmodule
CONSTANT
dht.OK,dht.ERROR_CHECKSUM,
dht.ERROR_TIMEOUT
dht.OKis0,dht.ERROR_CHECKSUMis1,
dht.ERROR_TIMEOUTis2
dht.read()
Description
Readallkindsofdhtsensors,includingdht11,21,
22,33,44humiditytemperaturecombosensor.
Syntax
dht.read(pin)
Parameters
pin:pinnumberofdhtsensor(can'tbe0),typeis
number
Return
integerofstatus,numberoftemperature,humidity,
decimialoftemperature,decimialofhumidity.
statusisinteger,temperature,humidity,decimialof
temperature,decimialofhumidityisnumber.*Note:
Ifusingfloatfirmware,thetemperature,humidity
alreadywithdecimial.
data:text/html,<htmlcontenteditable> 123/127
29.6.2015 data:text/html,<htmlcontenteditable>
Example
pin=5
status,temp,humi,temp_decimial,humi_decimial=dht.
if(status==dht.OK)then
Integerfirmwareusingthisexample
print(
string.format(
"DHTTemperature:%d.%03d;Humidity:%d.%03d\r\n
math.floor(temp),
temp_decimial,
math.floor(humi),
humi_decimial
)
)
Floatfirmwareusingthisexample
print("DHTTemperature:"..temp..";".."Humidity:"
elseif(status==dht.ERROR_CHECKSUM)then
print("DHTChecksumerror.");
elseif(status==dht.ERROR_TIMEOUT)then
print("DHTTimeout.");
end
dht.read11()
Description
Readdht11humiditytemperaturecombosensor.
Syntax
dht.read11(pin)
Parameters
pin:pinnumberofdhtsensor(can'tbe0),typeis
number
Return
integerofstatus,numberoftemperature,humidity,
decimialoftemperature,decimialofhumidity.
data:text/html,<htmlcontenteditable> 124/127
29.6.2015 data:text/html,<htmlcontenteditable>
statusisinteger,temperature,humidity,decimialof
temperature,decimialofhumidityisnumber.*Note:
Ifusingfloatfirmware,thetemperature,humidity
alreadywithdecimial.
Example
pin=5
status,temp,humi,temp_decimial,humi_decimial=dht.
if(status==dht.OK)then
Integerfirmwareusingthisexample
print(
string.format(
"DHTTemperature:%d.%03d;Humidity:%d.%03d\r\n
math.floor(temp),
temp_decimial,
math.floor(humi),
humi_decimial
)
)
Floatfirmwareusingthisexample
print("DHTTemperature:"..temp..";".."Humidity:"
elseif(status==dht.ERROR_CHECKSUM)then
print("DHTChecksumerror.");
elseif(status==dht.ERROR_TIMEOUT)then
print("DHTTimeout.");
end
dht.readxx()
Description
Readallkindsofdhtsensors,exceptdht11.
Syntax
dht.readxx(pin)
Parameters
pin:pinnumberofdhtsensor(can'tbe0),typeis
number
data:text/html,<htmlcontenteditable> 125/127
29.6.2015 data:text/html,<htmlcontenteditable>
Return
integerofstatus,numberoftemperature,humidity,
decimialoftemperature,decimialofhumidity.
statusisinteger,temperature,humidity,decimialof
temperature,decimialofhumidityisnumber.*Note:
Ifusingfloatfirmware,thetemperature,humidity
alreadywithdecimial.
Example
pin=5
status,temp,humi,temp_decimial,humi_decimial=dht.
if(status==dht.OK)then
Integerfirmwareusingthisexample
print(
string.format(
"DHTTemperature:%d.%03d;Humidity:%d.%03d\r\n
math.floor(temp),
temp_decimial,
math.floor(humi),
humi_decimial
)
)
Floatfirmwareusingthisexample
print("DHTTemperature:"..temp..";".."Humidity:"
elseif(status==dht.ERROR_CHECKSUM)then
print("DHTChecksumerror.");
elseif(status==dht.ERROR_TIMEOUT)then
print("DHTTimeout.");
end
TheMITLicense(MIT)
Copyright(c)2014zerodaynodemcu.com
Permissionisherebygranted,freeofcharge,toanypersonobtainingacopy
ofthissoftwareandassociateddocumentationfiles(the"Software"),todeal
intheSoftwarewithoutrestriction,includingwithoutlimitationtherights
touse,copy,modify,merge,publish,distribute,sublicense,and/orsell
copiesoftheSoftware,andtopermitpersonstowhomtheSoftwareis
furnishedtodoso,subjecttothefollowingconditions:
data:text/html,<htmlcontenteditable> 126/127
29.6.2015 data:text/html,<htmlcontenteditable>
Theabovecopyrightnoticeandthispermissionnoticeshallbeincludedinall
copiesorsubstantialportionsoftheSoftware.
THESOFTWAREISPROVIDED"ASIS",WITHOUTWARRANTYOFANYKIND,EXPRESSOR
IMPLIED,INCLUDINGBUTNOTLIMITEDTOTHEWARRANTIESOFMERCHANTABILITY,
FITNESSFORAPARTICULARPURPOSEANDNONINFRINGEMENT.INNOEVENTSHALLTHE
AUTHORSORCOPYRIGHTHOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHER
LIABILITY,WHETHERINANACTIONOFCONTRACT,TORTOROTHERWISE,ARISINGFROM,
OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSINTHE
SOFTWARE.
data:text/html,<htmlcontenteditable> 127/127