Tuesday, 28 July 2015 22:16

Lua_GPIO: GPIO Read/Write Functions for Lua

GPIO Read Write Functions for Lua

This is a very simple GPIO read/write functions for Lua running on linux-based embedded system, it is based on Arduino digital input/output syntax.

Only four functions are available: pinMode, digitalWrite, digitalRead & delay

Update: Added pin_direction_status() function on 16 Oct 2015



Configures the specified pin to behave either as an input or an output

  • Syntax:
    pinMode(pin, mode)
  • Example1: Set GPIO 20 as input)
    pinMode(20, INPUT)
  • Example2: Set GPIO 20 as output)
    pinMode(20, OUTPUT)



Write a HIGH or a LOW value to a pin.

  • Syntax:
    digitalWrite(pin, value)
  • Example1: Set GPIO 20 to low
    digitalWrite(20, LOW)
  • Example2: Set GPIO 20 to high
    digitalWrite(20, HIGH)



Reads the value from a specified pin, either HIGH or LOW.

  • Syntax:
  • Example: Read value from GPIO 20, return high or low



Pauses the program for the amount of time (in seconds)

  • Syntax:
  • Example: Delay 0.5 second



 Chcek the direction of a give pin

  • Syntax:
  • Example: Check the direction of pin20, return o if it is declared as output, return i if it is declared as input, otherwise return nothing ("")


Default Configuration

This is the pin layout for GL.iNet wireless router, you can change its value to match with your hardware configuration.

GPIO = {20, 19, 18, 22, 21}

GL iNet



Example below is a Lua script running on OpenWRT which turn on GPIO 20, it then turn off after 0.5 second

  1. #!/usr/bin/lua
  2. require "gpio" --import lua_gpio library
  3. IO_pin=20 -- or IO_pin=GPIO[1]
  4. pinMode(IO_pin,OUTPUT) -- configure IO_pin as output
  5. digitalWrite(IO_pin, HIGH) -- turn it ON
  6. print(digitalRead(IO_pin)) -- print the output
  7. delay(0.5) -- wait for 0.5 second
  8. digitalWrite(IO_pin, LOW) -- turn it OFF
  9. print(digitalRead(IO_pin)) -- print the output


Another Example

  1. #!/usr/bin/lua
  2. require "gpio"
  4. ----- set GPIO as output
  5. for i=1, 5 do
  6. pinMode(GPIO[i],OUTPUT)
  7. end
  9. ----- set GPIO to HIGH
  10. for i=1, 5 do
  11. digitalWrite(GPIO[i],HIGH)
  12. delay(0.2)
  13. end
  15. ----- set GPIO to LOW
  16. for i=1, 5 do
  17. digitalWrite(GPIO[i],LOW)
  18. delay(0.2)
  19. end



Lua_GPIO source code is available here.


Related articles

Lua_ShiftOut: A 74HC595 Shift Register Library for Lua




Read 22271 times Last modified on Friday, 16 October 2015 21:12
Back to Top