LuaArduino icon indicating copy to clipboard operation
LuaArduino copied to clipboard

Add Arduino functions

Open hypercubed-music opened this issue 5 years ago • 2 comments

Hello, I am using your project and trying to figure out how to integrate standard Arduino functions. After following the instructions here: https://www.lua.org/pil/24.html I have a file called lua_arduino.h:

#include <Arduino.h>
#include <LuaArduino.h>
#include <lua/lapi.h>

static int l_pinMode(lua_State *L) {
    double pin = lua_tonumber(L, 1);
    double mode = lua_tonumber(L, 2);
    pinMode((int)pin, (int)mode);
    return 0;
}

static int l_digitalWrite(lua_State *L) {
    double pin = lua_tonumber(L, 1);
    double state = lua_tonumber(L, 2);
    digitalWrite((int)pin, (int)state);
    return 0;
}

static int l_digitalRead(lua_State *L) {
    double pin = lua_tonumber(L, 1);
    lua_pushnumber(L, digitalRead((int)pin));
    return 1;
}

static int l_analogRead(lua_State *L) {
    double pin = lua_tonumber(L, 1);
    lua_pushnumber(L, analogRead(pin));
    return 1;
}

static int l_analogWrite(lua_State *L) {
    double pin = lua_tonumber(L, 1);
    double value = lua_tonumber(L, 2);
    analogWrite((int)pin, (int)value);
    return 0;
}

static int l_millis(lua_State *L) {
    lua_pushnumber(L, millis());
    return 1;
}

static const struct luaL_reg arduinolib [] = {
    {"pinMode", l_pinMode},
    {"digitalWrite", l_digitalWrite},
    {"digitalRead", l_digitalRead},
    {"millis", l_millis},
    {"analogRead", l_analogRead},
    {"analogWrite", l_analogWrite},
    {NULL, NULL}  /* sentinel */
};

int luaopen_arduino(lua_State *L) {
    lua_register(L, "pinMode", l_pinMode);
    lua_register(L, "digitalWrite", l_digitalWrite);
    lua_register(L, "digitalRead", l_digitalRead);
    lua_register(L, "millis", l_millis);
    lua_register(L, "analogRead", l_analogRead);
    lua_register(L, "analogWrite", l_analogWrite);
}

I'm just a bit confused as to what to do next. How do I actually add these functions into the Lua interpreter?

hypercubed-music avatar Aug 19 '20 21:08 hypercubed-music

I think your main sketch will need to call your luaopen_arduino() in the setup function to register those functions, passing in the result of lua->getState()

Once you get it all working, it would be cool to include this as part of the library so that more of the built-in Arduino functions are available within Lua, hopefully expanding it over time to include the full Arduino "language" capabilities.

blackketter avatar Aug 19 '20 21:08 blackketter

Worked perfectly! I'll start adding other functions

What would be the best way to implement Arduino variables, like OUTPUT, or HIGH, etc. Would it be best to put it all in a string like

"LOW = 0\nHIGH = 1"

and then pass it to the Lua interpreter at the beginning? Or is there an easier way?

hypercubed-music avatar Aug 20 '20 01:08 hypercubed-music