Managing Files with NodeMCU | NodeMCU Examples

In this article, We learn “Managing Files with NodeMCU”. NodeMCU is most popular development board for IoT projects. NodeMCU is an open source IoT platform. It includes firmware which runs on the ESP8266 Wi-Fi SoC from Espressif Systems, and hardware which is based on the ESP-12 module. The term “NodeMCU” by default refers to the firmware rather than the development kits. The firmware uses the Lua scripting language. It is based on the eLua project, and built on the Espressif Non-OS SDK for ESP8266. It uses many open source projects, such as lua-cjson and SPIFFS (SPI Flash File System).

NodeMCU Firmware has inbuilt support for file operations using SPI Flash File System (SPIFFS), so you can perform operations like upload, delete, list, compile, run, etc directly on ESP8266 Module. SPIFFS allows data and scripts to be written and read from the flash memory in form of files instead of raw memory locations. Lua source program can be saved, compiled and run directly on NodeMCU Module. Within NodeMCU, the file module is used by Lua scripts to interact with the SPIFFS filesystem. It means that we perform the file operations using simple Lua based NodeMCU functions/commands.

Managing Files with NodeMCU

Let’s explore some of the file operations here.

List Files:

You can list all the available files, following script –

for k,v in pairs(file.list()) do 
 print("File Name: " .. k .. " Size: " .. v)
end

Create File:

To create a new text file you can use following script. Maximum filename length is 32 characters.

file.open("hello_world.txt", "w")
file.writeline("My First File on NodeMCU") 
file.close()

To create a Lua Script file you need to enclose the line in “[[ ]]”. Following is an example –

file.open("helloLua.lua", "w")
file.writeline([[a=1]])
file.writeline([[a=a+1]])
file.writeline([[print(a)]])
file.close()

NodeMCU allows a file to be opened in following mode –

"r": read mode (the default)
"w": write mode
"a": append mode
"r+": update mode, all previous data is preserved
"w+": update mode, all previous data is erased
"a+": append update mode, previous data is preserved, writing is only allowed at the end of file

Read File:

file.open("hello_world.txt", "r")
while true 
do 
 line = file.readline() 
 if (line == nil) then 
 file.close()
 break 
 end
 print(line)
end

Rename File:

file.rename("hello_world.txt", "helloIndia.txt")

Compile Lua Script File:

You can compile a Lua file on NodeMCU board using following method. After compilation a new file will be created with same name and “.lc” extension.

node.compile("helloLua.lua")

Execute Lua Script File:

dofile("helloLua.lua")

Delete File:

file.remove("helloIndia.txt")
file.remove("helloLua.lua")

Format File System:

file.format()

init.lua File:

“init.lua” acts as C main() function for NodeMCU. It is the first file that NodeMCU looks for after completing the boot process. If it finds this file, it tries to execute the contents otherwise ignores it.

In most of the cases the “init.lua” file will not be there by default. This is the reason why you see following message on serial console when you connect to NodeMCU for the first time –

lua: cannot open init.lua

Important thing to notice while creating init.lua file is that if there are errors in init.lua code, NodeMCU may fall into infinite reboot loop. So it becomes really important to test your code before adding that to init.lua file.

In case if you are unable to recover NodeMCU from reboot loop, you may try re-flashing the firmware using NodeMCU Flasher.

NodeMCU Flasher

NodeMCU flasher is a firmware programmer for NodeMCU DEVKIT V0.9. You can use it to program NodeMCU DEVKIT or your own ESP8266 board. You MUST set GPIO0 to LOW before programming, and NodeMCU DEVKIT V0.9 will do it automatically. It will be cross platform and open source.

NodeMCU Examples

Connect to the wireless network


print(wifi.sta.getip())
--nil
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","password")
print(wifi.sta.getip())
--192.168.18.110
              

Arduino like IO access


pin = 1
gpio.mode(pin,gpio.OUTPUT)
gpio.write(pin,gpio.HIGH)
gpio.mode(pin,gpio.INPUT)
print(gpio.read(pin))

              

HTTP Client


-- A simple http client
conn=net.createConnection(net.TCP, false) 
conn:on("receive", function(conn, pl) print(pl) end)
conn:connect(80,"121.41.33.127")
conn:send("GET / HTTP/1.1\r\nHost: www.nodemcu.com\r\n"
    .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")

              

HTTP Server


-- a simple http server
srv=net.createServer(net.TCP) 
srv:listen(80,function(conn) 
    conn:on("receive",function(conn,payload) 
    print(payload) 
    conn:send("<h1> Hello, NodeMcu.</h1>")
    end) 
end)
              

PWM


function led(r,g,b) 
    pwm.setduty(1,r) 
    pwm.setduty(2,g) 
    pwm.setduty(3,b) 
end
pwm.setup(1,500,512) 
pwm.setup(2,500,512) 
pwm.setup(3,500,512)
pwm.start(1) 
pwm.start(2) 
pwm.start(3)
led(512,0,0) -- red
led(0,0,512) -- blue
              

Blinking Led



lighton=0
tmr.alarm(0,1000,1,function()
if lighton==0 then 
    lighton=1 
    led(512,512,512) 
    -- 512/1024, 50% duty cycle
else 
    lighton=0 
    led(0,0,0) 
end 
end)

              

Bootstrap


--init.lua will be excuted
file.open("init.lua","w")
file.writeline([[print("Hello World!")]])
file.close()
node.restart()  -- this will restart the module.
              

Use timer to repeat


tmr.alarm(1,5000,1,function() print("alarm 1") end)
tmr.alarm(0,1000,1,function() print("alarm 0") end)
tmr.alarm(2,2000,1,function() print("alarm 2") end)
-- after sometime
tmr.stop(0)
              

A pure lua telnet server


-- a simple telnet server
s=net.createServer(net.TCP,180) 
s:listen(2323,function(c) 
    function s_output(str) 
      if(c~=nil) 
        then c:send(str) 
      end 
    end 
    node.output(s_output, 0)   
    -- re-direct output to function s_ouput.
    c:on("receive",function(c,l) 
      node.input(l)           
      --like pcall(loadstring(l)), support multiple separate lines
    end) 
    c:on("disconnection",function(c) 
      node.output(nil)        
      --unregist redirect output function, output goes to serial
    end) 
    print("Welcome to NodeMcu world.")
end)

              

Interfacing with sensor


-- read temperature with DS18B20
t=require("ds18b20")
t.setup(9)
addrs=t.addrs()
-- Total DS18B20 numbers, assume it is 2
print(table.getn(addrs))
-- The first DS18B20
print(t.read(addrs[1],t.C))
print(t.read(addrs[1],t.F))
print(t.read(addrs[1],t.K))
-- The second DS18B20
print(t.read(addrs[2],t.C))
print(t.read(addrs[2],t.F))
print(t.read(addrs[2],t.K))
-- Just read
print(t.read())
-- Just read as centigrade
print(t.read(nil,t.C))
-- Don't forget to release it after use
t = nil
ds18b20 = nil
package.loaded["ds18b20"]=nil
              

I hope you like this post “Managing Files with NodeMCU”. Do you have any questions? Leave a comment down below!


Buy now : Raspberry PI 3 Model B+ Motherboard

Harshvardhan Mishra

I am an IoT (Internet of Things) Enthusiast and Blogging is my Passion. Follow and send tweets me on @harshvardhanrvm

Leave a Reply

%d bloggers like this: