Current Lua downloadable firmware will be posted here

User avatar
By blavery
#69804 I recently wanted to expand the functionality of some of the standard rom-based functions that the NodeMCU Lua provides. Specifically I wanted to add to gpio and adc and math modules. I had added extra mcp23017 digitals, some multiplexed ADC via a 74HC4051, and I had written some trig functions for math. And so I wanted gpio.write(19,gpio.HIGH) to work, and adc.read(5), and math.sin(x), just "like normal."

It's perfectly possible, and I discovered it's not difficult. Most of lua's modules are type "romtable" and their member functions are "lightfunction", again in rom.

Hints: Use print(type(gpio)) or print(type(gpio.write)) to examine items: addresses in 0x4xxxx are rom, in 0x3xxxx are ram. And to see the whole table, use
for k,v in pairs(gpio) do print(k,v) end)

1. Clone the main table, eg gpio, into ram. The "small" items in the table like .OUTPUT go into ram, but the lightfunctions like .write() stay in rom. Effectively, we copy just the outer skeleton of table gpio{} into ram.
2. Since the table is now in ram, we are free to add new members or overwrite some. But firstly, add one new member called "parent", which points to the ORIGINAL gpio{} rom=based table.
3. Assign the original name gpio to be the NEW table. At this point both gpio.write(4, gpio.HIGH) and gpio.parent.write(4, gpio.HIGH) will work identically.
4. Simply write code for any new member function like gpio.write(). Our new function is to write to our new hardware if the pin number is in some new range (say 13 - 28), and defer back to the rom code for original pin numbers.
Code: Select alllocal function clone (t)
    local target = {}
    for k, v in pairs(t) do target[k] = v end
    setmetatable(target, getmetatable(t))
    target['parent'] = t
    return target 
end

gpio=clone(gpio)

function gpio.write(pin, data)
        if pin <=12 then gpio.parent.write(pin,data) return end  -- use orig rom code
        MCP23017_pinWrite(pin-13, data)  -- call our own code to write to 23017 pins
end

Write your equivalents for gpio.mode() and gpio.read(), and from now on we have digital pins 0 to 28 all controlled with the same syntax.

(The new GPIO pins just operate slightly slower, over I2C. And they don't support interrupts, unless you code that too!)