diff --git a/README.md b/README.md index 404d947..278aa26 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,14 @@ # rpio.lua Pure Lua Raspberry Pi GPIO library + +```lua +local rpio = require 'rpio' +local gpio = rpio(12) + +gpio.set_direction('out') +gpio.write(1) + +gpio.set_direction('in') +print(gpio.read()) +``` + diff --git a/rockspecs/gpio-git-0.rockspec b/rockspecs/gpio-git-0.rockspec new file mode 100644 index 0000000..fccaaec --- /dev/null +++ b/rockspecs/gpio-git-0.rockspec @@ -0,0 +1,20 @@ +package = 'rpio' +version = 'git-0' +source = { + url = 'git://github.com/ryanplusplus/rpio.lua.git' +} +description = { + summary = 'Pure Lua Raspberry Pi GPIO library', + homepage = 'https://github.com/ryanplusplus/rpio.lua/', + license = 'MIT ' +} +dependencies = { + 'lua >= 5.1' +} +build = { + type = 'builtin', + modules = { + ['rpio'] = 'rpio.lua' + } +} + diff --git a/rockspecs/rpio-1.0-0.rockspec b/rockspecs/rpio-1.0-0.rockspec new file mode 100644 index 0000000..0508e85 --- /dev/null +++ b/rockspecs/rpio-1.0-0.rockspec @@ -0,0 +1,21 @@ +package = 'rpio' +version = '1.0-0' +source = { + url = 'https://github.com/ryanplusplus/rpio.lua/archive/v1.0-0.tar.gz', + dir = 'rpio.lua-1.0-0/src' +} +description = { + summary = 'Pure Lua Raspberry Pi GPIO library', + homepage = 'https://github.com/ryanplusplus/rpio.lua/', + license = 'MIT ' +} +dependencies = { + 'lua >= 5.1' +} +build = { + type = 'builtin', + modules = { + ['rpio'] = 'rpio.lua' + } +} + diff --git a/src/rpio.lua b/src/rpio.lua new file mode 100644 index 0000000..97b91f1 --- /dev/null +++ b/src/rpio.lua @@ -0,0 +1,59 @@ +local gpio_subsystem = '/sys/class/gpio/' + +local function write(path, value) + local f = io.open(path, 'a+') + f:write(tostring(value)) + f:close() +end + +local function read(path) + local f = io.popen('cat ' .. path, 'r') + local value = f:read('*a') + f:close() + return value +end + +local function exists(path) + local f = io.open(path) + if f then + f:close() + return true + else + return false + end +end + +local function ready(device) + return pcall(function() + write(device .. 'value', 0) + end) +end + +return function(which) + local device = gpio_subsystem .. 'gpio' .. which .. '/' + + if exists(device) then + write(gpio_subsystem .. 'unexport', which) + end + + write(gpio_subsystem .. 'export', which) + + while not ready(device) do + os.execute('sleep 0.001') + end + + return { + set_direction = function(direction) + write(device .. 'direction', direction) + end, + + write = function(value) + write(device .. 'value', value) + end, + + read = function() + return read(device .. 'value') + end + } +end +