vsergeev / lua-periphery

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

GPIO(pin, "preserve") is not working on raspberry pi zero #16

Closed vesley closed 6 years ago

vesley commented 7 years ago

Following command is not working on a raspberry pi zero:

local gpio_10 = GPIO(10, "preserve")

Following error is thrown:

GPIO_ERROR_IO
Error: Writing GPIO 'value': Operation not permitted [errno 1]

But when I open the pin 10 with "out" for the first time, I can open it after that with "preserve" without any error. The lua script is executed from a nginx web server, using the libnginx_mod_http_lua module with the user www-data. The user www-data belongs to the gpio group.

Here is the lua code:

local GPIO = require('periphery').GPIO

local gpio_10 = GPIO(10, "preserve")
local value = gpio_10:read()
status, err = pcall(function() gpio_10:write(not value) end)
if status==false then
        value = tostring(err)
end
gpio_10:close()

local file = io.open("/var/www/html/lua/index.html","r")
local tmp = file:read("*a")
file:close(file)

tmp = tmp:gsub("$$HEAD","Raspberry Pi Zero GPIO test")
tmp = tmp:gsub("$$PIN10",tostring(value))

ngx.say(tmp)
vsergeev commented 6 years ago

This is technically expected behavior. The first time you export and open a GPIO, the direction defaults to in.

I'm presuming you want to preserve the output direction and state, so one easy workaround is to check and update the direction to out after opening it with preserve:

local gpio_10 = GPIO(10, "preserve")
if gpio_10.direction ~= "out" then
    gpio_10.direction = "out"
end

Let me know if you run into any more issues.