用 Lua 控制你的树莓派
Lua 树莓派
![](/data/attachment/album/202306/08/170454p0tf2a6znfn2kzkf.jpg)



> 
> 学习如何使用 Lua 编程语言为物联网（IoT）设备编程，并与树莓派上的通用输入/输出（GPIO）引脚互动。
> 
> 
> 


Lua 是一种有时会被误解的语言。它与 Python 等其他语言不同，但它是一种通用的扩展语言，广泛用于游戏引擎、框架等。总的来说，我发现 Lua 对开发人员来说是一个有价值的工具，可以让他们以一些强大的方式增强和扩展他们的项目。


你可以按照 Seth Kenlon 的文章《[Lua 值得学习吗？](https://opensource.com/article/22/11/lua-worth-learning)》的介绍下载并运行常用的 Lua，该文章中还包括了简单的 Lua 代码示例。但是，要充分利用 Lua，最好将它与采用该语言的框架一起使用。在本教程中，我演示了如何使用名为 Mako Server 的框架，该框架旨在使 Lua 程序员能够轻松地编写 IoT 和 Web 应用代码。我还向你展示了如何使用 API 扩展此框架以使用树莓派的 GPIO 引脚。


### 要求


在学习本教程之前，你需要一个可以登录的正在运行的树莓派。虽然我将在本教程中编译 C 代码，但你不需要任何 C 代码经验。但是，你需要一些使用 [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) 终端的经验。


### 安装


首先，在树莓派上打开一个终端窗口并安装以下工具，以使用 Git 下载代码和编译 C 代码：



```
$ sudo apt install git unzip gcc make

```

接下来，通过运行以下命令编译开源 Mako Server 代码和 lua-periphery 库（树莓派的 GPIO 库）：



```
$ wget -O Mako-Server-Build.sh \
  https://raw.githubusercontent.com/RealTimeLogic/BAS/main/RaspberryPiBuild.sh

```

查看脚本以了解它的作用，并在你觉得没问题后运行它：



```
$ sh ./Mako-Server-Build.sh

```

编译过程可能需要一些时间，尤其是在较旧的树莓派上。编译完成后，脚本会要求你将 Mako Server 和 lua-periphery 模块安装到 `/usr/local/bin/`。我建议安装它以简化软件的使用。别担心，如果你不再需要它，你可以卸载它：



```
$ cd /usr/local/bin/
$ sudo rm mako mako.zip periphery.so

```

要测试安装，请在终端中输入 `mako`。这将启动 Mako 服务器，并在你的终端中看到一些输出。你可以按 `CTRL+C` 停止服务器。


### IoT 和 Lua


现在 Mako 服务器已在你的树莓派上设置好，你可以开始对 IoT 和 Web 应用进行编程，并使用 Lua 操作树莓派的 GPIO 引脚。Mako Server 框架为 Lua 开发人员提供了一个强大而简单的 API 来创建物联网应用，而 lua-periphery 模块让 Lua 开发人员可以与树莓派的 GPIO 引脚和其他外围设备进行交互。


首先创建一个应用目录和一个 `.preload` 脚本，其中插入用于测试 GPIO 的 Lua 代码。`.preload` 脚本是一个 Mako 服务器扩展，在应用启动时作为 Lua 脚本加载和运行。



```
$ mkdir gpiotst
$ nano gpiotst/.preload

```

将以下内容复制到 [Nano 编辑器](https://opensource.com/article/20/12/gnu-nano) 中并保存文件：



```
-- Load periphery.so and access the LED interface
local LED = require('periphery').LED

local function doled()
  local led = LED("led0") -- Open LED led0
  trace"Turn LED on"
  led:write(true)   -- Turn on LED (set max brightness)
  ba.sleep(3000)    -- 3 seconds
  trace"Turn LED off"
  led:write(false)  -- Turn off LED (set zero brightness)
  led:close()
end

ba.thread.run(doled) -- Defer execution
                     -- to after Mako has started

```

上面的 Lua 代码使用你编译并包含在 Mako 服务器中的 Lua-periphery 库控制树莓派 LED。该脚本定义了一个名为 `doled` 的函数来控制 LED。该脚本首先使用 Lua `require` 函数加载 `periphery` 库（共享库 [periphery.so](http://periphery.so)）。返回的数据是一个包含所有 GPIO API 函数的 [Lua 表](https://opensource.com/article/22/11/iterate-over-tables-lua)。但是，你只需要 LED API，你可以通过在调用 `require` 后附加 `.LED` 来直接访问它。接下来，代码定义了一个名为 `doled` 的函数，它执行以下操作：


* 通过调用 `periphery` 库中的 `LED` 函数，并将字符串 `led0` 传给它，打开树莓派主 LED，识别为 `led0`。
* 将消息 `Turn LED on` 打印到跟踪（控制台）。
* 通过调用 LED 对象上的 `write` 方法并将布尔值 `true` 传递给它来激活 LED，该值设置 LED 的最大亮度。
* 通过调用 `ba.sleep(3000)` 等待 3 秒。
* 将消息 `Turn LED off` 打印到跟踪。
* 通过调用 LED 对象上的 `write` 方法并将布尔值 `false` 传递给它来停用 LED，这会将 LED 的亮度设置为零。
* 通过调用 LED 对象上的 `close` 函数关闭 `LED`。


在 `.preload` 脚本的末尾，`doled` 函数作为参数传递给 `ba.thread.run` 函数。这允许将 `doled` 函数的执行推迟到 Mako 服务器启动之后。


要启动 `gpiotst` 应用，请按如下方式运行 Mako 服务器：



```
$ mako -l::gpiotst

```

控制台中打印以下文本：



```
Opening LED:
opening 'brightness': Permission denied.

```

访问 GPIO 需要 root 访问权限，因此按 `CTRL+C` 停止服务器并重新启动 Mako 服务器，如下所示：



```
$ sudo mako -l::gpiotst

```

现在树莓派 LED 亮起 3 秒。成功！


### Lua 解锁 IoT


在本入门教程中，你学习了如何编译 Mako 服务器，包括 GPIO Lua 模块，以及如何编写用于打开和关闭树莓派 LED 的基本 Lua 脚本。在以后的文章中，我将在本文的基础上进一步介绍 IoT 功能。


同时，你可以通过阅读它的 [文档](https://github.com/vsergeev/lua-periphery/tree/master/docs) 来更深入地研究 Lua-periphery GPIO 库，以了解有关功能以及如何将其与不同外设一起使用的更多信息。要充分利用本教程，请考虑关注 [交互式 Mako Server Lua 教程](https://tutorial.realtimelogic.com/Introduction.lsp) 以更好地了解 Lua、Web 和 IoT。编码愉快！


*（题图：MJ/4514210d-5697-4cd3-8c44-450bbe56be64）*




---


via: <https://opensource.com/article/23/3/control-your-raspberry-pi-lua>


作者：[Alan Smithee](https://opensource.com/users/alansmithee) 选题：[lkxed](https://github.com/lkxed/) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Lua is a sometimes misunderstood language. It’s different from other languages, like Python, but it’s a versatile extension language that’s widely used in game engines, frameworks, and more. Overall, I find Lua to be a valuable tool for developers, letting them enhance and expand their projects in some powerful ways.

You can download and run stock Lua as Seth Kenlon explained in his article [Is Lua worth learning](https://opensource.com/article/22/11/lua-worth-learning), which includes simple Lua code examples. However, to get the most out of Lua, it’s best to use it with a framework that has already adopted the language. In this tutorial, I demonstrate how to use a framework called Mako Server, which is designed for enabling Lua programmers to easily code IoT and web applications. I also show you how to extend this framework with an API for working with the Raspberry Pi’s GPIO pins.

## Requirements

Before following this tutorial, you need a running Raspberry Pi that you can log into. While I will be compiling C code in this tutorial, you do not need any prior experience with C code. However, you do need some experience with a [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) terminal.

## Install

To start, open a terminal window on your Raspberry Pi and install the following tools for downloading code using Git and for compiling C code:

```
````$ sudo apt install git unzip gcc make`


Next, compile the open source Mako Server code and the Lua-periphery library (the Raspberry Pi GPIO library) by running the following command:

```
``````
$ wget -O Mako-Server-Build.sh \
https://raw.githubusercontent.com/RealTimeLogic/BAS/main/RaspberryPiBuild.sh
```


Review the script to see what it does, and run it once you’re comfortable with it:

```
````$ bash ./Mako-Server-Build.sh`


The compilation process may take some time, especially on an older Raspberry Pi. Once the compilation is complete, the script asks you to install the Mako Server and the lua-periphery module to `/usr/local/bin/`

. I recommend installing it to simplify using the software. Don’t worry, if you no longer need it, you can uninstall it:

```
``````
$ cd /usr/local/bin/
$ sudo rm mako mako.zip periphery.so
```


To test the installation, type `mako`

into your terminal. This starts the Mako Server, and see some output in your terminal. You can stop the server by pressing **CTRL+C**.

## IoT and Lua

Now that the Mako Server is set up on your Raspberry Pi, you can start programming IoT and web applications and working with the Raspberry Pi’s GPIO pins using Lua. The Mako Server framework provides a powerful and easy API for Lua developers to create IoT applications and the lua-periphery module lets Lua developers interact with the Raspberry Pi’s GPIO pins and other peripheral devices.

Start by creating an application directory and a `.preload`

script, which inserts Lua code for testing the GPIO. The `.preload`

script is a Mako Server extension that’s loaded and run as a Lua script when an application is started.

```
``````
$ mkdir gpiotst
$ nano gpiotst/.preload
```


Copy the following into the [Nano editor](https://opensource.com/article/20/12/gnu-nano) and save the file:

```
``````
-- Load periphery.so and access the LED interface
local LED = require('periphery').LED
local function doled()
local led = LED("led0") -- Open LED led0
trace"Turn LED on"
led:write(true) -- Turn on LED (set max brightness)
ba.sleep(3000) -- 3 seconds
trace"Turn LED off"
led:write(false) -- Turn off LED (set zero brightness)
led:close()
end
ba.thread.run(doled) -- Defer execution
-- to after Mako has started
```



The above Lua code controls the main Raspberry Pi LED using the Lua-periphery library you compiled and included with the Mako Server. The script defines a single function called `doled`

that controls the LED. The script begins by loading the `periphery`

library (the shared library periphery.so) using the Lua `require`

function. The returned data is a [Lua table](https://opensource.com/article/22/11/iterate-over-tables-lua) with all GPIO API functions. However, you only need the LED API, and you directly access that by appending `.LED`

after calling `require`

. Next, the code defines a function called `doled`

that does the following:

- Opens the Raspberry Pi main LED identified as
`led0`

by calling the`LED`

function from the`periphery`

library and by passing it the string`led0`

. - Prints the message
`Turn LED on`

to the trace (the console). - Activates the LED by calling the
`write`

method on the LED object and passing it the Boolean value`true`

, which sets the maximum brightness of the LED. - Waits for 3 seconds by calling
`ba.sleep(3000)`

. - Prints the message
`Turn LED off`

to the trace. - Deactivates the LED by calling the
`write`

method on the LED object and passing it the Boolean value`false`

, which sets zero brightness of the LED. - Closes the
`LED`

by calling the`close`

function on the LED object.

At the end of the `.preload`

script, the `doled`

function is passed in as argument to function `ba.thread.run`

. This allows the execution of the `doled`

function to be deferred until after Mako Server has started.

To start the `gpiotst`

application, run the Mako Server as follows:

```
````$ mako -l::gpiotst`


The following text is printed in the console:

```
``````
Opening LED:
opening 'brightness': Permission denied.
```


Accessing GPIO requires root access, so stop the server by pressing **CTRL+C** and restart the Mako Server as follows:

```
````$ sudo mako -l::gpiotst`


Now the Raspberry Pi LED turns on for 3 seconds. Success!

## Lua unlocks IoT

In this primer, you learned how to compile the Mako Server, including the GPIO Lua module, and how to write a basic Lua script for turning the Raspberry Pi LED on and off. I’ll cover further IoT functions, building upon this article, in future articles.

You may in the meantime delve deeper into the Lua-periphery GPIO library by reading its [documentation](https://github.com/vsergeev/lua-periphery/tree/master/docs) to understand more about its functions and how to use it with different peripherals. To get the most out of this tutorial, consider following the [interactive Mako Server Lua tutorial](https://tutorial.realtimelogic.com/Introduction.lsp) to get a better understanding of Lua, web, and IoT. Happy coding!

## Comments are closed.