vsergeev / lua-periphery

A Lua library for peripheral I/O (GPIO, LED, PWM, SPI, I2C, MMIO, Serial) in Linux.
MIT License
182 stars 38 forks source link

Poll multiple GPIOs #2

Closed 1linux closed 9 years ago

1linux commented 9 years ago

Hello Vanya, is there a solution to poll() multiple GPIOs at a time? I tried to poll() via luaposix, but that doesn´t seem to work...

1linux commented 9 years ago

I finally got it to run. Here´s my example code:

-- Example how to poll multiple GPIO-Pins at a time
-- Feb. 2015 Helmut Gruber
--
-- make sure lua runs with su priviledges, e.g. with sudo chmod +s /usr/bin/lua
-- or run this script with "sudo lua"

local GPIO = require('periphery').GPIO
local P = require 'posix'

-- Example table with pin numbers an some description
local pins={
    {   pin=25, code="KEY_LEFT"     },      -- // Joystick (4 pins)
    {   pin=9,  code="KEY_RIGHT"    },
    {   pin=10, code="KEY_UP"       },
    {   pin=17, code="KEY_DOWN"     },
    {   pin=23, code="KEY_LEFTCTRL" },  --   // A/Fire/jump/primary
    {   pin=7,  code="KEY_LEFTALT"  },  --   // B/Bomb/secondary
    {   pin=2,  code="KEY_5"        },  -- // Coin
    {   pin=27, code="KEY_1"        },  -- //  1 Player up
    {   pin=3,  code="KEY_SPACE"    },  -- // C/Button 3
    {   pin=4,  code="KEY_ENTER"    },  -- // Pause
    {   pin=22, code="KEY_TAB"      },  -- // TAB links aussen
    {   pin=24, code="KEY_ESC" }    
}

-- Create a table of GPIO-Pins, same order as the "pins" table
local gpios={}
for t=1,#pins do
    gpios[t]=GPIO( pins[t].pin, "in")
    gpios[t].edge="both"                        -- Get interrupt on button press and release
end

-- Forever loop:
while true do
    -- Create a table of FileDescriptors for posix-poll()
    -- GPIO-Interrupts arrive with flag "PRI"
    local fds={}
    for t=1, #gpios do
        fds[gpios[t].fd] = { events = {PRI=true , index=t }}
    end

    local numevents=P.poll(fds,1000)            
    if numevents > 0 then                   -- Anything changed? 
        for _,f in pairs(fds) do                    -- Now search all revents with PRI=true
            local revents=f.revents
            if revents then
                if revents.PRI then
                    local ix=f.events.index         -- Get Index of our gpios table
                    local res = gpios[ix]:read()                -- Get the input state
                    print(res, gpios[ix], pins[ix].code)    -- Give some user feedback
                end
            end
        end
    end
end