Skip to content

Commit

Permalink
exposing Lua PWM API
Browse files Browse the repository at this point in the history
  • Loading branch information
rusefillc committed Apr 4, 2024
1 parent 9397521 commit b45dcef
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 18 deletions.
43 changes: 25 additions & 18 deletions firmware/controllers/lua/lua_hooks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -268,30 +268,34 @@ static P luaL_checkPwmIndex(lua_State* l, int pos) {
#define PWM_FREQ_PWM 1000
#endif

static int lua_startPwm(lua_State* l) {
auto p = luaL_checkPwmIndex(l, 1);
auto freq = luaL_checknumber(l, 2);
auto duty = luaL_checknumber(l, 3);

if (duty < 0 || duty > PWM_MAX_DUTY) {
luaL_error(l, "Duty parameter should be from 0 to 1 got %f", duty);
return 0;
}

void startPwm(int index, float freq, float duty) {
// clamp to 1..1000 hz, this line would turn 0hz on/off PWM into 1hz behind the scenes
freq = clampF(1, freq, 1000);

brain_pin_e pwmPin = engineConfiguration->luaOutputPins[p.idx];
brain_pin_e pwmPin = engineConfiguration->luaOutputPins[index];

startSimplePwmExt(
&p.pwm, "lua", &engine->executor,
pwmPin, &enginePins.luaOutputPins[p.idx],
&pwms[index], "lua", &engine->executor,
pwmPin, &enginePins.luaOutputPins[index],
freq, duty
);

efiPrintf("LUA PWM on %s at %f initial duty",
hwPortname(pwmPin),
PERCENT_MULT * duty);
}

static int lua_startPwm(lua_State* l) {
auto p = luaL_checkPwmIndex(l, 1);
auto freq = luaL_checknumber(l, 2);
auto duty = luaL_checknumber(l, 3);

if (duty < 0 || duty > PWM_MAX_DUTY) {
luaL_error(l, "Duty parameter should be from 0 to 1 got %f", duty);
return 0;
}

startPwm(p.idx, freq, duty);

return 0;
}
Expand All @@ -303,14 +307,17 @@ void luaDeInitPins() {
}
}

static int lua_setPwmDuty(lua_State* l) {
auto p = luaL_checkPwmIndex(l, 1);
auto duty = luaL_checknumber(l, 2);

void setPwmDuty(int index, float duty) {
// clamp to 0..1
duty = clampF(0, duty, 1);

p.pwm.setSimplePwmDutyCycle(duty);
pwms[index].setSimplePwmDutyCycle(duty);
}

static int lua_setPwmDuty(lua_State* l) {
auto p = luaL_checkPwmIndex(l, 1);
auto duty = luaL_checknumber(l, 2);
setPwmDuty(p.idx, duty);

return 0;
}
Expand Down
3 changes: 3 additions & 0 deletions firmware/controllers/lua/lua_hooks.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ struct LuaOverrideSensor final : public Sensor {
float overrideValue = -1;
SensorType m_underlyingType;
};

void startPwm(int index, float freq, float duty);
void setPwmDuty(int index, float duty);

0 comments on commit b45dcef

Please sign in to comment.