Jump to content

Lua: Difference between revisions

From epicEFI Wiki
No edit summary
No edit summary
Line 1: Line 1:
<nowiki>#</nowiki> Lua Scripting
# Lua Scripting


<nowiki>**</nowiki>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.


<nowiki>##</nowiki> 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.


<nowiki>##</nowiki> 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:


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


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


<nowiki>##</nowiki> 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)
- [Hooks for CAN bus communications](#can-bus)
- [Inputs from sensors can be read directly](#input). [You can also produce sensor values](#set-sensor-value) with Lua.
- [Inputs from sensors can be read directly](#input). [You can also produce sensor values](#set-sensor-value) with Lua.
- [ECU general purpose outputs](#output)
- [ECU general purpose outputs](#output)
- [Aspects of the engine can be controlled directly](#engine-control)
- [Aspects of the engine can be controlled directly](#engine-control)
- ECU configuration can be accessed (read/write) via [`getCalibration()`](#getcalibrationname) and [`setCalibration()`](#setcalibrationname-value-needevent).
- ECU configuration can be accessed (read/write) via [`getCalibration()`](#getcalibrationname) and [`setCalibration()`](#setcalibrationname-value-needevent).
 
  - 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 [Variable Status Selector](<nowiki>https://content.epicefi.com/docs/variable_status_selector.html</nowiki>).
 
- 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()`](#getoutputname), and some can be changed via dedicated setters (e.g. [`setClutchUpState()`](#setclutchupstatevalue)). 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 [Variable Status Selector](<nowiki>https://content.epicefi.com/docs/variable_status_selector.html</nowiki>).
 
- 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).


<nowiki>##</nowiki> 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 `print()` output.
- Unless otherwise noted, all `index` parameters are **zero-based** (first element is index `0`).
- Unless otherwise noted, all `index` parameters are **zero-based** (first element is index `0`).


<nowiki>##</nowiki> 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 `onTick` is called periodically by epicEFI.
Line 54: Line 44:


```lua
```lua
print('Hello Lua startup!')
print('Hello Lua startup!')


function onTick()
function onTick()
 
    print('Hello onTick()')
    print('Hello onTick()')
 
end
end
```
```


<nowiki>###</nowiki> 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`.
`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`.


```lua
```lua
n = 0
n = 0
setTickRate(5) -- 5 Hz
setTickRate(5) -- 5 Hz
function onTick()
function onTick()
 
    print('Hello Lua: ' .. n)
    print('Hello Lua: ' .. n)
    n = n + 1
 
    n = n + 1
 
end
end
```
```


<nowiki>###</nowiki> Editing scripts
### Editing scripts


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


<nowiki>##</nowiki> Hooks / function reference
## Hooks / function reference


<nowiki>###</nowiki> User settings
### User settings


<nowiki>####</nowiki> `getOutput(name)`
#### `getOutput(name)`


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


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


<nowiki>####</nowiki> `setClutchUpState(value)`
#### `setClutchUpState(value)`


<nowiki>####</nowiki> `setBrakePedalState(value)`
#### `setBrakePedalState(value)`


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


<nowiki>####</nowiki> `setAcRequestState(value)`
#### `setAcRequestState(value)`


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


<nowiki>####</nowiki> `setEtbDisabled(value)`
#### `setEtbDisabled(value)`


<nowiki>####</nowiki> `setIgnDisabled(value)`
#### `setIgnDisabled(value)`


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


<nowiki>####</nowiki> `setAcDisabled(value)`
#### `setAcDisabled(value)`


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


<nowiki>####</nowiki> `getTimeSinceAcToggleMs()`
#### `getTimeSinceAcToggleMs()`


<nowiki>####</nowiki> `getCalibration(name)`
#### `getCalibration(name)`


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


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


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


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 `needEvent`.
Line 133: Line 112:
Example: `setCalibration("cranking.rpm", 900, false)`
Example: `setCalibration("cranking.rpm", 900, false)`


<nowiki>####</nowiki> `burnconfig`
#### `burnconfig`


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.


<nowiki>####</nowiki> `findSetting(name, defaultValue)`
#### `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.
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)
  - `defaultValue`: Returned if the setting is not found


  - `name`: Variable name (matches the configuration field name)
### `isFirmwareError`
 
  - `defaultValue`: Returned if the setting is not found
 
<nowiki>###</nowiki> `isFirmwareError`


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


<nowiki>###</nowiki> Engine control
### Engine control


<nowiki>####</nowiki> `startCrankingEngine()`
#### `startCrankingEngine()`


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


<nowiki>####</nowiki> `stopEngine()`
#### `stopEngine()`


<nowiki>####</nowiki> `isEngineStopRequested()`
#### `isEngineStopRequested()`


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


<nowiki>####</nowiki> `setLaunchTrigger`
#### `setLaunchTrigger`


<nowiki>####</nowiki> `setSparkSkipRatio(ratio)`
#### `setSparkSkipRatio(ratio)`


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


Useful for torque reduction.
Useful for torque reduction.


<nowiki>####</nowiki> `setSparkHardSkipRatio(ratio)`
#### `setSparkHardSkipRatio(ratio)`


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


<nowiki>####</nowiki> `setIdleAdd(percent)`
#### `setIdleAdd(percent)`


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


<nowiki>####</nowiki> `setFuelAdd(amount)`
#### `setFuelAdd(amount)`


<nowiki>*</nowiki>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()`](#setfuelmultcoeff); starts at 0.


<nowiki>####</nowiki> `setFuelMult(coeff)`
#### `setFuelMult(coeff)`


<nowiki>*</nowiki>Currently not functional.*
*Currently not functional.*


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


<nowiki>####</nowiki> `setBoostTargetAdd(amount)`
#### `setBoostTargetAdd(amount)`


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


<nowiki>####</nowiki> `setBoostTargetMult(coeff)`
#### `setBoostTargetMult(coeff)`


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


<nowiki>####</nowiki> `setBoostDutyAdd(amount)`
#### `setBoostDutyAdd(amount)`


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


<nowiki>####</nowiki> `setTimingAdd(angle)`
#### `setTimingAdd(angle)`


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


<nowiki>####</nowiki> `setTimingMult(coeff)`
#### `setTimingMult(coeff)`


Useful for torque reduction.
Useful for torque reduction.


<nowiki>####</nowiki> `setEtbAdd(percent)`
#### `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).
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).
Line 221: Line 196:
Useful for torque reduction.
Useful for torque reduction.


<nowiki>###</nowiki> Timer
### Timer


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


<nowiki>####</nowiki> `reset`
#### `reset`


`yourTimer:reset()` resets the timer.
`yourTimer:reset()` resets the timer.


<nowiki>####</nowiki> `getElapsedSeconds`
#### `getElapsedSeconds`


`yourTimer:getElapsedSeconds()` returns seconds since last reset.
`yourTimer:getElapsedSeconds()` returns seconds since last reset.


<nowiki>####</nowiki> `getTsButtonCount`
#### `getTsButtonCount`


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


<nowiki>###</nowiki> CAN bus
### CAN bus


<nowiki>####</nowiki> `enableCanTx(isEnabled)`
#### `enableCanTx(isEnabled)`


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


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


- **Parameters**
- **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


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


<nowiki>####</nowiki> `canRxAdd(bus, id)`
#### `canRxAdd(bus, id)`


<nowiki>####</nowiki> `canRxAdd(id, callback)`
#### `canRxAdd(id, callback)`


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


<nowiki>####</nowiki> `canRxAddMask(id, mask)`
#### `canRxAddMask(id, mask)`


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


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


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


- **Parameters**
- **Parameters**
 
  - `id`: CAN ID to listen for
  - `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.
  - `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.
  - `callback`: Function called when a matching frame arrives. If omitted, `onCanRx` is used.
 
  - `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:
CAN RX callback shape:


```lua
```lua
function onCanRx(bus, id, dlc, data)
function onCanRx(bus, id, dlc, data)
 
    -- handle frame
    -- handle frame
 
end
end
```
```


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


<nowiki>###</nowiki> SENT protocol
### SENT protocol


<nowiki>####</nowiki> `getSentValue(index)`
#### `getSentValue(index)`


<nowiki>####</nowiki> `getSentValues(index)`
#### `getSentValues(index)`


<nowiki>###</nowiki> PID
### PID


`deltaTime` is measured automatically between successive `pid:get` calls.
`deltaTime` is measured automatically between successive `pid:get` calls.


```lua
```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)
pid:setOffset(0.3)
pid:setOffset(0.3)
pid:get(target, input)
pid:get(target, input)
pid:reset()
pid:reset()


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


<nowiki>###</nowiki> Utility
### Utility


<nowiki>####</nowiki> `print(msg)`
#### `print(msg)`


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


- **Parameters:** `msg` — string or number
- **Parameters:** `msg` — string or number
- **Returns:** none
- **Returns:** none


<nowiki>####</nowiki> `vin(index)`
#### `vin(index)`


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


<nowiki>**</nowiki>Example:**
**Example:**


```lua
```lua
n = 5.5
n = 5.5
print('Hello Lua, number is: ' .. n)
print('Hello Lua, number is: ' .. n)
```
```


Output: `Hello Lua, number is: 5.5`
Output: `Hello Lua, number is: 5.5`


<nowiki>####</nowiki> `setTickRate(hz)`
#### `setTickRate(hz)`


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


- **Parameters:** `hz` — clamped to 1–200 Hz
- **Parameters:** `hz` — clamped to 1–200 Hz
- **Returns:** none
- **Returns:** none


<nowiki>####</nowiki> `mcu_standby()`
#### `mcu_standby()`


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


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


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


<nowiki>####</nowiki> `findTableIndex(name)`
#### `findTableIndex(name)`


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


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


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)
  - `tableIdx`: Table index (1–4)
  - `x`: X-axis value (often RPM)
 
  - `y`: Y-axis value (often load)
  - `x`: X-axis value (often RPM)
 
  - `y`: Y-axis value (often load)
 
- **Returns:** table output value
- **Returns:** table output value


<nowiki>####</nowiki> `findCurveIndex(name)`
#### `findCurveIndex(name)`


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


<nowiki>####</nowiki> `curve(curveIdx, x)`
#### `curve(curveIdx, x)`


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


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


  - `curveIdx`: Curve index (1-based)
#### `setDebug(index, value)`
 
  - `x`: Axis value
 
<nowiki>####</nowiki> `setDebug(index, value)`


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:** `index` 1–7, `value` — channel value
- **Returns:** none
- **Returns:** none


<nowiki>###</nowiki> Input
### Input


<nowiki>####</nowiki> `getSensor(name)`
#### `getSensor(name)`


Reads a sensor by name, e.g. `getSensor("AcceleratorPedal")`.
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`)
- **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
- **Returns:** reading, or `nil` if the sensor is invalid or not configured


<nowiki>####</nowiki> `getSensorByIndex(index)`
#### `getSensorByIndex(index)`


Reads a sensor by enum index.
Reads a sensor by enum index.
Line 425: Line 366:
- **Returns:** reading, or `nil` on failure
- **Returns:** reading, or `nil` on failure


<nowiki>####</nowiki> `getSensorRaw(index)`
#### `getSensorRaw(index)`


Raw sensor value (usually pin voltage before scaling).
Raw sensor value (usually pin voltage before scaling).
Line 431: Line 372:
- **Returns:** raw value, or `0` if unsupported / not configured / failed
- **Returns:** raw value, or `0` if unsupported / not configured / failed


<nowiki>####</nowiki> `getAuxAnalog(index)`
#### `getAuxAnalog(index)`


Like `getSensorRaw` but for aux analog inputs — always voltage.
Like `getSensorRaw` but for aux analog inputs — always voltage.


- **Parameters:** `index` 0–3
- **Parameters:** `index` 0–3
- **Returns:** voltage, or `nil` if not configured
- **Returns:** voltage, or `nil` if not configured


<nowiki>####</nowiki> `hasSensor(index)`
#### `hasSensor(index)`


Whether a sensor slot is configured (valid or not).
Whether a sensor slot is configured (valid or not).
Line 445: Line 385:
- **Returns:** boolean
- **Returns:** boolean


<nowiki>####</nowiki> `getDigital(index)`
#### `getDigital(index)`


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


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


| 0     | Clutch down    |
#### `getAuxDigital(index)`
 
| 1     | Clutch up      |
 
| 2     | Brake switch   |
 
| 3     | AC switch      |
 
<nowiki>####</nowiki> `getAuxDigital(index)`


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.


<nowiki>####</nowiki> `readPin(pinName)`
#### `readPin(pinName)`


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. `"PD15"`). Emergency/debug only — prefer Lua aux inputs for real logic.


<nowiki>###</nowiki> Output
### Output


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


<nowiki>####</nowiki> `selfStimulateRPM(rpm)`
#### `selfStimulateRPM(rpm)`


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


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


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
  - `frequency`: 1–1000 Hz
  - `duty`: 0.0 = off, 1.0 = full on


  - `index`: 0–7
#### `setPwmDuty(index, duty)`
 
  - `frequency`: 1–1000 Hz
 
  - `duty`: 0.0 = off, 1.0 = full on
 
<nowiki>####</nowiki> `setPwmDuty(index, duty)`


<nowiki>####</nowiki> `setPwmFreq(index, frequency)`
#### `setPwmFreq(index, frequency)`


<nowiki>####</nowiki> `getGpPwm(index)`
#### `getGpPwm(index)`


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


<nowiki>####</nowiki> `setLuaGauge(index, value)`
#### `setLuaGauge(index, value)`


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


<nowiki>####</nowiki> `setDacVoltage(index, value)`
#### `setDacVoltage(index, value)`


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


<nowiki>##</nowiki> Console commands
## Console commands


- `luamemory` — Lua memory usage
- `luamemory` — Lua memory usage
- `luareset` — reset Lua VM
- `luareset` — reset Lua VM


<nowiki>##</nowiki> Examples
## Examples


Example scripts ship with the firmware under `firmware/controllers/lua/examples/` ([browse on GitHub](<nowiki>https://github.com/epicEFI/epicefi_fw/tree/master/firmware/controllers/lua/examples</nowiki>)).
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)).


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


<nowiki>###</nowiki> Timer example
### Timer example


```lua
```lua
t = Timer.new()
t = Timer.new()
timingAdd = 0
timingAdd = 0


function onTick()
function onTick()
  auxV = getAuxAnalog(0)
  tps = getSensor("TPS")
  -- check for nil if aux input is not assigned
  if auxV > 2 then
    t:reset()
  end


   auxV = getAuxAnalog(0)
  val = t:getElapsedSeconds()
 
   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)
  if t:getElapsedSeconds() < 3 then
    timingAdd = 10
  else
    timingAdd = 0
  end
  setTimingAdd(timingAdd)


  print('Hello analog ' .. auxV .. " " .. val)
end
end
```
```


<nowiki>###</nowiki> PWM
### PWM


```lua
```lua
startPwm(0, 100, 0)
startPwm(0, 100, 0)


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


<nowiki>###</nowiki> CAN transmit
### CAN transmit


```lua
```lua
function onTick()
function onTick()
  clt = getSensor("CLT")
  print('CLT ' .. clt)
  voltage0 = getSensor("aux0")


  clt = getSensor("CLT")
  txPayload = {}
 
  txPayload[1] = math.floor(((voltage0/256) - math.floor(voltage0/256))*256)
  print('CLT ' .. clt)
  txPayload[2] = math.floor(voltage0 / 256)
 
  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)


  txCan(1, 0x600, 1, txPayload)
end
end
```
```


<nowiki>###</nowiki> Set sensor value
### Set sensor value


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


```lua
```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")
vssSensor:setTimeout(3000)
vssSensor:setTimeout(3000)
function onTick()
function onTick()
 
injectedVssValue = 123.4
injectedVssValue = 123.4
vssSensor:set(injectedVssValue)
 
valFromSensor = getSensor("VehicleSpeed")
vssSensor:set(injectedVssValue)
print("VSS " .. valFromSensor)
 
valFromSensor = getSensor("VehicleSpeed")
 
print("VSS " .. valFromSensor)
 
end
end
```
```


<nowiki>###</nowiki> CAN receive
### CAN receive


```lua
```lua
canRxAdd(0x500)
canRxAdd(0x500)
canRxAdd(0x570)
canRxAdd(0x570)
function onCanRx(bus, id, dlc, data)
function onCanRx(bus, id, dlc, data)
 
print('got CAN id=' .. id .. ' dlc=' .. dlc)
print('got CAN id=' .. id .. ' dlc=' .. dlc)
if id == 0x500 then
 
  canState = data[1]
if id == 0x500 then
end
 
if id == 0x570 then
  canState = data[1]
  mcu_standby()
 
end
end
 
if id == 0x570 then
 
  mcu_standby()
 
end
 
end
end
```
```


<nowiki>###</nowiki> Table / curve
### Table / curve


```lua
```lua
tableIndex = findTableIndex("duty")
tableIndex = findTableIndex("duty")


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


Line 666: Line 545:


sparkCutCurve = findCurveIndex("sparkcut")
sparkCutCurve = findCurveIndex("sparkcut")
sparkCutByTorque = curve(sparkCutCurve, torquex)
sparkCutByTorque = curve(sparkCutCurve, torquex)
```
```


<nowiki>##</nowiki> See also
## See also
 
- [Variable Status Selector](<nowiki>https://content.epicefi.com/docs/variable_status_selector.html</nowiki>) — names, types, and hashes for your firmware
 
- [Lua examples](<nowiki>https://github.com/epicEFI/epicefi_fw/tree/master/firmware/controllers/lua/examples</nowiki>) — vehicle-specific scripts


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

Revision as of 03:15, 18 August 2026

  1. 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.
    1. 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.

    1. 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:

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

    1. Basics

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

- [Hooks for CAN bus communications](#can-bus) - [Inputs from sensors can be read directly](#input). [You can also produce sensor values](#set-sensor-value) with Lua. - [ECU general purpose outputs](#output) - [Aspects of the engine can be controlled directly](#engine-control) - ECU configuration can be accessed (read/write) via [`getCalibration()`](#getcalibrationname) and [`setCalibration()`](#setcalibrationname-value-needevent).

 - Valid calibration names for your firmware are listed in the [Variable Status Selector](https://content.epicefi.com/docs/variable_status_selector.html).

- 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).

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

- Hooks to read values from SENT sensors; see [SENT protocol](#sent-protocol). - Useful helper routines; see [Utility](#utility).

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

    1. 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`).

    1. 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:

```lua print('Hello Lua startup!')

function onTick()

   print('Hello onTick()')

end ```

      1. 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`.

```lua n = 0 setTickRate(5) -- 5 Hz function onTick()

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

end ```

      1. Editing scripts

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

    1. Hooks / function reference
      1. User settings
        1. `getOutput(name)`

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

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

        1. `setClutchUpState(value)`
        1. `setBrakePedalState(value)`

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

        1. `setAcRequestState(value)`

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

        1. `setEtbDisabled(value)`
        1. `setIgnDisabled(value)`

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

        1. `setAcDisabled(value)`

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

        1. `getTimeSinceAcToggleMs()`
        1. `getCalibration(name)`

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

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

        1. `setCalibration(name, value, needEvent)`

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

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

        1. `burnconfig`

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

        1. `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
      1. `isFirmwareError`

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

      1. Engine control
        1. `startCrankingEngine()`

Starts cranking as if the physical start button were pressed.

        1. `stopEngine()`
        1. `isEngineStopRequested()`

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

        1. `setLaunchTrigger`
        1. `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.

        1. `setSparkHardSkipRatio(ratio)`

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

        1. `setIdleAdd(percent)`

Percent added to idle (including open loop).

        1. `setFuelAdd(amount)`
  • Currently not functional.*

Fuel mass to add to injection, scaled by [`setFuelMult()`](#setfuelmultcoeff); starts at 0.

        1. `setFuelMult(coeff)`
  • Currently not functional.*

Multiplier for added fuel mass; starts at 1.0.

        1. `setBoostTargetAdd(amount)`

Additive offset for closed-loop boost target.

        1. `setBoostTargetMult(coeff)`

Multiplier for closed-loop boost target.

        1. `setBoostDutyAdd(amount)`

Additive offset for open-loop boost duty.

        1. `setTimingAdd(angle)`

Use negative values to retard timing.

        1. `setTimingMult(coeff)`

Useful for torque reduction.

        1. `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.

      1. Timer

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

        1. `reset`

`yourTimer:reset()` resets the timer.

        1. `getElapsedSeconds`

`yourTimer:getElapsedSeconds()` returns seconds since last reset.

        1. `getTsButtonCount`

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

      1. CAN bus
        1. `enableCanTx(isEnabled)`

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

        1. `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
        1. `canRxAdd(id)`
        1. `canRxAdd(bus, id)`
        1. `canRxAdd(id, callback)`
        1. `canRxAdd(bus, id, callback)`
        1. `canRxAddMask(id, mask)`
        1. `canRxAddMask(bus, id, mask)`
        1. `canRxAddMask(id, mask, callback)`
        1. `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:

```lua function onCanRx(bus, id, dlc, data)

   -- handle frame

end ```

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

      1. SENT protocol
        1. `getSentValue(index)`
        1. `getSentValues(index)`
      1. PID

`deltaTime` is measured automatically between successive `pid:get` calls.

```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() ```

      1. Utility
        1. `print(msg)`

Prints a line to the ECU log.

- **Parameters:** `msg` — string or number - **Returns:** none

        1. `vin(index)`

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

    • Example:**

```lua n = 5.5 print('Hello Lua, number is: ' .. n) ```

Output: `Hello Lua, number is: 5.5`

        1. `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

        1. `mcu_standby()`

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

        1. `interpolate(x1, y1, x2, y2, x)`

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

        1. `findTableIndex(name)`

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

        1. `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

        1. `findCurveIndex(name)`

Returns the index of a script curve by name.

        1. `curve(curveIdx, x)`

Looks up a value from a script curve.

- **Parameters**

 - `curveIdx`: Curve index (1-based)
 - `x`: Axis value
        1. `setDebug(index, value)`

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

- **Parameters:** `index` 1–7, `value` — channel value - **Returns:** none

      1. Input
        1. `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

        1. `getSensorByIndex(index)`

Reads a sensor by enum index.

- **Returns:** reading, or `nil` on failure

        1. `getSensorRaw(index)`

Raw sensor value (usually pin voltage before scaling).

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

        1. `getAuxAnalog(index)`

Like `getSensorRaw` but for aux analog inputs — always voltage.

- **Parameters:** `index` 0–3 - **Returns:** voltage, or `nil` if not configured

        1. `hasSensor(index)`

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

- **Returns:** boolean

        1. `getDigital(index)`

Reads a built-in digital input.

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

        1. `getAuxDigital(index)`

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

        1. `readPin(pinName)`

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

      1. Output

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

        1. `selfStimulateRPM(rpm)`

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

        1. `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
        1. `setPwmDuty(index, duty)`
        1. `setPwmFreq(index, frequency)`
        1. `getGpPwm(index)`

Current GPPWM output percent (index 0–3).

        1. `setLuaGauge(index, value)`

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

        1. `setDacVoltage(index, value)`

Only on boards with DAC hardware enabled.

    1. Console commands

- `luamemory` — Lua memory usage - `luareset` — reset Lua VM

    1. 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)).

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

      1. Timer example

```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 ```

      1. PWM

```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 ```

      1. CAN transmit

```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 ```

      1. Set sensor value

Use standard sensor names from TunerStudio Live Data.

```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 ```

      1. CAN receive

```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 ```

      1. Table / curve

```lua tableIndex = findTableIndex("duty")

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

dutyCycle = table3d(tableIndex, TurbochargerSpeed, tps)

sparkCutCurve = findCurveIndex("sparkcut") sparkCutByTorque = curve(sparkCutCurve, torquex) ```

    1. See also

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