Jump to content

Lua: Difference between revisions

From epicEFI Wiki
No edit summary
No edit summary
Line 1: Line 1:
# Lua Scripting
= Lua Scripting =


**TL;DR:** Connect with TunerStudio, open the **Lua** tab (or use epicEFI Console), and edit your script there. Lua runs on the ECU for live scripting. The most popular use case is CAN bus integration.
'''TL;DR:''' Connect with TunerStudio, open the '''Lua''' tab (or use epicEFI Console), and edit your script there. Lua runs on the ECU for live scripting. The most popular use case is CAN bus integration.


## Introduction
== Introduction ==


epicEFI gives you a lot of flexibility — enough to build user-defined control strategies for primary and auxiliary actuators. Boards with an **F7** or **H7** MCU (EpicECU, M144H7, M144F7RED, etc.) have the most headroom for Lua. F4 boards (MEGA100F4, UAEFI) also support Lua but with tighter memory limits.
epicEFI gives you a lot of flexibility — enough to build user-defined control strategies for primary and auxiliary actuators. Boards with an '''F7''' or '''H7''' MCU (EpicECU, M144H7, M144F7RED, etc.) have the most headroom for Lua. F4 boards (MEGA100F4, UAEFI) also support Lua but with tighter memory limits.


## Variable names and hashes
== Variable names and hashes ==


Calibration names, output channel names, variable types (CONFIG GETTER/SETTER, OUTPC GETTER/SETTER), and their **djb2 hashes** depend on your exact firmware build. Do not guess — look them up here:
Calibration names, output channel names, variable types (CONFIG GETTER/SETTER, OUTPC GETTER/SETTER), and their '''djb2 hashes''' depend on your exact firmware build. Do not guess — look them up here:


