As the title says... Chat on...

User avatar
By Horst Horstmann
#60533 Hi everybody,

short story: How do I pass parameters to callback functions in LUA?

Long story:
I'm working on an ESP8266 with the nodemcu firmware. Essentially I intend to built a dash button, just with multiple buttons per node. I'm doing this with the interrupt possibility of the gpio pins.
However it only seems to be documented how to invoke a function without passing parameters to it. But in my case I want to know for which pin the interrupt came. I googled quite a bit and came up with the approach below. It is working except for the value of the pin, that seems to reset to the initialization value of 1 when triggered.

Code: Select all  -- Have an area to hold all pins to query (in testing only one)

  buttonPins = { 5 }
  direction="up"

  armAllButtons()

  function armAllButtons()
   for i,v in ipairs(buttonPins)
   do
      armButton(v)
   end
  end


  function armButton(buttonPin)
   print("Arming pin "..buttonPin.." for button presses.")

   gpio.mode(buttonPin,gpio.INT,gpio.FLOAT)
   gpio.trig(buttonPin, direction, function (buttonPinPressed) notifyButtonPressed(buttonPinPressed) end)

   print("Waiting for button press on "..buttonPin.."...")
  end

  function notifyButtonPressed(buttonPin)
   print("Button at pin "..buttonPin.." pressed.")

    --rearm the pins for interrupts
   gpio.trig(buttonPin, direction, notifyButtonPressed)
  end


However from within the function notifyButtonPressed() the value of buttonPin is always 1 when pressed, not 5 as I would expect it to be. I'd assume that's probably the initialization value of number variables.

Does anybody have an idea?
User avatar
By devsaurus
#60578 When you look at http://nodemcu.readthedocs.io/en/master ... /#gpiotrig you see that the first parameter passed to the callback function is the pin level. You can't define different parameters.
Seems that your approach with a single function which is parametrized by the pin number isn't feasible. You'd need to establish a dedicated callback function per pin.