Making variables persistent after a restart on NodeMCU

Suraj Bhawal picture Suraj Bhawal · Sep 16, 2015 · Viewed 10.4k times · Source

I'm making a smart home system using nodeMCU, and I need to store and retrieve data from the module. I used the following function.

function save_settings(name,value)
  file.remove(name)
  file.open(name,"w+")
  file.writeline(value)
  file.close()
end

It works but it's slow and the NodeMCU crashes if I trigger the above function rapidly... Sometimes requiring a FS format to be able to use it again.

So my question is: is there any other way to make variables persistent between restarts?

Answer

wordsforthewise picture wordsforthewise · Oct 17, 2015

I'm using the latest firmware, 0.9.6-dev_20150704, the float version (https://github.com/nodemcu/nodemcu-firmware/releases)

This code took 62-63 ms to complete at first, and seems to add a few fractions of a millisecond with each successive run of the code, after a few hundred executions, it was up to almost 100 ms. It never crashed on me.

function save_setting(name, value)
  file.open(name, 'w') -- you don't need to do file.remove if you use the 'w' method of writing
  file.writeline(value)
  file.close()
end

function read_setting(name)
  if (file.open(name)~=nil) then
      result = string.sub(file.readline(), 1, -2) -- to remove newline character
      file.close()
      return true, result
  else
      return false, nil
  end
end

startTime = tmr.now()

test1 = 1200
test2 = 15.7
test3 = 75
test4 = 15000001
save_setting('test1', test1)
save_setting('test2', test2)
save_setting('test3', test3)
save_setting('test4', test4)

1exists, test1 = read_setting('test1')
2exists, test2 = read_setting('test2')
3exists, test3 = read_setting('test3')
4exists, test4 = read_setting('test4')

completeTime = (tmr.now()-startTime)/(1000)
print('time to complete (ms):')
print(tostring(completeTime))