幾個NodeMcu開發技巧

  • 517
  • 0
  • 2019-04-18

一些開發NodeMcu可能會用到的knon how

查詢剩餘ram

當記憶體又不夠用時,可以在dofile()前後加上這段來確認它耗了多少記憶體

print('heap = ', node.heap())

這時你會發現一個奇怪現像,就是有時同一段code全放init.lua時耗的記憶體是1000,另開lua script再dofile後就變成3000了。

local多宣告一次?

將原本在全域變數的東西多宣告local變數再使用,是為了加快使用其硬體module時的存取速度,譬如

local i2c = i2c
i2c.write(...)

文件解釋說變數存取速度是local(使用index存取)快於global(hash查詢table),相對非常慢的是Firmware-based tables,也就是在存取從韌體而來的那些module功能時。故此在使用前,先將其存進一個local變數中,可以大大加快之後每次存取的時間。

The Lua runtime uses hashed key access internally to retrieve keyed data from a table. On the other hand locals and upvalues are stored as a contiguous vector and are accessed directly by an index, which is a lot faster. In NodeMCU Lua accesses to Firmware-based tables is particularly slow, which is why you will often see statements like the following at the beginning of modules. Using locals and upvalues this way is both a lot faster at runtime and generates less bytecode instructions for their access.

一般使用時這點時差可能不太要緊,不過在作i2c通訊或計時相關操作時可以注意一下。我碰過的坑是有時i2c寫入LCD(lcd1602)會顯示亂碼,研究後發現是因為我把`lcd1602.lua`放進了LFS而導致它變慢。故此i與write byte相關的函式不得放進LFS,而是必需與init.lua一樣存於SPIFFS(SPI Flash File system)再載入到ram以加快操作,同時它的runtime string也不得放到LFS的preload字串中(dummy_strings.lua)。像以下字串必需自行排除

local preload_ignore = "i2c", "address", "start", "stop", "write", "lshift", "band", "bit"

延遲的硬體操作

NodeMCU中的lua程式執行某些與硬體相關(C library)的操作時,會先將其操作暫存,並於lua程式碼段執行完畢將主控交還C後才進行。故此像node.restart()這個操作並不會立即重置SOC(System On a Chip),會在lua執行完後才重啟。