首先,您的代码根本不运行…按原样,它将抛出
input:6: attempt to call a nil value (global 'armAllButtons')
我将您的代码片段重新排列为:
buttonPins = { 5 }
direction="up"
function armButton(buttonPin)
print("Arming pin "..buttonPin.." for button presses.")
gpio.mode(buttonPin,gpio.INT,gpio.FLOAT)
gpio.trig(buttonPin, direction, function (buttonPin) --notifyButtonPressed(buttonPin) end)
print("Waiting for button press on "..buttonPin.."...")
end
function notifyButtonPressed(buttonPin)
print("Button at pin "..buttonPin.." pressed.")
--rearm the pins for interrupts
armButton(buttonPin)
end
function armAllButtons()
for i,v in ipairs(buttonPins)
do
armButton(v)
end
end
armAllButtons()
它输出:
Arming pin 5 for button presses.
Waiting for button press on 5...
为了使回调能够完美地工作,您必须为每个按钮传递不同的函数,而不是尝试将参数传递给函数…请尝试以下操作:
buttonPins = { 5 }
direction="up"
function armButton(buttonPin)
print("Arming pin "..buttonPin.." for button presses.")
gpio.mode(buttonPin,gpio.INT,gpio.FLOAT)
gpio.trig(
buttonPin,
direction,
function ()
notifyButtonPressed(buttonPin)
end
) -- this should create a function for each button, and each function shall pass a different argument to notifyButtonPressed
print("Waiting for button press on "..buttonPin.."...")
end
function notifyButtonPressed(buttonPin)
print("Button at pin "..buttonPin.." pressed.")
--rearm the pins for interrupts
armButton(buttonPin)
end
function armAllButtons()
for i,v in ipairs(buttonPins)
do
armButton(v)
end
end
armAllButtons()