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

 

pinMode()

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)

 

digitalWrite()

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)

 

digitalRead()

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

  • Syntax:
    digitalRead(pin)
  • Example: Read value from GPIO 20, return high or low
    digitalRead(20)

 

delay()

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

  • Syntax:
    delay(second)
  • Example: Delay 0.5 second
    delay(0.5)

 

pin_direction_status()

 Chcek the direction of a give pin

  • Syntax:
    pin_direction_status(pin)
  • 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 ("")
    pin_direction_status(20)

 

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

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"
  3.  
  4. ----- set GPIO as output
  5. for i=1, 5 do
  6. pinMode(GPIO[i],OUTPUT)
  7. end
  8.  
  9. ----- set GPIO to HIGH
  10. for i=1, 5 do
  11. digitalWrite(GPIO[i],HIGH)
  12. delay(0.2)
  13. end
  14.  
  15. ----- set GPIO to LOW
  16. for i=1, 5 do
  17. digitalWrite(GPIO[i],LOW)
  18. delay(0.2)
  19. end

 

Download

Lua_GPIO source code is available here.

 

Related articles

Lua_ShiftOut: A 74HC595 Shift Register Library for Lua

 

Resources

http://wiki.openwrt.org/doc/hardware/port.gpio

Read 6634 times Last modified on Friday, 16 October 2015 21:12

Leave a comment

Back to Top