Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making variables persistent after a restart on NodeMCU

Tags:

nodemcu

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?

like image 987
Suraj Bhawal Avatar asked Sep 16 '15 18:09

Suraj Bhawal


2 Answers

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))
like image 110
wordsforthewise Avatar answered Dec 01 '22 00:12

wordsforthewise


If you upgrade to the newer version (based on SDK 1.4.0) you can use the rtcmem memory slots:

local offset = 10
local val = rtcmem.read32(offset, 1)
rtcmem.write32(offset, val + 1)

That memory is documented to persist through a deep sleep cycle; I've found it to persist across both hardware and software resets (but not cycling power.)

like image 30
Mark McGinty Avatar answered Dec 01 '22 00:12

Mark McGinty