**[Variable Status Selector](https://content.epicefi.com/docs/variable_status_selector.html)**
'''[https://content.epicefi.com/docs/variable_status_selector.html Variable Status Selector]'''


Use this tool when calling `getCalibration()` / `setCalibration()`, `getOutput()`, configuring user-table axes, or reading/writing variables over EPIC CAN.
Use this tool when calling <code>getCalibration()</code> / <code>setCalibration()</code>, <code>getOutput()</code>, configuring user-table axes, or reading/writing variables over EPIC CAN.


## Basics
== Basics ==


epicEFI provides hooks to interface with the firmware, manipulate its state, and read/write configuration:
epicEFI provides hooks to interface with the firmware, manipulate its state, and read/write configuration:


- [Hooks for CAN bus communications](#can-bus)
* [[#CAN bus|Hooks for CAN bus communications]]
- [Inputs from sensors can be read directly](#input). [You can also produce sensor values](#set-sensor-value) with Lua.
* [[#Input|Inputs from sensors can be read directly]]. [[#Set sensor value|You can also produce sensor values]] with Lua.
- [ECU general purpose outputs](#output)
* [[#Output|ECU general purpose outputs]]
- [Aspects of the engine can be controlled directly](#engine-control)
* [[#Engine control|Aspects of the engine can be controlled directly]]
- ECU configuration can be accessed (read/write) via [`getCalibration()`](#getcalibrationname) and [`setCalibration()`](#setcalibrationname-value-needevent).
* ECU configuration can be accessed (read/write) via [[#getCalibration(name)|<code>getCalibration()</code>]] and [[#setCalibration(name, value, needEvent)|<code>setCalibration()</code>]].
  - Valid calibration names for your firmware are listed in the [Variable Status Selector](https://content.epicefi.com/docs/variable_status_selector.html).
** Valid calibration names for your firmware are listed in the [https://content.epicefi.com/docs/variable_status_selector.html Variable Status Selector].
- ECU internal state (logic outputs / Live Data values) can be read via [`getOutput()`](#getoutputname), and some can be changed via dedicated setters (e.g. [`setClutchUpState()`](#setclutchupstatevalue)). See [Output](#output).
* ECU internal state (logic outputs / Live Data values) can be read via [[#getOutput(name)|<code>getOutput()</code>]], and some can be changed via dedicated setters (e.g. [[#setClutchUpState(value)|<code>setClutchUpState()</code>]]). See [[#Output|Output]].
  - Valid output names for your firmware are listed in the [Variable Status Selector](https://content.epicefi.com/docs/variable_status_selector.html).
** Valid output names for your firmware are listed in the [https://content.epicefi.com/docs/variable_status_selector.html Variable Status Selector].
- Hooks to read values from SENT sensors; see [SENT protocol](#sent-protocol).
* Hooks to read values from SENT sensors; see [[#SENT protocol|SENT protocol]].
- Useful helper routines; see [Utility](#utility).
* Useful helper routines; see [[#Utility|Utility]].


Some example uses are in [Examples](#examples).
Some example uses are in [[#Examples|Examples]].


## Conventions
== Conventions ==


- The Lua interpreter reports errors when something is wrong; check epicEFI Console / TunerStudio Lua output for errors and `print()` output.
* The Lua interpreter reports errors when something is wrong; check epicEFI Console / TunerStudio Lua output for errors and <code>print()</code> output.
- Unless otherwise noted, all `index` parameters are **zero-based** (first element is index `0`).
* Unless otherwise noted, all <code>index</code> parameters are '''zero-based''' (first element is index <code>0</code>).


## Writing Your Script
== Writing Your Script ==


The entire Lua script is loaded at startup. After that, a function named `onTick` is called periodically by epicEFI.
The entire Lua script is loaded at startup. After that, a function named <code>onTick</code> is called periodically by epicEFI.


Simple startup example:
Simple startup example:


```lua
<syntaxhighlight lang="lua">
print('Hello Lua startup!')
print('Hello Lua startup!')


Line 49: Line 49:
     print('Hello onTick()')
     print('Hello onTick()')
end
end
```
</syntaxhighlight>


### Controlling the tick rate
=== Controlling the tick rate ===


`setTickRate(hz)` sets how often epicEFI calls `onTick`. If your script does heavy work, it may run slower than the requested rate. The Lua VM runs at low priority relative to engine control, so you cannot starve critical ECU functions — set the rate to whatever your script needs. `onCanRx` runs at the same rate as `onTick`.
<code>setTickRate(hz)</code> sets how often epicEFI calls <code>onTick</code>. If your script does heavy work, it may run slower than the requested rate. The Lua VM runs at low priority relative to engine control, so you cannot starve critical ECU functions — set the rate to whatever your script needs. <code>onCanRx</code> runs at the same rate as <code>onTick</code>.


```lua
<syntaxhighlight lang="lua">
n = 0
n = 0
setTickRate(5) -- 5 Hz
setTickRate(5) -- 5 Hz
Line 62: Line 62:
     n = n + 1
     n = n + 1
end
end
```
</syntaxhighlight>


### Editing scripts
=== Editing scripts ===


An editor with [Lua Language Server](https://github.com/LuaLS/lua-language-server#install) (LSP) support makes writing scripts much easier.
An editor with [https://github.com/LuaLS/lua-language-server#install Lua Language Server] (LSP) support makes writing scripts much easier.


## Hooks / function reference
== Hooks / function reference ==


### User settings
=== User settings ===


#### `getOutput(name)`
==== <code>getOutput(name)</code> ====


Example: `getOutput("clutchUpState")` or `getOutput("brakePedalState")`.
Example: <code>getOutput("clutchUpState")</code> or <code>getOutput("brakePedalState")</code>.


Valid output names for your firmware: [Variable Status Selector](https://content.epicefi.com/docs/variable_status_selector.html).
Valid output names for your firmware: [https://content.epicefi.com/docs/variable_status_selector.html Variable Status Selector].


#### `setClutchUpState(value)`
==== <code>setClutchUpState(value)</code> ====


#### `setBrakePedalState(value)`
==== <code>setBrakePedalState(value)</code> ====


Use `setBrakePedalState` to report a CAN-based brake pedal to epicEFI.
Use <code>setBrakePedalState</code> to report a CAN-based brake pedal to epicEFI.


#### `setAcRequestState(value)`
==== <code>setAcRequestState(value)</code> ====


Use `setAcRequestState` to report a CAN-based A/C request.
Use <code>setAcRequestState</code> to report a CAN-based A/C request.


#### `setEtbDisabled(value)`
==== <code>setEtbDisabled(value)</code> ====


#### `setIgnDisabled(value)`
==== <code>setIgnDisabled(value)</code> ====


Use `setIgnDisabled` for cranking safety and other ignition-cut strategies.
Use <code>setIgnDisabled</code> for cranking safety and other ignition-cut strategies.


#### `setAcDisabled(value)`
==== <code>setAcDisabled(value)</code> ====


Disable/suppress A/C regardless of how it would otherwise be enabled.
Disable/suppress A/C regardless of how it would otherwise be enabled.


#### `getTimeSinceAcToggleMs()`
==== <code>getTimeSinceAcToggleMs()</code> ====


#### `getCalibration(name)`
==== <code>getCalibration(name)</code> ====


Returns the current value of a scalar calibration setting. Example: `getCalibration("cranking.rpm")`.
Returns the current value of a scalar calibration setting. Example: <code>getCalibration("cranking.rpm")</code>.


Full list of valid names: [Variable Status Selector](https://content.epicefi.com/docs/variable_status_selector.html).
Full list of valid names: [https://content.epicefi.com/docs/variable_status_selector.html Variable Status Selector].


#### `setCalibration(name, value, needEvent)`
==== <code>setCalibration(name, value, needEvent)</code> ====


Sets a calibration value. Optionally fires a calibration change event depending on `needEvent`.
Sets a calibration value. Optionally fires a calibration change event depending on <code>needEvent</code>.


Example: `setCalibration("cranking.rpm", 900, false)`
Example: <code>setCalibration("cranking.rpm", 900, false)</code>


#### `burnconfig`
==== <code>burnconfig</code> ====


Schedules a write of current calibration to flash once the engine is stopped.
Schedules a write of current calibration to flash once the engine is stopped.


#### `findSetting(name, defaultValue)`
==== <code>findSetting(name, defaultValue)</code> ====


Finds a user setting by name and returns its numeric value. Useful when the script author and the tuner are different people, or when editing is done only through TunerStudio fields rather than the Lua editor.
Finds a user setting by name and returns its numeric value. Useful when the script author and the tuner are different people, or when editing is done only through TunerStudio fields rather than the Lua editor.


- **Parameters**
* '''Parameters'''
  - `name`: Variable name (matches the configuration field name)
** <code>name</code>: Variable name (matches the configuration field name)
  - `defaultValue`: Returned if the setting is not found
** <code>defaultValue</code>: Returned if the setting is not found


### `isFirmwareError`
=== <code>isFirmwareError</code> ===


Returns `true` if the ECU is in a critical/fatal error state.
Returns <code>true</code> if the ECU is in a critical/fatal error state.


### Engine control
=== Engine control ===


#### `startCrankingEngine()`
==== <code>startCrankingEngine()</code> ====


Starts cranking as if the physical start button were pressed.
Starts cranking as if the physical start button were pressed.


#### `stopEngine()`
==== <code>stopEngine()</code> ====


#### `isEngineStopRequested()`
==== <code>isEngineStopRequested()</code> ====


Returns `true` if an engine stop was requested (by Lua or the start/stop button) within the last five seconds.
Returns <code>true</code> if an engine stop was requested (by Lua or the start/stop button) within the last five seconds.


#### `setLaunchTrigger`
==== <code>setLaunchTrigger</code> ====


#### `setSparkSkipRatio(ratio)`
==== <code>setSparkSkipRatio(ratio)</code> ====


- `setSparkSkipRatio(0)` — skip 0% of ignition events (no skip)
* <code>setSparkSkipRatio(0)</code> — skip 0% of ignition events (no skip)
- `setSparkSkipRatio(0.5)` — skip half of ignition events (never two consecutive skips)
* <code>setSparkSkipRatio(0.5)</code> — skip half of ignition events (never two consecutive skips)


Useful for torque reduction.
Useful for torque reduction.


#### `setSparkHardSkipRatio(ratio)`
==== <code>setSparkHardSkipRatio(ratio)</code> ====


- `setSparkHardSkipRatio(0)` — no skip
* <code>setSparkHardSkipRatio(0)</code> — no skip
- `setSparkHardSkipRatio(0.75)` — skip 75% of ignition events
* <code>setSparkHardSkipRatio(0.75)</code> — skip 75% of ignition events


#### `setIdleAdd(percent)`
==== <code>setIdleAdd(percent)</code> ====


Percent added to idle (including open loop).
Percent added to idle (including open loop).


#### `setFuelAdd(amount)`
==== <code>setFuelAdd(amount)</code> ====


*Currently not functional.*
''Currently not functional.''


Fuel mass to add to injection, scaled by [`setFuelMult()`](#setfuelmultcoeff); starts at 0.
Fuel mass to add to injection, scaled by [[#setFuelMult(coeff)|<code>setFuelMult()</code>]]; starts at 0.


#### `setFuelMult(coeff)`
==== <code>setFuelMult(coeff)</code> ====


*Currently not functional.*
''Currently not functional.''


Multiplier for added fuel mass; starts at 1.0.
Multiplier for added fuel mass; starts at 1.0.


#### `setBoostTargetAdd(amount)`
==== <code>setBoostTargetAdd(amount)</code> ====


Additive offset for closed-loop boost target.
Additive offset for closed-loop boost target.


#### `setBoostTargetMult(coeff)`
==== <code>setBoostTargetMult(coeff)</code> ====


Multiplier for closed-loop boost target.
Multiplier for closed-loop boost target.


#### `setBoostDutyAdd(amount)`
==== <code>setBoostDutyAdd(amount)</code> ====


Additive offset for open-loop boost duty.
Additive offset for open-loop boost duty.


#### `setTimingAdd(angle)`
==== <code>setTimingAdd(angle)</code> ====


Use negative values to retard timing.
Use negative values to retard timing.


#### `setTimingMult(coeff)`
==== <code>setTimingMult(coeff)</code> ====


Useful for torque reduction.
Useful for torque reduction.


#### `setEtbAdd(percent)`
==== <code>setEtbAdd(percent)</code> ====


ETB adder as a percent of wide-open: e.g. `10` adds +10%. Static offset on top of the computed position (TPS 5% + `10` → 15% ETB command).
ETB adder as a percent of wide-open: e.g. <code>10</code> adds +10%. Static offset on top of the computed position (TPS 5% + <code>10</code> → 15% ETB command).


Useful for torque reduction.
Useful for torque reduction.


### Timer
=== Timer ===


`yourTimer = Timer.new()` creates a timer object.
<code>yourTimer = Timer.new()</code> creates a timer object.


#### `reset`
==== <code>reset</code> ====


`yourTimer:reset()` resets the timer.
<code>yourTimer:reset()</code> resets the timer.


#### `getElapsedSeconds`
==== <code>getElapsedSeconds</code> ====


`yourTimer:getElapsedSeconds()` returns seconds since last reset.
<code>yourTimer:getElapsedSeconds()</code> returns seconds since last reset.


#### `getTsButtonCount`
==== <code>getTsButtonCount</code> ====


`getTsButtonCount(X)` returns how many times Lua button **X** was pressed in TunerStudio. See `ts-button-example.lua` in the firmware examples.
<code>getTsButtonCount(X)</code> returns how many times Lua button '''X''' was pressed in TunerStudio. See <code>ts-button-example.lua</code> in the firmware examples.


### CAN bus
=== CAN bus ===


#### `enableCanTx(isEnabled)`
==== <code>enableCanTx(isEnabled)</code> ====


Enabled by default. Use `enableCanTx(false)` to suppress CAN transmit from Lua.
Enabled by default. Use <code>enableCanTx(false)</code> to suppress CAN transmit from Lua.


#### `txCan(bus, ID, isExt, payload)`
==== <code>txCan(bus, ID, isExt, payload)</code> ====


- **Parameters**
* '''Parameters'''
  - `bus`: Hardware CAN bus index — typically `1` on single-CAN boards; `1` or `2` on dual-CAN boards (EpicECU, M144H7, etc.)
** <code>bus</code>: Hardware CAN bus index — typically <code>1</code> on single-CAN boards; <code>1</code> or <code>2</code> on dual-CAN boards (EpicECU, M144H7, etc.)
  - `isExt`: `0` for 11-bit standard ID
** <code>isExt</code>: <code>0</code> for 11-bit standard ID


#### `canRxAdd(id)`
==== <code>canRxAdd(id)</code> ====


#### `canRxAdd(bus, id)`
==== <code>canRxAdd(bus, id)</code> ====


#### `canRxAdd(id, callback)`
==== <code>canRxAdd(id, callback)</code> ====


#### `canRxAdd(bus, id, callback)`
==== <code>canRxAdd(bus, id, callback)</code> ====


#### `canRxAddMask(id, mask)`
==== <code>canRxAddMask(id, mask)</code> ====


#### `canRxAddMask(bus, id, mask)`
==== <code>canRxAddMask(bus, id, mask)</code> ====


#### `canRxAddMask(id, mask, callback)`
==== <code>canRxAddMask(id, mask, callback)</code> ====


#### `canRxAddMask(bus, id, mask, callback)`
==== <code>canRxAddMask(bus, id, mask, callback)</code> ====


- **Parameters**
* '''Parameters'''
  - `id`: CAN ID to listen for
** <code>id</code>: CAN ID to listen for
  - `mask`: Applied to the received ID before comparison. Example: id `3` and mask `0xFF` matches any frame whose low 8 bits are `3`. Omit the mask to match exactly one ID.
** <code>mask</code>: Applied to the received ID before comparison. Example: id <code>3</code> and mask <code>0xFF</code> matches any frame whose low 8 bits are <code>3</code>. Omit the mask to match exactly one ID.
  - `bus`: Hardware CAN bus index. If omitted, frames from any bus are received.
** <code>bus</code>: Hardware CAN bus index. If omitted, frames from any bus are received.
  - `callback`: Function called when a matching frame arrives. If omitted, `onCanRx` is used.
** <code>callback</code>: Function called when a matching frame arrives. If omitted, <code>onCanRx</code> is used.


CAN RX callback shape:
CAN RX callback shape:


```lua
<syntaxhighlight lang="lua">
function onCanRx(bus, id, dlc, data)
function onCanRx(bus, id, dlc, data)
     -- handle frame
     -- handle frame
end
end
```
</syntaxhighlight>


For high-throughput RX, see `enableCanRxWorkaround()` in the firmware examples.
For high-throughput RX, see <code>enableCanRxWorkaround()</code> in the firmware examples.


### SENT protocol
=== SENT protocol ===


#### `getSentValue(index)`
==== <code>getSentValue(index)</code> ====


#### `getSentValues(index)`
==== <code>getSentValues(index)</code> ====


### PID
=== PID ===


`deltaTime` is measured automatically between successive `pid:get` calls.
<code>deltaTime</code> is measured automatically between successive <code>pid:get</code> calls.


```lua
<syntaxhighlight lang="lua">
-- p, i, d, min, max
-- p, i, d, min, max
pid = Pid.new(2, 0, 0, -100, 100)
pid = Pid.new(2, 0, 0, -100, 100)
Line 279: Line 279:
industrialPid:get(target, input)
industrialPid:get(target, input)
industrialPid:reset()
industrialPid:reset()
```
</syntaxhighlight>


### Utility
=== Utility ===


#### `print(msg)`
==== <code>print(msg)</code> ====


Prints a line to the ECU log.
Prints a line to the ECU log.


- **Parameters:** `msg` — string or number
* '''Parameters:''' <code>msg</code> — string or number
- **Returns:** none
* '''Returns:''' none


#### `vin(index)`
==== <code>vin(index)</code> ====


Returns the VIN character at the given zero-based index.
Returns the VIN character at the given zero-based index.


**Example:**
'''Example:'''


```lua
<syntaxhighlight lang="lua">
n = 5.5
n = 5.5
print('Hello Lua, number is: ' .. n)
print('Hello Lua, number is: ' .. n)
```
</syntaxhighlight>


Output: `Hello Lua, number is: 5.5`
Output: <code>Hello Lua, number is: 5.5</code>


#### `setTickRate(hz)`
==== <code>setTickRate(hz)</code> ====


Sets how often epicEFI calls `onTick` and `onCanRx`, in Hz. Default after reset is 10 Hz.
Sets how often epicEFI calls <code>onTick</code> and <code>onCanRx</code>, in Hz. Default after reset is 10 Hz.


- **Parameters:** `hz` — clamped to 1–200 Hz
* '''Parameters:''' <code>hz</code> — clamped to 1–200 Hz
- **Returns:** none
* '''Returns:''' none


#### `mcu_standby()`
==== <code>mcu_standby()</code> ====


Puts the MCU into standby (low current). Use with care.
Puts the MCU into standby (low current). Use with care.


#### `interpolate(x1, y1, x2, y2, x)`
==== <code>interpolate(x1, y1, x2, y2, x)</code> ====


Linear interpolation of `x` on the line through `(x1, y1)` and `(x2, y2)`.
Linear interpolation of <code>x</code> on the line through <code>(x1, y1)</code> and <code>(x2, y2)</code>.


#### `findTableIndex(name)`
==== <code>findTableIndex(name)</code> ====


Returns the index of a script table by human-readable name.
Returns the index of a script table by human-readable name.


#### `table3d(tableIdx, x, y)`
==== <code>table3d(tableIdx, x, y)</code> ====


Looks up a value from a script 3D table.
Looks up a value from a script 3D table.


- **Parameters**
* '''Parameters'''
  - `tableIdx`: Table index (1–4)
** <code>tableIdx</code>: Table index (1–4)
  - `x`: X-axis value (often RPM)
** <code>x</code>: X-axis value (often RPM)
  - `y`: Y-axis value (often load)
** <code>y</code>: Y-axis value (often load)
- **Returns:** table output value
* '''Returns:''' table output value


#### `findCurveIndex(name)`
==== <code>findCurveIndex(name)</code> ====


Returns the index of a script curve by name.
Returns the index of a script curve by name.


#### `curve(curveIdx, x)`
==== <code>curve(curveIdx, x)</code> ====


Looks up a value from a script curve.
Looks up a value from a script curve.


- **Parameters**
* '''Parameters'''
  - `curveIdx`: Curve index (1-based)
** <code>curveIdx</code>: Curve index (1-based)
  - `x`: Axis value
** <code>x</code>: Axis value


#### `setDebug(index, value)`
==== <code>setDebug(index, value)</code> ====


Sets a debug channel when ECU debug mode is **Lua**.
Sets a debug channel when ECU debug mode is '''Lua'''.


- **Parameters:** `index` 1–7, `value` — channel value
* '''Parameters:''' <code>index</code> 1–7, <code>value</code> — channel value
- **Returns:** none
* '''Returns:''' none


### Input
=== Input ===


#### `getSensor(name)`
==== <code>getSensor(name)</code> ====


Reads a sensor by name, e.g. `getSensor("AcceleratorPedal")`.
Reads a sensor by name, e.g. <code>getSensor("AcceleratorPedal")</code>.


- **Parameters:** `name` — sensor name (same names as TunerStudio Live Data, e.g. `TPS`, `CLT`, `RPM`, `MAP`)
* '''Parameters:''' <code>name</code> — sensor name (same names as TunerStudio Live Data, e.g. <code>TPS</code>, <code>CLT</code>, <code>RPM</code>, <code>MAP</code>)
- **Returns:** reading, or `nil` if the sensor is invalid or not configured
* '''Returns:''' reading, or <code>nil</code> if the sensor is invalid or not configured


#### `getSensorByIndex(index)`
==== <code>getSensorByIndex(index)</code> ====


Reads a sensor by enum index.
Reads a sensor by enum index.


- **Returns:** reading, or `nil` on failure
* '''Returns:''' reading, or <code>nil</code> on failure


#### `getSensorRaw(index)`
==== <code>getSensorRaw(index)</code> ====


Raw sensor value (usually pin voltage before scaling).
Raw sensor value (usually pin voltage before scaling).


- **Returns:** raw value, or `0` if unsupported / not configured / failed
* '''Returns:''' raw value, or <code>0</code> if unsupported / not configured / failed


#### `getAuxAnalog(index)`
==== <code>getAuxAnalog(index)</code> ====


Like `getSensorRaw` but for aux analog inputs — always voltage.
Like <code>getSensorRaw</code> but for aux analog inputs — always voltage.


- **Parameters:** `index` 0–3
* '''Parameters:''' <code>index</code> 0–3
- **Returns:** voltage, or `nil` if not configured
* '''Returns:''' voltage, or <code>nil</code> if not configured


#### `hasSensor(index)`
==== <code>hasSensor(index)</code> ====


Whether a sensor slot is configured (valid or not).
Whether a sensor slot is configured (valid or not).


- **Returns:** boolean
* '''Returns:''' boolean


#### `getDigital(index)`
==== <code>getDigital(index)</code> ====


Reads a built-in digital input.
Reads a built-in digital input.


| Index | Channel       |
{| class="wikitable"
|------:|----------------|
|-
| 0     | Clutch down   |
! Index !! Channel
| 1     | Clutch up     |
|-
| 2     | Brake switch   |
| 0 || Clutch down
| 3     | AC switch     |
|-
| 1 || Clutch up
|-
| 2 || Brake switch
|-
| 3 || AC switch
|}


#### `getAuxDigital(index)`
==== <code>getAuxDigital(index)</code> ====


Reads a user-configured digital input (index 0–7). Configure pins under **Lua Digital Aux Inputs** in TunerStudio.
Reads a user-configured digital input (index 0–7). Configure pins under '''Lua Digital Aux Inputs''' in TunerStudio.


#### `readPin(pinName)`
==== <code>readPin(pinName)</code> ====


Reads an MCU pin directly (e.g. `"PD15"`). Emergency/debug only — prefer Lua aux inputs for real logic.
Reads an MCU pin directly (e.g. <code>"PD15"</code>). Emergency/debug only — prefer Lua aux inputs for real logic.


### Output
=== Output ===


Not the same as Live Data “outputs” or GPPWM.
Not the same as Live Data “outputs” or GPPWM.


#### `selfStimulateRPM(rpm)`
==== <code>selfStimulateRPM(rpm)</code> ====


Positive RPM starts injector clicking at that speed; `0` stops self-stimulation.
Positive RPM starts injector clicking at that speed; <code>0</code> stops self-stimulation.


#### `startPwm(index, frequency, duty)`
==== <code>startPwm(index, frequency, duty)</code> ====


Starts PWM on a Lua PWM output. Pin assignment: **Lua PWM Outputs** in TunerStudio.
Starts PWM on a Lua PWM output. Pin assignment: '''Lua PWM Outputs''' in TunerStudio.


- **Parameters**
* '''Parameters'''
  - `index`: 0–7
** <code>index</code>: 0–7
  - `frequency`: 1–1000 Hz
** <code>frequency</code>: 1–1000 Hz
  - `duty`: 0.0 = off, 1.0 = full on
** <code>duty</code>: 0.0 = off, 1.0 = full on


#### `setPwmDuty(index, duty)`
==== <code>setPwmDuty(index, duty)</code> ====


#### `setPwmFreq(index, frequency)`
==== <code>setPwmFreq(index, frequency)</code> ====


#### `getGpPwm(index)`
==== <code>getGpPwm(index)</code> ====


Current GPPWM output percent (index 0–3).
Current GPPWM output percent (index 0–3).


#### `setLuaGauge(index, value)`
==== <code>setLuaGauge(index, value)</code> ====


Writes a Lua gauge (indices 1–8) for Live Data / logging.
Writes a Lua gauge (indices 1–8) for Live Data / logging.


#### `setDacVoltage(index, value)`
==== <code>setDacVoltage(index, value)</code> ====


Only on boards with DAC hardware enabled.
Only on boards with DAC hardware enabled.


## Console commands
== Console commands ==


- `luamemory` — Lua memory usage
* <code>luamemory</code> — Lua memory usage
- `luareset` — reset Lua VM
* <code>luareset</code> — reset Lua VM


## Examples
== Examples ==


Example scripts ship with the firmware under `firmware/controllers/lua/examples/` ([browse on GitHub](https://github.com/epicEFI/epicefi_fw/tree/master/firmware/controllers/lua/examples)).
Example scripts ship with the firmware under <code>firmware/controllers/lua/examples/</code> ([https://github.com/epicEFI/epicefi_fw/tree/master/firmware/controllers/lua/examples browse on GitHub]).


Notable examples: `honda-bcm.txt` (VSS from CAN / gear detection), `ford-focus-ii-pps.txt`, `bmw-idrive.txt`.
Notable examples: <code>honda-bcm.txt</code> (VSS from CAN / gear detection), <code>ford-focus-ii-pps.txt</code>, <code>bmw-idrive.txt</code>.


### Timer example
=== Timer example ===


```lua
<syntaxhighlight lang="lua">
t = Timer.new()
t = Timer.new()
timingAdd = 0
timingAdd = 0
Line 473: Line 479:
   print('Hello analog ' .. auxV .. " " .. val)
   print('Hello analog ' .. auxV .. " " .. val)
end
end
```
</syntaxhighlight>


### PWM
=== PWM ===


```lua
<syntaxhighlight lang="lua">
startPwm(0, 100, 0)
startPwm(0, 100, 0)


Line 484: Line 490:
  setPwmDuty(0, enable_pump and 1 or 0)
  setPwmDuty(0, enable_pump and 1 or 0)
end
end
```
</syntaxhighlight>


### CAN transmit
=== CAN transmit ===


```lua
<syntaxhighlight lang="lua">
function onTick()
function onTick()
   clt = getSensor("CLT")
   clt = getSensor("CLT")
Line 500: Line 506:
   txCan(1, 0x600, 1, txPayload)
   txCan(1, 0x600, 1, txPayload)
end
end
```
</syntaxhighlight>


### Set sensor value
=== Set sensor value ===


Use standard sensor names from TunerStudio Live Data.
Use standard sensor names from TunerStudio Live Data.


```lua
<syntaxhighlight lang="lua">
-- do not configure the same physical input elsewhere
-- do not configure the same physical input elsewhere
vssSensor = Sensor.new("VehicleSpeed")
vssSensor = Sensor.new("VehicleSpeed")
Line 516: Line 522:
  print("VSS " .. valFromSensor)
  print("VSS " .. valFromSensor)
end
end
```
</syntaxhighlight>


### CAN receive
=== CAN receive ===


```lua
<syntaxhighlight lang="lua">
canRxAdd(0x500)
canRxAdd(0x500)
canRxAdd(0x570)
canRxAdd(0x570)
Line 532: Line 538:
  end
  end
end
end
```
</syntaxhighlight>


### Table / curve
=== Table / curve ===


```lua
<syntaxhighlight lang="lua">
tableIndex = findTableIndex("duty")
tableIndex = findTableIndex("duty")


Line 546: Line 552:
sparkCutCurve = findCurveIndex("sparkcut")
sparkCutCurve = findCurveIndex("sparkcut")
sparkCutByTorque = curve(sparkCutCurve, torquex)
sparkCutByTorque = curve(sparkCutCurve, torquex)
```
</syntaxhighlight>


## See also
== See also ==


- [Variable Status Selector](https://content.epicefi.com/docs/variable_status_selector.html) — names, types, and hashes for your firmware
* [https://content.epicefi.com/docs/variable_status_selector.html Variable Status Selector] — names, types, and hashes for your firmware
- [Lua examples](https://github.com/epicEFI/epicefi_fw/tree/master/firmware/controllers/lua/examples) — vehicle-specific scripts
* [https://github.com/epicEFI/epicefi_fw/tree/master/firmware/controllers/lua/examples Lua examples] — vehicle-specific scripts
- [Lua ternary operator](http://lua-users.org/wiki/TernaryOperator) — Lua has no `?:`; use `and` / `or` patterns
* [http://lua-users.org/wiki/TernaryOperator Lua ternary operator] — Lua has no <code>?:</code>; use <code>and</code> / <code>or</code> patterns

Revision as of 03:17, 18 August 2026

Lua Scripting

TL;DR: Connect with TunerStudio, open the Lua tab (or use epicEFI Console), and edit your script there. Lua runs on the ECU for live scripting. The most popular use case is CAN bus integration.

Introduction

epicEFI gives you a lot of flexibility — enough to build user-defined control strategies for primary and auxiliary actuators. Boards with an F7 or H7 MCU (EpicECU, M144H7, M144F7RED, etc.) have the most headroom for Lua. F4 boards (MEGA100F4, UAEFI) also support Lua but with tighter memory limits.

Variable names and hashes

Calibration names, output channel names, variable types (CONFIG GETTER/SETTER, OUTPC GETTER/SETTER), and their djb2 hashes depend on your exact firmware build. Do not guess — look them up here:

Variable Status Selector

Use this tool when calling getCalibration() / setCalibration(), getOutput(), configuring user-table axes, or reading/writing variables over EPIC CAN.

Basics

epicEFI provides hooks to interface with the firmware, manipulate its state, and read/write configuration:

Some example uses are in Examples.

Conventions

  • The Lua interpreter reports errors when something is wrong; check epicEFI Console / TunerStudio Lua output for errors and print() output.
  • Unless otherwise noted, all index parameters are zero-based (first element is index 0).

Writing Your Script

The entire Lua script is loaded at startup. After that, a function named onTick is called periodically by epicEFI.

Simple startup example:

<syntaxhighlight lang="lua"> print('Hello Lua startup!')

function onTick()

   print('Hello onTick()')

end </syntaxhighlight>

Controlling the tick rate

setTickRate(hz) sets how often epicEFI calls onTick. If your script does heavy work, it may run slower than the requested rate. The Lua VM runs at low priority relative to engine control, so you cannot starve critical ECU functions — set the rate to whatever your script needs. onCanRx runs at the same rate as onTick.

<syntaxhighlight lang="lua"> n = 0 setTickRate(5) -- 5 Hz function onTick()

   print('Hello Lua: ' .. n)
   n = n + 1

end </syntaxhighlight>

Editing scripts

An editor with Lua Language Server (LSP) support makes writing scripts much easier.

Hooks / function reference

User settings

getOutput(name)

Example: getOutput("clutchUpState") or getOutput("brakePedalState").

Valid output names for your firmware: Variable Status Selector.

setClutchUpState(value)

setBrakePedalState(value)

Use setBrakePedalState to report a CAN-based brake pedal to epicEFI.

setAcRequestState(value)

Use setAcRequestState to report a CAN-based A/C request.

setEtbDisabled(value)

setIgnDisabled(value)

Use setIgnDisabled for cranking safety and other ignition-cut strategies.

setAcDisabled(value)

Disable/suppress A/C regardless of how it would otherwise be enabled.

getTimeSinceAcToggleMs()

getCalibration(name)

Returns the current value of a scalar calibration setting. Example: getCalibration("cranking.rpm").

Full list of valid names: Variable Status Selector.

setCalibration(name, value, needEvent)

Sets a calibration value. Optionally fires a calibration change event depending on needEvent.

Example: setCalibration("cranking.rpm", 900, false)

burnconfig

Schedules a write of current calibration to flash once the engine is stopped.

findSetting(name, defaultValue)

Finds a user setting by name and returns its numeric value. Useful when the script author and the tuner are different people, or when editing is done only through TunerStudio fields rather than the Lua editor.

  • Parameters
    • name: Variable name (matches the configuration field name)
    • defaultValue: Returned if the setting is not found

isFirmwareError

Returns true if the ECU is in a critical/fatal error state.

Engine control

startCrankingEngine()

Starts cranking as if the physical start button were pressed.

stopEngine()

isEngineStopRequested()

Returns true if an engine stop was requested (by Lua or the start/stop button) within the last five seconds.

setLaunchTrigger

setSparkSkipRatio(ratio)

  • setSparkSkipRatio(0) — skip 0% of ignition events (no skip)
  • setSparkSkipRatio(0.5) — skip half of ignition events (never two consecutive skips)

Useful for torque reduction.

setSparkHardSkipRatio(ratio)

  • setSparkHardSkipRatio(0) — no skip
  • setSparkHardSkipRatio(0.75) — skip 75% of ignition events

setIdleAdd(percent)

Percent added to idle (including open loop).

setFuelAdd(amount)

Currently not functional.

Fuel mass to add to injection, scaled by setFuelMult(); starts at 0.

setFuelMult(coeff)

Currently not functional.

Multiplier for added fuel mass; starts at 1.0.

setBoostTargetAdd(amount)

Additive offset for closed-loop boost target.

setBoostTargetMult(coeff)

Multiplier for closed-loop boost target.

setBoostDutyAdd(amount)

Additive offset for open-loop boost duty.

setTimingAdd(angle)

Use negative values to retard timing.

setTimingMult(coeff)

Useful for torque reduction.

setEtbAdd(percent)

ETB adder as a percent of wide-open: e.g. 10 adds +10%. Static offset on top of the computed position (TPS 5% + 10 → 15% ETB command).

Useful for torque reduction.

Timer

yourTimer = Timer.new() creates a timer object.

reset

yourTimer:reset() resets the timer.

getElapsedSeconds

yourTimer:getElapsedSeconds() returns seconds since last reset.

getTsButtonCount

getTsButtonCount(X) returns how many times Lua button X was pressed in TunerStudio. See ts-button-example.lua in the firmware examples.

CAN bus

enableCanTx(isEnabled)

Enabled by default. Use enableCanTx(false) to suppress CAN transmit from Lua.

txCan(bus, ID, isExt, payload)

  • Parameters
    • bus: Hardware CAN bus index — typically 1 on single-CAN boards; 1 or 2 on dual-CAN boards (EpicECU, M144H7, etc.)
    • isExt: 0 for 11-bit standard ID

canRxAdd(id)

canRxAdd(bus, id)

canRxAdd(id, callback)

canRxAdd(bus, id, callback)

canRxAddMask(id, mask)

canRxAddMask(bus, id, mask)

canRxAddMask(id, mask, callback)

canRxAddMask(bus, id, mask, callback)

  • Parameters
    • id: CAN ID to listen for
    • mask: Applied to the received ID before comparison. Example: id 3 and mask 0xFF matches any frame whose low 8 bits are 3. Omit the mask to match exactly one ID.
    • bus: Hardware CAN bus index. If omitted, frames from any bus are received.
    • callback: Function called when a matching frame arrives. If omitted, onCanRx is used.

CAN RX callback shape:

<syntaxhighlight lang="lua"> function onCanRx(bus, id, dlc, data)

   -- handle frame

end </syntaxhighlight>

For high-throughput RX, see enableCanRxWorkaround() in the firmware examples.

SENT protocol

getSentValue(index)

getSentValues(index)

PID

deltaTime is measured automatically between successive pid:get calls.

<syntaxhighlight lang="lua"> -- p, i, d, min, max pid = Pid.new(2, 0, 0, -100, 100) pid:setOffset(0.3) pid:get(target, input) pid:reset()

industrialPid = IndustrialPid.new(2, 0, 0, -100, 100) industrialPid:setOffset(0.3) industrialPid:setDerivativeFilterLoss(0.3) industrialPid:setAntiwindupFreq(0.3) industrialPid:get(target, input) industrialPid:reset() </syntaxhighlight>

Utility

print(msg)

Prints a line to the ECU log.

  • Parameters: msg — string or number
  • Returns: none

vin(index)

Returns the VIN character at the given zero-based index.

Example:

<syntaxhighlight lang="lua"> n = 5.5 print('Hello Lua, number is: ' .. n) </syntaxhighlight>

Output: Hello Lua, number is: 5.5

setTickRate(hz)

Sets how often epicEFI calls onTick and onCanRx, in Hz. Default after reset is 10 Hz.

  • Parameters: hz — clamped to 1–200 Hz
  • Returns: none

mcu_standby()

Puts the MCU into standby (low current). Use with care.

interpolate(x1, y1, x2, y2, x)

Linear interpolation of x on the line through (x1, y1) and (x2, y2).

findTableIndex(name)

Returns the index of a script table by human-readable name.

table3d(tableIdx, x, y)

Looks up a value from a script 3D table.

  • Parameters
    • tableIdx: Table index (1–4)
    • x: X-axis value (often RPM)
    • y: Y-axis value (often load)
  • Returns: table output value

findCurveIndex(name)

Returns the index of a script curve by name.

curve(curveIdx, x)

Looks up a value from a script curve.

  • Parameters
    • curveIdx: Curve index (1-based)
    • x: Axis value

setDebug(index, value)

Sets a debug channel when ECU debug mode is Lua.

  • Parameters: index 1–7, value — channel value
  • Returns: none

Input

getSensor(name)

Reads a sensor by name, e.g. getSensor("AcceleratorPedal").

  • Parameters: name — sensor name (same names as TunerStudio Live Data, e.g. TPS, CLT, RPM, MAP)
  • Returns: reading, or nil if the sensor is invalid or not configured

getSensorByIndex(index)

Reads a sensor by enum index.

  • Returns: reading, or nil on failure

getSensorRaw(index)

Raw sensor value (usually pin voltage before scaling).

  • Returns: raw value, or 0 if unsupported / not configured / failed

getAuxAnalog(index)

Like getSensorRaw but for aux analog inputs — always voltage.

  • Parameters: index 0–3
  • Returns: voltage, or nil if not configured

hasSensor(index)

Whether a sensor slot is configured (valid or not).

  • Returns: boolean

getDigital(index)

Reads a built-in digital input.

Index Channel
0 Clutch down
1 Clutch up
2 Brake switch
3 AC switch

getAuxDigital(index)

Reads a user-configured digital input (index 0–7). Configure pins under Lua Digital Aux Inputs in TunerStudio.

readPin(pinName)

Reads an MCU pin directly (e.g. "PD15"). Emergency/debug only — prefer Lua aux inputs for real logic.

Output

Not the same as Live Data “outputs” or GPPWM.

selfStimulateRPM(rpm)

Positive RPM starts injector clicking at that speed; 0 stops self-stimulation.

startPwm(index, frequency, duty)

Starts PWM on a Lua PWM output. Pin assignment: Lua PWM Outputs in TunerStudio.

  • Parameters
    • index: 0–7
    • frequency: 1–1000 Hz
    • duty: 0.0 = off, 1.0 = full on

setPwmDuty(index, duty)

setPwmFreq(index, frequency)

getGpPwm(index)

Current GPPWM output percent (index 0–3).

setLuaGauge(index, value)

Writes a Lua gauge (indices 1–8) for Live Data / logging.

setDacVoltage(index, value)

Only on boards with DAC hardware enabled.

Console commands

  • luamemory — Lua memory usage
  • luareset — reset Lua VM

Examples

Example scripts ship with the firmware under firmware/controllers/lua/examples/ (browse on GitHub).

Notable examples: honda-bcm.txt (VSS from CAN / gear detection), ford-focus-ii-pps.txt, bmw-idrive.txt.

Timer example

<syntaxhighlight lang="lua"> t = Timer.new() timingAdd = 0

function onTick()

  auxV = getAuxAnalog(0)
  tps = getSensor("TPS")
  -- check for nil if aux input is not assigned
  if auxV > 2 then
    t:reset()
  end
  val = t:getElapsedSeconds()
  if t:getElapsedSeconds() < 3 then
    timingAdd = 10
  else
    timingAdd = 0
  end
  setTimingAdd(timingAdd)
  print('Hello analog ' .. auxV .. " " .. val)

end </syntaxhighlight>

PWM

<syntaxhighlight lang="lua"> startPwm(0, 100, 0)

function onTick()

enable_pump = getSensor("RPM") > 700 and getSensor("BatteryVoltage") > 13 and getSensor("VehicleSpeed") < 60
setPwmDuty(0, enable_pump and 1 or 0)

end </syntaxhighlight>

CAN transmit

<syntaxhighlight lang="lua"> function onTick()

 clt = getSensor("CLT")
 print('CLT ' .. clt)
 voltage0 = getSensor("aux0")
 txPayload = {}
 txPayload[1] = math.floor(((voltage0/256) - math.floor(voltage0/256))*256)
 txPayload[2] = math.floor(voltage0 / 256)
 txCan(1, 0x600, 1, txPayload)

end </syntaxhighlight>

Set sensor value

Use standard sensor names from TunerStudio Live Data.

<syntaxhighlight lang="lua"> -- do not configure the same physical input elsewhere vssSensor = Sensor.new("VehicleSpeed") vssSensor:setTimeout(3000) function onTick()

injectedVssValue = 123.4
vssSensor:set(injectedVssValue)
valFromSensor = getSensor("VehicleSpeed")
print("VSS " .. valFromSensor)

end </syntaxhighlight>

CAN receive

<syntaxhighlight lang="lua"> canRxAdd(0x500) canRxAdd(0x570) function onCanRx(bus, id, dlc, data)

print('got CAN id=' .. id .. ' dlc=' .. dlc)
if id == 0x500 then
 canState = data[1]
end
if id == 0x570 then
 mcu_standby()
end

end </syntaxhighlight>

Table / curve

<syntaxhighlight lang="lua"> tableIndex = findTableIndex("duty")

TurbochargerSpeed = getSensor("TurbochargerSpeed") tps = getSensor("Tps1")

dutyCycle = table3d(tableIndex, TurbochargerSpeed, tps)

sparkCutCurve = findCurveIndex("sparkcut") sparkCutByTorque = curve(sparkCutCurve, torquex) </syntaxhighlight>

See also