RaceCapturePro Lua Scripting: Difference between revisions
(90 intermediate revisions by 6 users not shown) | |||
Line 1: | Line 1: | ||
=RaceCapture/Pro Scripting Guide= | |||
==Example Scripts and How-Tos== | ==Example Scripts and How-Tos== | ||
A large collection of example scripts can be found in our '''[[RaceCapturePro Lua Scripting Examples|Lua Scripting Examples]]''' | |||
'''[[RaceCapturePro Lua Scripting Examples|Lua Scripting Examples]] | The [https://www.lua.org/manual/5.1/ Lua Reference Manual] can be found on [https://www.lua.org/ Lua.org] | ||
You can use [http://luaedit.sourceforge.net/ LuaEdit] to help you edit and debug your Lua code. | |||
==Lua Script Basics== | |||
===Conventions=== | |||
* All inputs and outputs are numbered starting at 0 (getGpio(0), setChannel(0), etc) | |||
* All channel values must be numbers | |||
* All virtual channel names must have no spaces (to be fixed in future revisions) | |||
====Writing your script==== | |||
=====onTick() function===== | |||
Your Lua script is centered around the onTick() function. RaceCapture/Pro will periodically call this function, and here you can define your custom tasks and logic. | |||
Example: this script will periodically write a message to the log: | |||
<pre> | |||
function onTick() | |||
println("hello from RaceCapture/Pro") | |||
end | |||
</pre> | |||
* '''Note''': There can only be one onTick() handler; if multiple are defined your script will not work properly. | |||
=====Viewing the output log===== | |||
You can observe the loading of new script and monitor and debug the behavior of your script by using the print() / println() functions. In order to see the log output, enable the "Poll Log" checkbox in the scripting window: | |||
[[image:Hello_RaceCapturePro_script.png|800px]] | |||
=====Controlling the onTick() rate===== | |||
You can control how fast your script is executed using the setTickRate() function. The tick Rate is specified in Hz, and the default rate is 1Hz, maximum of 1000Hz. | |||
* '''Note:''' actual tick rates may be slower based on the amount of processing time in your onTick() handler. | |||
<pre> | |||
count = 0 | |||
setTickRate(10) | |||
function onTick() | |||
count = count + 1 | |||
println("Tick: " ..count) | |||
end | |||
</pre> | |||
[[image:RaceCapture_tick_count.png|800px]] | |||
=====Reading and controlling inputs and outputs===== | |||
The Lua scripting enables endless combinations of custom behaviors by reading sensor values, controlling output lines, broadcasting CAN messages and writing data to the Auxiliary serial port. | |||
Example: Reading a sensor value and activating an output based on a threshold. | |||
Given: | |||
* A calibrated temperature sensor is connected to the first analog input (0); | |||
* The first GPIO is configured for output mode | |||
This script will activate the output upon crossing the temperature threshold of 212. | |||
<pre> | |||
function onTick() | |||
temperature = getAnalog(0) | |||
if temperature > 212 then | |||
setGpio(0, 1) | |||
else | |||
setGpio(0, 0) | |||
end | |||
end | |||
</pre> | |||
=====Combining multiple functions===== | |||
When combining multiple functions into one script, it's recommended to break them into multiple functions and reference them from the main onTick() function. | |||
Example: | |||
<pre> | |||
function checkTemps() | |||
[ temperature checking logic goes here ] | |||
end | |||
function checkAutoLogging() | |||
[ automatic logging logic goes here ] | |||
end | |||
function onTick() | |||
checkTemps() | |||
checkAutoLogging() | |||
end | |||
</pre> | |||
==Troubleshooting== | |||
===Debugging your script=== | |||
If you're not sure why your script is misbehaving, you can use the println() function to output messages in the log and observe how your script is behaving. | |||
Example: | |||
<pre> | |||
function onTick() | |||
temperature = getAnalog(0) | |||
println("current temp: " ..temperature) | |||
if temperature > 212 then | |||
println("over temp!") | |||
setGpio(0, 1) | |||
else | |||
println("under temp") | |||
setGpio(0, 0) | |||
end | |||
end | |||
</pre> | |||
===Out of memory issues=== | |||
If you are seeing out of memory issues, try the following: | |||
====Mark variables in your script as local==== | |||
Lua makes variables global by default, which is typically opposite of other programming languages. Since global variables consume more memory, try making variables declared in your function local: | |||
<pre> | |||
function addSomeNumbers() | |||
local var1 = 3 | |||
local var2 = 5 | |||
return var1 + var2 | |||
end | |||
</pre> | |||
====Reduce extra comments, large string variable declaration and other bloat==== | |||
* Remove comments, shorten the size of any text strings you define - these all consume memory. | |||
====Simplify your script==== | |||
* Reduce the number of variables at the top, and inline their usage in the script. This will help reduce the amount of global memory uses. | |||
* Evaluate the functions you define. Sometimes it makes sense to combine your code into fewer functions, if it turns out you only call that function once. Other times, you may need to break out a function to save space, if you need that function repeatedly. | |||
====Call the garbage collector periodically==== | |||
If your script is very close the limits of memory, regularly calling the garbage collector may help. Calling collectgarbage() in the onTick() is recommended:<pre> | |||
function onTick() | |||
collectgarbage() | |||
-- other code -- | |||
end | |||
</pre> | |||
====Try a Lua minimizer==== | |||
Minimizing/Minifying your script will compact your script, at the expense of making it harder to read. You can try an [https://mothereff.in/lua-minifier online minifier] to see if that makes a difference. | |||
* Since it makes your script harder to maintain, we recommend this as a last resort. | |||
=Lua Reference= | |||
RaceCapture/Pro uses the standard, lightweight Lua scripting language used as an extension / customization language for many software applications and especially gaming. | |||
* See [https://www.lua.org/ lua.org] for additional information on how to use the Lua language | |||
=More examples= | |||
You can see more examples in our [[RaceCapturePro Lua Scripting Examples|Lua Scripting Examples]] section. | |||
=API Reference= | |||
==General Input / Output (GPIO) Functions== | ==General Input / Output (GPIO) Functions== | ||
Line 13: | Line 170: | ||
** state: 1 = channel is high, 0 = channel is low | ** state: 1 = channel is high, 0 = channel is low | ||
When the channel is configured for input mode, a voltage high input (> 2 volts) will read as 1; a voltage low will read as 0. | * When the channel is configured for input mode, a voltage high input (> 2 volts) will read as 1; a voltage low will read as 0. | ||
* When the channel is configured as output, the channel reads 1 when the channel is activated (output transistor is connected to ground) | |||
* '''Note''': RaceCapture/Pro MK1 has internal pull-up resistors to 5V. | |||
===setGpio ( channel, state )=== | ===setGpio ( channel, state )=== | ||
Line 21: | Line 179: | ||
*params | *params | ||
** channel: integer 0 - 2 | ** channel: integer 0 - 2 | ||
** state: (int / ''(since 2.10.0)'' bool) 1 / true = output active; 0 / false = output inactive | |||
*returns: | *returns: | ||
** none | ** none | ||
Line 35: | Line 194: | ||
** none | ** none | ||
*returns | *returns | ||
** state: | ** state: true = pushbutton is depressed; false = pushbutton is not depressed | ||
==PWM / Analog Output functions== | ==PWM / Analog Output functions== | ||
'''PWM / Analog outputs only apply to RaceCapture/Pro MK1 and MK2'' | |||
===setPwmDutyCycle( channel, dutyCyclePct )=== | ===setPwmDutyCycle( channel, dutyCyclePct )=== | ||
Line 44: | Line 204: | ||
*params | *params | ||
** channel: PWM / Analog output channel 0 - 3 | ** channel: PWM / Analog output channel 0 - 3 | ||
** dutyCyclePct: Percentage value of the duty cycle as a counting number 0 - 100 | |||
*returns | *returns | ||
** none | ** none | ||
Line 70: | Line 231: | ||
*params | *params | ||
** channel: Timer channel 0 | ** channel: Timer channel. Zero based, so first channel is 0, 2nd channel is 1, and so on. | ||
** returns: RPM value | ** returns: RPM value | ||
Line 77: | Line 238: | ||
*params | *params | ||
** channel: Timer channel 0 - 3 | ** channel: Timer channel 0 - 3. Zero based, so first channel is 0, 2nd channel is 1, and so on. | ||
** returns: millisecond value | ** returns: millisecond value | ||
Line 84: | Line 245: | ||
*params | *params | ||
** channel: Timer channel 0 | ** channel: Timer channel. Zero based, so first channel is 0, 2nd channel is 1, and so on. | ||
** returns: Frequency in Hz | ** returns: Frequency in Hz | ||
Line 91: | Line 252: | ||
*params | *params | ||
** channel: Timer channel 0 - 3 | ** channel: Timer channel 0 - 3. Zero based, so first channel is 0, 2nd channel is 1, and so on. | ||
** returns: Raw timer value between 0 - 65535 | ** returns: Raw timer value between 0 - 65535 | ||
Line 102: | Line 263: | ||
===getAnalog(channel)=== | ===getAnalog(channel)=== | ||
Reads the scaled analog value for the specified analog input channel. | Reads the scaled analog value for the specified analog input channel. | ||
*params | *params | ||
** channel: Analog input channel 0 | ** channel: Analog input channel. Zero based, so first channel is 0, 2nd channel is 1, and so on. | ||
*** Note: | *** Note: the last Analog input is connected to battery voltage: | ||
**** Channel 7 on RaceCapture/Pro MK1 and MK2 | |||
****Channel 8 on RaceCapture/Pro MK3 and RaceCapture Apex | |||
****Channel 0 on RaceCapture/Track MK1 / MK2 | |||
** returns: Scaled / calculated value for the specified analog channel as defined in the channel scaling configuration | ** returns: Scaled / calculated value for the specified analog channel as defined in the channel scaling configuration | ||
Line 113: | Line 278: | ||
Reads the specified IMU channel | Reads the specified IMU channel | ||
* params | * params | ||
** channel (0 | ** channel (0 = X, 1 = Y, 2=Z, 3= Yaw, 4= Pitch, 5 = Roll) | ||
* returns | * returns | ||
** The value scaled to G force, or degrees/sec depending on the channel selected | ** The value scaled to G force, or degrees/sec depending on the channel selected | ||
Line 120: | Line 285: | ||
Reads the raw value of the specified accelerometer or yaw channel | Reads the raw value of the specified accelerometer or yaw channel | ||
* params | * params | ||
** channel (0 | ** channel (0 = X, 1 = Y, 2=Z, 3= Yaw, 4= Pitch, 5 = Roll) | ||
* returns | * returns | ||
** The raw accelerometer value | ** The raw accelerometer value | ||
Line 148: | Line 313: | ||
** The current GPS quality indicator | ** The current GPS quality indicator | ||
** 0: No fix; 1: Fixed; 2: SPS Fix; 3: Differential Fix | ** 0: No fix; 1: Fixed; 2: SPS Fix; 3: Differential Fix | ||
===getGpsSats()=== | |||
* params | |||
** (none) | |||
* returns | |||
** The number of GPS satellites currently used in the fix | |||
===getGpsTime()=== | ===getGpsTime()=== | ||
Line 162: | Line 333: | ||
* returns | * returns | ||
** The distance, in Miles | ** The distance, in Miles | ||
===getGpsAltitude()=== | |||
Provides the current GPS calculated altitude from sea level in feet. The method will return 0 if there is no GPS lock. | |||
* Added: v2.9.0 | |||
* Parameters: ''None'' | |||
* Returns: <altitude> | |||
===getGpsSec()=== | |||
Provides the number of seconds since midnight, as measured by the GPS module. ''todo: how does this relate to timezone? GMT or local?'' | |||
* params | |||
** (none) | |||
* returns | |||
** number of seconds since midnight, as measured by the attached GPS module | |||
==Lap Statistics== | |||
===getLapCount()=== | ===getLapCount()=== | ||
Line 177: | Line 363: | ||
** The last measured lap time in decimal minutes / seconds | ** The last measured lap time in decimal minutes / seconds | ||
=== | ===getPredTime()=== | ||
Provides the | ''as of 2.12.0 firmware'' | ||
Provides the current Predicted Lap time time as determined by the start/finish line configuration and measured by the attached GPS module. A training lap is required before the predicted time is valid. | |||
* params | * params | ||
** (none) | ** (none) | ||
* returns | * returns | ||
** | ** The current predicted time in decimal minutes / seconds | ||
===getAtStartFinish()=== | ===getAtStartFinish()=== | ||
Line 189: | Line 377: | ||
** (none) | ** (none) | ||
* returns | * returns | ||
** | ** true if currently within the start/finish line target, false if outside | ||
===resetLapStats()=== | |||
''since 2.16.0'' | |||
Resets Lap Statistics, including lap count, lap time, predictive time, and session time. | |||
* params | * params | ||
** | ** (none) | ||
* returns | * returns | ||
** | ** (none) | ||
=== | ==Time Functions== | ||
===getTickCount()=== | |||
Returns the number of milliseconds since power-up. | |||
* params | * params | ||
None | |||
* returns | * returns | ||
** The number of | ** The number of milliseconds since power-up | ||
==CAN Bus functions== | ==CAN Bus functions== | ||
Line 214: | Line 404: | ||
** channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware | ** channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware | ||
** baud rate: Supported baud rates: 100000, 125000, 250000, 500000, 1000000 | ** baud rate: Supported baud rates: 100000, 125000, 250000, 500000, 1000000 | ||
** termination: 1 to enable termination, 0 to disable. Defaults to 1 (enabled) ''Only available on RaceCapture/Pro MK3 and RaceCapture/Apex. On other platforms this setting has no effect''. | |||
* returns | * returns | ||
** 1 if successful, 0 if initialization fails, nil if parameters are incorrect | ** 1 if successful, 0 if initialization fails, nil if parameters are incorrect | ||
Line 242: | Line 433: | ||
* params | * params | ||
** channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware | ** channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware | ||
** timeout (optional). read timeout in milliseconds. defaults to 100ms | ** timeout (optional). read timeout in milliseconds. defaults to 100ms. For non-blocking functionality specify a timeout of 0. | ||
* returns | * returns | ||
** identifier: The Identifier value of the message, either in standard (11 bit) or extended (29 bit) format. | ** identifier: The Identifier value of the message, either in standard (11 bit) or extended (29 bit) format. | ||
Line 258: | Line 449: | ||
===setCANfilter(channel, filterId, extended, filter, mask )=== | ===setCANfilter(channel, filterId, extended, filter, mask )=== | ||
''available in firmware 2.0'' | ''available in firmware 2.0'' | ||
Sets the specified CAN filter ID, to ignore messages | Sets the specified CAN filter and mask ID, to ignore CAN messages that match a particular ID pattern. | ||
* params | * params | ||
** channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware | ** channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware | ||
Line 268: | Line 459: | ||
** 1 for success, 0 for fail, nil if parameters are incorrect | ** 1 for success, 0 for fail, nil if parameters are incorrect | ||
==OBDII functions== | |||
===readOBD2( PID )=== | ===readOBD2( PID )=== | ||
''available in firmware 2.0'' | ''available in firmware 2.0'' | ||
Line 275: | Line 467: | ||
* returns | * returns | ||
** The calculated PID value, or nil if the OBD2 PID was invalid or could not be read (e.g. CAN receive message timeout) | ** The calculated PID value, or nil if the OBD2 PID was invalid or could not be read (e.g. CAN receive message timeout) | ||
===setOBD2Delay( delayMs )=== | |||
Sets an additional delay in-between OBDII PID queries. Normally the system will query PIDs as fast as possible, in a [[RC_OBDII|round robin fashion]]. | |||
If the vehicle's ECU exhibits problems with the rate of querying, an additional delay can be added between queries to effectively slow down the queries. | |||
* params | |||
** The additional delay between PID queries, in ms | |||
* returns | |||
** none | |||
==Logger Control Functions== | ==Logger Control Functions== | ||
Line 285: | Line 487: | ||
The onTick() function is the main loop where scripting activity takes place. By default it is called by RaceCapture/Pro every 1 second (1Hz). The rate can be adjusted using the setTickRate() function. | The onTick() function is the main loop where scripting activity takes place. By default it is called by RaceCapture/Pro every 1 second (1Hz). The rate can be adjusted using the setTickRate() function. | ||
* '''Note''' - you should only define one onTick() function in your code. If multiple onTick() functions are defined, only the last defined onTick() function will be used. | |||
Example: | Example: | ||
Line 295: | Line 499: | ||
Sets the rate at which the onTick() function is called | Sets the rate at which the onTick() function is called | ||
* params | * params | ||
** rate: The rate the onTick() function is called, in Hz. Max tick rate is | ** rate: The rate the onTick() function is called, in Hz. Max tick rate is 1000Hz. | ||
* returns | * returns | ||
** (none) | ** (none) | ||
==SD Logging control== | |||
The following functions control logging operations to the internal SD card. | |||
* '''Note:''' Only SD card logging is controlled; External devices or apps connected to the telemetry stream are not affected by these commands. | |||
===isLogging()=== | |||
Indicates if an SD card logging session is in progress | |||
* params | |||
** (none) | |||
* returns | |||
** 0 if not logging, non zero otherwise. | |||
===startLogging()=== | ===startLogging()=== | ||
Begins a logging session | Begins a logging session to the SD card. If currently logging, this function has no effect. | ||
* '''Note:''' If an error occurs during writing, the error indicator on the front panel, if provided, will illuminate. | |||
* params | * params | ||
** (none) | ** (none) | ||
Line 307: | Line 523: | ||
===stopLogging()=== | ===stopLogging()=== | ||
Stops the current logging session. If not logging, this function has no effect. | Stops the current SD card logging session. If not logging, this function has no effect. | ||
* params | * params | ||
** (none) | ** (none) | ||
Line 317: | Line 533: | ||
* params | * params | ||
** led (1-3) | ** led (1-3) | ||
** state : 1 = on, 0 = off | ** state: (int / ''[as of 2.10.0]'' bool) 1 / true = on, 0 / false = off | ||
* returns | * returns | ||
** (none) | ** (none) | ||
===setBgStream( on/off )=== | |||
Sets the state of background streaming | |||
* params | |||
** Boolean: true for on, false for off. | |||
* returns | |||
** (none) | |||
===getBgStream()=== | |||
Gets the state of background streaming | |||
* params | |||
** (none) | |||
* returns | |||
** Boolean: True for on, false for off. | |||
==Serial Port Communications== | ==Serial Port Communications== | ||
Line 326: | Line 556: | ||
===Port mappings=== | ===Port mappings=== | ||
0 = USB port<br/> | * 0 = USB port<br/> | ||
1 = GPS port<br/> | * 1 = GPS port<br/> | ||
2 = Internal telemetry port (MK2 only)<br/> | * 2 = Internal telemetry port (MK2/3/Apex only)<br/> | ||
3 = | * 3 = Bluetooth port<br/> | ||
4 = Auxiliary port<br/> | * 4 = Auxiliary / WiFi port<br/> (RaceCapture/Pro MK2) | ||
* 5 = WiFi port | |||
* 6 = External Auxiliary port (RaceCapture/Pro MK3 and RaceCapture/Apex only) | |||
* '''Note''': We only recommend using ports | * '''Note''': We only recommend using the designated auxiliary port for your hardware model The other ports have been included for reference; using them may interfere with normal operations of the unit. | ||
===initSer( port, baud, bits, parity, stopBits)=== | ===initSer( port, baud, bits, parity, stopBits)=== | ||
Line 345: | Line 577: | ||
* returns | * returns | ||
** | ** true if initialization succeeds | ||
===readCSer( port, [timeout])=== | |||
''Available since firmware 2.8.4''<br> | |||
Read a character from the specified serial port | Read a character from the specified serial port | ||
Line 359: | Line 590: | ||
** the character read, or nil if the timeout was reached | ** the character read, or nil if the timeout was reached | ||
===readSer( port )=== | ===readSer( port, [timeout])=== | ||
Read a line of data from the specified serial port. This command blocks until a newline ('\n') character is received on the port, or a timeout occurs. | Read a line of data from the specified serial port. This command blocks until a newline ('\n') character is received on the port, or a timeout occurs. | ||
* params | * params | ||
Line 367: | Line 598: | ||
===writeCSer( port, data )=== | ===writeCSer( port, data )=== | ||
'' | ''Available since firmware 2.8.4''<br> | ||
Writes the specified character to the serial port. The call will block until the character is written. | Writes the specified character to the serial port. The call will block until the character is written. | ||
* params: | * params: | ||
Line 420: | Line 650: | ||
===addChannel( name, sampleRate, [precision], [min], [max], [units] )=== | ===addChannel( name, sampleRate, [precision], [min], [max], [units] )=== | ||
''available in firmware 2.0'' | ''available in firmware 2.0'' | ||
Adds a virtual channel. This virtual channel remains in memory during runtime; it is not persisted in the configuration. Up to | Adds a virtual channel. This virtual channel remains in memory during runtime; it is not persisted in the configuration. Up to 100 virtual channels can be created. | ||
* params | * params | ||
** name: The name of the channel, up to 10 characters long. We recommend using an existing System channel name as defined by the app when possible. | ** name: The name of the channel, up to 10 characters long. We recommend using an existing System channel name as defined by the app when possible. | ||
Line 431: | Line 661: | ||
* returns | * returns | ||
** the id of the new virtual channel, or NIL if the virtual channel could not be created. Use this id for setting the channel value (see setChannel() ) | ** the id of the new virtual channel, or NIL if the virtual channel could not be created. Use this id for setting the channel value (see setChannel() ) | ||
===getChannel( Channel ID or name )=== | |||
* First available in v2.9.0 ; retrieving by channel name available in v2.13.0 | |||
* Parameters | |||
** Channel ID or name : if a number, matches on the channel ID as provided by the '''addChannel''' function. If string, matches on any current channel in the system. | |||
* Returns | |||
** (number) The current value of the channel if available, or '''nil''' if the value is not available. You should always check if the value is present before using it for other purposes, especially if the script's tick rate is high relative to the channel's sample rate. | |||
* Examples: | |||
--returns the virtual channel assigned to ID 1. Current value of channel is stored in val | |||
val = getChannel(1) | |||
--get the channel by name | |||
rpm = getChannel("RPM") | |||
if rpm ~= nil then | |||
println("rpm channel: " ..rpm) | |||
end | |||
===setChannel( channelId, value )=== | ===setChannel( channelId, value )=== | ||
Line 461: | Line 709: | ||
===getDateTime()=== | ===getDateTime()=== | ||
''Available since firmware 2.8.4''<br> | ''Available since firmware 2.8.4''<br> | ||
Returns date and time info to the best of the systems ability. Only available after GPS lock has been established. Will return epoch time (Jan 1, 1970 00:00:000) if time is not available. | Returns date and time info to the best of the systems ability, in UTC. Only available after GPS lock has been established. Will return epoch time (Jan 1, 1970 00:00:000) if time is not available. | ||
* Returns: A list of date and time information in the following order: | * Returns: A list of date and time information in the following order: | ||
Line 468: | Line 716: | ||
** Day | ** Day | ||
** Hour | ** Hour | ||
** Minute | |||
** Second | ** Second | ||
** Millisecond | ** Millisecond | ||
==Dashboard Control== | |||
===txButton()=== | |||
Simulates button press events for dashboard navigation and control. RaceCapture dashboard must be connected for function to have effect. | |||
* params | |||
** button_id: ID of button to transmit. 0 = left button;1 = right button;2 = ack/yes;3 = no | |||
** state: State of button: 1 = pressed; 0 = not pressed | |||
* returns | |||
** (nothing) | |||
==ShiftX2/3 control== | |||
The following functions provide access to the [[ShiftX2]] or [[ShiftX3]] RGB sequential shift light. ''Available in firmware 2.15.0'' | |||
===sxSetConfig()=== | |||
Configures the connected ShiftX device. This must be called prior to any other configuration function calls. All parameters are optional; call with no parameters to use the default settings: | |||
<pre> | |||
sxSetConfig() | |||
</pre> | |||
* params | |||
** orientation: 0 (normal, 7-segment display below bar graph); 1 (inverted, 7-segment display above bar graph). Defaut value: 0 | |||
** brightness: 0 (automatic brightness control with ambient light sensor; 1-100: brightness percentage. Default value: 0 | |||
** CAN bus: 0 (connected to CAN1); 1 (connected to CAN2). Default value: 1 | |||
** CAN base address: base CAN address to use. Default value: 931328) | |||
** Auto brightness scaling: Amplification value to tune ambient light sensor. 0-255 value; Default value: 51 | |||
** Enable / Disable button events: true (Enable button event broadcast to app); false (Disable button event broadcast to app) | |||
* returns | |||
** true if configuration message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it) | |||
===sxCfgLinearGraph()=== | |||
Configures the the style and overall range for the linear graph. | |||
* params | |||
** Rendering Style: 0 (left->right); 1 (center); 2 (right->left) | |||
** Linear Style: 0 (Smooth / interpolated); 1 (stepped) | |||
** Low Range Threshold: The overall low range for the linear graph | |||
** High Range Threshold: The overall high range for the linear graph (ignored if linear style = stepped) | |||
* returns | |||
** true if configuration message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it) | |||
===sxSetLinearThresh()=== | |||
Configure a threshold for the linear graph. Each threshold is identified by an ID, and thresholds are processed from low to high IDs. 5 thresholds can be defined. | |||
* params | |||
** Threshold Id: Id for threshold to set. (0-4). Lower IDs are evaluated first. | |||
** Segment Length: 0 -> number of LEDs on linear graph. (Ignored if linear style = smooth) | |||
** Threshold Value: Value where this threshold is activated | |||
** Red: Red LED value (0-255) | |||
** Green: Green LED value (0-255) | |||
** Blue: Blue LED value (0-255) | |||
** Flash: 0-10Hz (0 = sold on) | |||
* returns | |||
** true if configuration message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it) | |||
===sxUpdateLinearGraph()=== | |||
Update the linear graph with the current sensor value. ShiftX will apply the previously configured thresholds to set bar graph length, color and flash. | |||
* params | |||
** Value: current value representing the linear graph | |||
* returns | |||
** (none) | |||
===sxSetAlert()=== | |||
Direct set an alert indicator. For ShiftX3, ID0=Alert LED on right side; ID1=Alert LED on left side. | |||
* params | |||
** Alert ID: ID of alert (0 -> # of alert indicators) | |||
** Red: Red LED value (0-255) | |||
** Green: Green LED value (0-255) | |||
** Blue: Blue LED value (0-255) | |||
** Flash: 0-10Hz (0 = sold on) | |||
* returns | |||
** true if update message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it) | |||
===sxSetAlertThresh()=== | |||
Configures an alert threshold. Up to 5 thresholds can be configured per alert indicator. Thresholds are evaluated by ID, from low to high. | |||
* params | |||
** Alert ID: Id of Alert (0 -> # of alert indicators) | |||
** Threshold ID: Id for threshold to set. (0-4). Lower IDs are evaluated first. | |||
** Threshold Value: Value where this threshold is activated | |||
** Red: Red LED value (0-255) | |||
** Green: Green LED value (0-255) | |||
** Blue: Blue LED value (0-255) | |||
** Flash: 0-10Hz (0 = sold on) | |||
* returns | |||
** true if configuration message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it) | |||
===sxUpdateAlert()=== | |||
Updates the current value for the specified Alert. ShiftX will apply the previously configured thresholds to set color and flash. | |||
* params | |||
** Alert ID: Id of Alert (0 -> # of alert indicators) | |||
** Value: current value representing the alert | |||
* returns | |||
** true if update message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it) | |||
===sxSetDisplay()=== | |||
Directly sets the value of the 7 segment display. | |||
* params | |||
** Digit index (must be 0) | |||
** Charater: 0-9. Can set ASCII value by offsetting the value by 48 (e.g. ASCII - 48) | |||
* returns | |||
** true if update message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it) | |||
===sxSetLed()=== | |||
Directly set any available LED on ShiftX | |||
* params | |||
** LED Index: 0 -> # of LEDs on device | |||
** Number of LEDs to set: 0 -> # of LEDs on device (0 = set all remaining) | |||
** Red: Red LED value (0-255) | |||
** Green: Green LED value (0-255) | |||
** Blue: Blue LED value (0-255) | |||
** Flash: 0-10Hz (0 = sold on) | |||
* returns | |||
** true if update message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it) | |||
===sxRxButton()=== | |||
* params | |||
** (none) | |||
* returns | |||
** nil if no button presses are available; otherwise: | |||
** button_id (ID of button. left button = 0, right button = 1, yes = 2, ok/no = 3) | |||
** state: (0 = not pressed; 1 = pressed) | |||
<pre> | |||
local id, state = sxRxButton() | |||
if id ~= nil then println('button ' ..id ..' state ' ..state) end | |||
</pre> | |||
==Helper Functions== | |||
===calcGear()=== | |||
A convenience function to calculate the current gear of the vehicle. ''Available in firmware 2.15.0'' | |||
Variation 1: Use built in GPS speed channel and RPM channel named "RPM" | |||
* params | |||
** Tire Diameter: Tire diameter, in cm. | |||
** Final Drive Ratio: The ratio of the final drive | |||
** Gear 1 Ratio: Ratio of 1st gear | |||
** Gear 2 Ratio: Ratio of 2nd gear (optional) | |||
** Gear 3 Ratio: Ratio of 3rd gear (optional) | |||
** Gear 4 Ratio: Ratio of 4th gear (optional) | |||
** Gear 5 Ratio: Ratio of 5th gear (optional) | |||
** Gear 6 Ratio: Ratio of 6th gear (optional) | |||
* returns | |||
** detected gear (1-6) or nil if no gear was detected | |||
<pre> | |||
local gear = calcGear(62.7, 3.45, 4.23, 2.52, 1.66, 1.22, 1.0, 0.8) | |||
if gear ~= nil then println('gear: ' ..gear) end | |||
</pre> | |||
Variation 2: Specify Speed and RPM channel | |||
* params | |||
** Speed Channel name | |||
** RPM Channel name | |||
** Tire Diameter: Tire diameter, in cm. | |||
** Final Drive Ratio: The ratio of the final drive | |||
** Gear 1 Ratio: Ratio of 1st gear | |||
** Gear 2 Ratio: Ratio of 2nd gear (optional) | |||
** Gear 3 Ratio: Ratio of 3rd gear (optional) | |||
** Gear 4 Ratio: Ratio of 4th gear (optional) | |||
** Gear 5 Ratio: Ratio of 5th gear (optional) | |||
** Gear 6 Ratio: Ratio of 6th gear (optional) | |||
* returns | |||
** detected gear (1-6) or nil if no gear was detected | |||
<pre> | |||
local gear = calcGear('Speed', 'RPM', 62.7, 3.45, 4.23, 2.52, 1.66, 1.22, 1.0, 0.8) | |||
if gear ~= nil then println('gear: ' ..gear) end | |||
</pre> |
Latest revision as of 16:15, 30 May 2024
RaceCapture/Pro Scripting Guide
Example Scripts and How-Tos
A large collection of example scripts can be found in our Lua Scripting Examples
The Lua Reference Manual can be found on Lua.org
You can use LuaEdit to help you edit and debug your Lua code.
Lua Script Basics
Conventions
- All inputs and outputs are numbered starting at 0 (getGpio(0), setChannel(0), etc)
- All channel values must be numbers
- All virtual channel names must have no spaces (to be fixed in future revisions)
Writing your script
onTick() function
Your Lua script is centered around the onTick() function. RaceCapture/Pro will periodically call this function, and here you can define your custom tasks and logic.
Example: this script will periodically write a message to the log:
function onTick() println("hello from RaceCapture/Pro") end
- Note: There can only be one onTick() handler; if multiple are defined your script will not work properly.
Viewing the output log
You can observe the loading of new script and monitor and debug the behavior of your script by using the print() / println() functions. In order to see the log output, enable the "Poll Log" checkbox in the scripting window:
Controlling the onTick() rate
You can control how fast your script is executed using the setTickRate() function. The tick Rate is specified in Hz, and the default rate is 1Hz, maximum of 1000Hz.
- Note: actual tick rates may be slower based on the amount of processing time in your onTick() handler.
count = 0 setTickRate(10) function onTick() count = count + 1 println("Tick: " ..count) end
Reading and controlling inputs and outputs
The Lua scripting enables endless combinations of custom behaviors by reading sensor values, controlling output lines, broadcasting CAN messages and writing data to the Auxiliary serial port.
Example: Reading a sensor value and activating an output based on a threshold.
Given:
- A calibrated temperature sensor is connected to the first analog input (0);
- The first GPIO is configured for output mode
This script will activate the output upon crossing the temperature threshold of 212.
function onTick() temperature = getAnalog(0) if temperature > 212 then setGpio(0, 1) else setGpio(0, 0) end end
Combining multiple functions
When combining multiple functions into one script, it's recommended to break them into multiple functions and reference them from the main onTick() function.
Example:
function checkTemps() [ temperature checking logic goes here ] end function checkAutoLogging() [ automatic logging logic goes here ] end function onTick() checkTemps() checkAutoLogging() end
Troubleshooting
Debugging your script
If you're not sure why your script is misbehaving, you can use the println() function to output messages in the log and observe how your script is behaving.
Example:
function onTick() temperature = getAnalog(0) println("current temp: " ..temperature) if temperature > 212 then println("over temp!") setGpio(0, 1) else println("under temp") setGpio(0, 0) end end
Out of memory issues
If you are seeing out of memory issues, try the following:
Mark variables in your script as local
Lua makes variables global by default, which is typically opposite of other programming languages. Since global variables consume more memory, try making variables declared in your function local:
function addSomeNumbers() local var1 = 3 local var2 = 5 return var1 + var2 end
Reduce extra comments, large string variable declaration and other bloat
- Remove comments, shorten the size of any text strings you define - these all consume memory.
Simplify your script
- Reduce the number of variables at the top, and inline their usage in the script. This will help reduce the amount of global memory uses.
- Evaluate the functions you define. Sometimes it makes sense to combine your code into fewer functions, if it turns out you only call that function once. Other times, you may need to break out a function to save space, if you need that function repeatedly.
Call the garbage collector periodically
If your script is very close the limits of memory, regularly calling the garbage collector may help. Calling collectgarbage() in the onTick() is recommended:
function onTick() collectgarbage() -- other code -- end
Try a Lua minimizer
Minimizing/Minifying your script will compact your script, at the expense of making it harder to read. You can try an online minifier to see if that makes a difference.
- Since it makes your script harder to maintain, we recommend this as a last resort.
Lua Reference
RaceCapture/Pro uses the standard, lightweight Lua scripting language used as an extension / customization language for many software applications and especially gaming.
- See lua.org for additional information on how to use the Lua language
More examples
You can see more examples in our Lua Scripting Examples section.
API Reference
General Input / Output (GPIO) Functions
getGpio( channel )
Retrieves the state of the specified GPIO channel
- params
- channel: integer 0 - 2
- returns:
- state: 1 = channel is high, 0 = channel is low
- When the channel is configured for input mode, a voltage high input (> 2 volts) will read as 1; a voltage low will read as 0.
- When the channel is configured as output, the channel reads 1 when the channel is activated (output transistor is connected to ground)
- Note: RaceCapture/Pro MK1 has internal pull-up resistors to 5V.
setGpio ( channel, state )
Sets the state of the GPIO channel when the channel is configured for output mode.
- params
- channel: integer 0 - 2
- state: (int / (since 2.10.0) bool) 1 / true = output active; 0 / false = output inactive
- returns:
- none
When the state specified is 1, the output is active (transistor is connected to ground). When state is 0, transistor is disconnected, and pullup resistor is active.
When configured for input mode this function has no effect.
getButton()
Gets the state of the front panel pushbutton.
- params
- none
- returns
- state: true = pushbutton is depressed; false = pushbutton is not depressed
PWM / Analog Output functions
'PWM / Analog outputs only apply to RaceCapture/Pro MK1 and MK2
setPwmDutyCycle( channel, dutyCyclePct )
Sets the duty cycle of the specified PWM / Analog output channel to the specified duty cycle percentage
- params
- channel: PWM / Analog output channel 0 - 3
- dutyCyclePct: Percentage value of the duty cycle as a counting number 0 - 100
- returns
- none
setPwmClockFreq( frequency )
Sets the clock frequency of the PWM outputs
- params
- frequency: the frequency of the PWM clock, in Hz. Supported range is 320-40000 Hz
- returns
- none
setAnalogOut( channel, voltage )
Sets the output voltage of the specified PWM / Analog output channel to the specified period. A convenience function equivalent to setPwmDutyCycle that translates voltage to PWM percentage.
- params
- channel: PWM / Analog output channel 0 - 3
- voltage: the specified output voltage ( 0 - 5v)
- returns
- none
Timer / RPM Sensor Functions
getTimerRpm(channel)
Returns the current RPM of the specified timer input channel. Note, the timer channel configuration must be set to RPM mode.
- params
- channel: Timer channel. Zero based, so first channel is 0, 2nd channel is 1, and so on.
- returns: RPM value
getTimerPeriodMs(channel)
Returns the current duration of the full cycle pulse of the specified timer input channel, in milliseconds. Note the timer channel configuration must be set to Duration mode.
- params
- channel: Timer channel 0 - 3. Zero based, so first channel is 0, 2nd channel is 1, and so on.
- returns: millisecond value
getTimerFreq(channel)
Returns the current frequency present on the specified timer input channel, in Hz. Note the timer channel configuration must be set to Frequency Mode.
- params
- channel: Timer channel. Zero based, so first channel is 0, 2nd channel is 1, and so on.
- returns: Frequency in Hz
getTimerRaw(channel)
Returns the current raw timer value as measured on the specified timer input channel.
- params
- channel: Timer channel 0 - 3. Zero based, so first channel is 0, 2nd channel is 1, and so on.
- returns: Raw timer value between 0 - 65535
Analog Sensor Functions
getAnalog(channel)
Reads the scaled analog value for the specified analog input channel.
- params
- channel: Analog input channel. Zero based, so first channel is 0, 2nd channel is 1, and so on.
- Note: the last Analog input is connected to battery voltage:
- Channel 7 on RaceCapture/Pro MK1 and MK2
- Channel 8 on RaceCapture/Pro MK3 and RaceCapture Apex
- Channel 0 on RaceCapture/Track MK1 / MK2
- Note: the last Analog input is connected to battery voltage:
- returns: Scaled / calculated value for the specified analog channel as defined in the channel scaling configuration
- channel: Analog input channel. Zero based, so first channel is 0, 2nd channel is 1, and so on.
Accelerometer / Yaw Sensor Functions
getImu(channel)
Reads the specified IMU channel
- params
- channel (0 = X, 1 = Y, 2=Z, 3= Yaw, 4= Pitch, 5 = Roll)
- returns
- The value scaled to G force, or degrees/sec depending on the channel selected
getImuRaw(channel)
Reads the raw value of the specified accelerometer or yaw channel
- params
- channel (0 = X, 1 = Y, 2=Z, 3= Yaw, 4= Pitch, 5 = Roll)
- returns
- The raw accelerometer value
GPS Sensor Functions
getGpsPos()
Reads the current position as measured by the attached GPS module coming in firmware 2.0
- params
- none
- returns
- Latitude: latitude in decimal degrees
- Longitude: longitude in decimal degress
getGpsSpeed()
Provides the current speed as measured by the attached GPS module
- params
- (none)
- returns
- The current speed in MPH
getGpsQuality()
Provides the current GPS quality indicator as indicated by the attached GPS module
- params
- (none)
- returns
- The current GPS quality indicator
- 0: No fix; 1: Fixed; 2: SPS Fix; 3: Differential Fix
getGpsSats()
- params
- (none)
- returns
- The number of GPS satellites currently used in the fix
getGpsTime()
Provides the current GPS time as indicated by the attached GPS module (in NMEA format) todo: document this
- params
- (none)
- returns
- The current GPS time value
getGpsDist()
Provides the current GPS calculated distance from the beginning of the logging session, or from the start finish line, if configured.
- params
- (none)
- returns
- The distance, in Miles
getGpsAltitude()
Provides the current GPS calculated altitude from sea level in feet. The method will return 0 if there is no GPS lock.
- Added: v2.9.0
- Parameters: None
- Returns: <altitude>
getGpsSec()
Provides the number of seconds since midnight, as measured by the GPS module. todo: how does this relate to timezone? GMT or local?
- params
- (none)
- returns
- number of seconds since midnight, as measured by the attached GPS module
Lap Statistics
getLapCount()
Provides the current Lap Count as determined by the start/finish line configuration and measured by the attached GPS module.
- params
- (none)
- returns
- The number of laps detected since the logging session started
getLapTime()
Provides the last lap time as determined by the start/finish line configuration and measured by the attached GPS module.
- params
- (none)
- returns
- The last measured lap time in decimal minutes / seconds
getPredTime()
as of 2.12.0 firmware
Provides the current Predicted Lap time time as determined by the start/finish line configuration and measured by the attached GPS module. A training lap is required before the predicted time is valid.
- params
- (none)
- returns
- The current predicted time in decimal minutes / seconds
getAtStartFinish()
Indicates if within the start finish line target as determined by the start/finish line configuration and measured by the attached GPS module.
- params
- (none)
- returns
- true if currently within the start/finish line target, false if outside
resetLapStats()
since 2.16.0
Resets Lap Statistics, including lap count, lap time, predictive time, and session time.
- params
- (none)
- returns
- (none)
Time Functions
getTickCount()
Returns the number of milliseconds since power-up.
- params
None
- returns
- The number of milliseconds since power-up
CAN Bus functions
initCAN(channel, baud )
available in firmware 2.0 Initializes the CAN bus module. Normally this is done when RaceCapture/Pro powers on; use this function if you need to change the CAN baud rate on the fly.
- params
- channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware
- baud rate: Supported baud rates: 100000, 125000, 250000, 500000, 1000000
- termination: 1 to enable termination, 0 to disable. Defaults to 1 (enabled) Only available on RaceCapture/Pro MK3 and RaceCapture/Apex. On other platforms this setting has no effect.
- returns
- 1 if successful, 0 if initialization fails, nil if parameters are incorrect
txCAN(channel, id, isExtended, data, [timeout] )
available in firmware 2.0 Transmit a CAN message.
- params
- channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware
- identifier: The Identifier value of the message, either in standard (11 bit) or extended (29 bit) format.
- isExtended: 0 for Standard (11 bit) Identifier or 1 for Extended (29 bit) Identifier.
- data: CAN message payload; array up to 8 elements long.
- timeout: (optional) specify a timeout for sending this message. if the transmit queue is full, will block for the specified milliseconds. Defaults to 100ms
- returns
- 1 if successful, 0 if failed, nil if parameters are incorrect
Example:
channel = 0 id = 1234 ext = 0 data = {11,22,33} res = txCAN(channel, id, ext, data)
rxCAN(channel, [timeout] )
available in firmware 2.0 Receive a CAN message, if available.
- params
- channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware
- timeout (optional). read timeout in milliseconds. defaults to 100ms. For non-blocking functionality specify a timeout of 0.
- returns
- identifier: The Identifier value of the message, either in standard (11 bit) or extended (29 bit) format.
- isExtended: 0 for Standard (11 bit) Identifier or 1 for Extended (29 bit) Identifier.
- Data: CAN message payload; array up to 8 elements long.
If no CAN message was received, the function returns nil
Example:
id, ext, data = rxCAN(0, 100) --100ms timeout if id ~= nil then println("CAN rx: " ..id .." " ..data[1]) --print ID and first element of received message end
setCANfilter(channel, filterId, extended, filter, mask )
available in firmware 2.0 Sets the specified CAN filter and mask ID, to ignore CAN messages that match a particular ID pattern.
- params
- channel: The CAN channel. 0 for the first channel, 1 for the 2nd, if supported on the hardware
- filterId: The id of the filter. Up to 6 filters are supported on MK1, 15 per channel on MK2. Filter ids start at 0.
- extended: 0 for Standard (11 bit) Identifier or 1 for Extended (29 bit) Identifier.
- filter: Pattern value for CAN filter
- mask: the mask for the CAN filter
- returns
- 1 for success, 0 for fail, nil if parameters are incorrect
OBDII functions
readOBD2( PID )
available in firmware 2.0 Reads an OBD2 PID and returns the calculated value. This is a convenience method wrapped around the built-in CAN functions.
- params
- The OBD2 PID to read. Supported PIDs (TBD documented)
- returns
- The calculated PID value, or nil if the OBD2 PID was invalid or could not be read (e.g. CAN receive message timeout)
setOBD2Delay( delayMs )
Sets an additional delay in-between OBDII PID queries. Normally the system will query PIDs as fast as possible, in a round robin fashion.
If the vehicle's ECU exhibits problems with the rate of querying, an additional delay can be added between queries to effectively slow down the queries.
- params
- The additional delay between PID queries, in ms
- returns
- none
Logger Control Functions
onTick()
- params:
- (none)
- returns:
- (none)
The onTick() function is the main loop where scripting activity takes place. By default it is called by RaceCapture/Pro every 1 second (1Hz). The rate can be adjusted using the setTickRate() function.
- Note - you should only define one onTick() function in your code. If multiple onTick() functions are defined, only the last defined onTick() function will be used.
Example:
function onTick() println("Hello") --write something to the log end
setTickRate(rate)
Sets the rate at which the onTick() function is called
- params
- rate: The rate the onTick() function is called, in Hz. Max tick rate is 1000Hz.
- returns
- (none)
SD Logging control
The following functions control logging operations to the internal SD card.
- Note: Only SD card logging is controlled; External devices or apps connected to the telemetry stream are not affected by these commands.
isLogging()
Indicates if an SD card logging session is in progress
- params
- (none)
- returns
- 0 if not logging, non zero otherwise.
startLogging()
Begins a logging session to the SD card. If currently logging, this function has no effect.
- Note: If an error occurs during writing, the error indicator on the front panel, if provided, will illuminate.
- params
- (none)
- returns
- (none)
stopLogging()
Stops the current SD card logging session. If not logging, this function has no effect.
- params
- (none)
- returns
- (none)
setLed( led, state )
Sets the state of a front panel LED
- params
- led (1-3)
- state: (int / [as of 2.10.0] bool) 1 / true = on, 0 / false = off
- returns
- (none)
setBgStream( on/off )
Sets the state of background streaming
- params
- Boolean: true for on, false for off.
- returns
- (none)
getBgStream()
Gets the state of background streaming
- params
- (none)
- returns
- Boolean: True for on, false for off.
Serial Port Communications
These function calls allow reading / writing line oriented data from the built in serial ports.
Port mappings
- 0 = USB port
- 1 = GPS port
- 2 = Internal telemetry port (MK2/3/Apex only)
- 3 = Bluetooth port
- 4 = Auxiliary / WiFi port
(RaceCapture/Pro MK2) - 5 = WiFi port
- 6 = External Auxiliary port (RaceCapture/Pro MK3 and RaceCapture/Apex only)
- Note: We only recommend using the designated auxiliary port for your hardware model The other ports have been included for reference; using them may interfere with normal operations of the unit.
initSer( port, baud, bits, parity, stopBits)
Initializes the specified serial port
- params
- port: The port to initialize. (defaults to Auxiliary port)
- baud: The baud rate to set (defaults to 115200)
- bits: Number of bit in the message (8 or 7) (defaults to 8)
- parity: (1 = Even Parity, 2 = Odd Parity, 0 = No Parity) (defaults to No Parity)
- stopBits: number of stop bits (1 or 2) (defaults to 1)
- returns
- true if initialization succeeds
readCSer( port, [timeout])
Available since firmware 2.8.4
Read a character from the specified serial port
- params
- port: The port to read. (required)
- timeout - the read timeout, in ms.
- returns
- the character read, or nil if the timeout was reached
readSer( port, [timeout])
Read a line of data from the specified serial port. This command blocks until a newline ('\n') character is received on the port, or a timeout occurs.
- params
- port: Serial port 0 - 4
- timeout - the read timeout, in ms.
- returns: a line of serial data, or nil if the timeout was reached
writeCSer( port, data )
Available since firmware 2.8.4
Writes the specified character to the serial port. The call will block until the character is written.
- params:
- port - the serial port to write
- char - the character to write.
- returns:
(no return values)
writeSer( port, data )
Writes a line of data to the specified serial port, appending a newline at the end. The call will block until all characters are written.
- params
- port: Serial port 0 - 4
- data: the data in string format
- returns:
(no return values)
Logger Configuration Functions
flashLoggerCfg()
Writes the current configuration in RAM to flash memory.
- params
- (none)
- returns
- (none)
setPwmClockFreq( freq )
Sets the clock frequency for all PWM channels
- params
- freq: The clock frequency todo: what units?
- returns
- (none)
getPwmClockFreq()
Gets the PWM clock frequency controlling all PWM channels
- params
- (none)
- returns
- the PWM clock frequency todo: what units?
calibrateImuZero()
Automatically Calibrates the accelerometer zero position.
- params
- (none)
- returns
- (none)
Virtual Channels
addChannel( name, sampleRate, [precision], [min], [max], [units] )
available in firmware 2.0 Adds a virtual channel. This virtual channel remains in memory during runtime; it is not persisted in the configuration. Up to 100 virtual channels can be created.
- params
- name: The name of the channel, up to 10 characters long. We recommend using an existing System channel name as defined by the app when possible.
- sampleRate: A supported sample rate (1,10,25,50,100,200Hz)
- precision: (optional) the numerical precision (number of decimal places) used when logging to SD and telemetry. Defaults to 2
- min: (optional) The min expected value for this channel. Defaults to 0
- max: (optional) The max expected value for this channel. Defaults to 1000
- units: (optional) The units label for this channel. Defaults to empty string / none
- returns
- the id of the new virtual channel, or NIL if the virtual channel could not be created. Use this id for setting the channel value (see setChannel() )
getChannel( Channel ID or name )
- First available in v2.9.0 ; retrieving by channel name available in v2.13.0
- Parameters
- Channel ID or name : if a number, matches on the channel ID as provided by the addChannel function. If string, matches on any current channel in the system.
- Returns
- (number) The current value of the channel if available, or nil if the value is not available. You should always check if the value is present before using it for other purposes, especially if the script's tick rate is high relative to the channel's sample rate.
- Examples:
--returns the virtual channel assigned to ID 1. Current value of channel is stored in val val = getChannel(1)
--get the channel by name rpm = getChannel("RPM") if rpm ~= nil then println("rpm channel: " ..rpm) end
setChannel( channelId, value )
available in firmware 2.0 Updates the value of a previously created virtual channel.
- params
- channelId: the ID of the channel provided by addChannel()
- value: the new value to set for the virtual channel
Example:
id = addChannel("EGT", 1) function onTick() temp = getAnalog(0) --read analog channel 0 temp = temp * 1000 setChannel(id, temp) --sets the virtual channel value end
Time Info
These methods get you information about dates and time. This is useful in controlling script behavior or just knowing what time it is.
getUptime()
Available since firmware 2.8.4
Returns the number of miliseconds since the device last started. This is always available and is the most consistent way to time things in LUA script on RaceCapture.
- Returns
- Number of milliseconds since CPU boot.
getDateTime()
Available since firmware 2.8.4
Returns date and time info to the best of the systems ability, in UTC. Only available after GPS lock has been established. Will return epoch time (Jan 1, 1970 00:00:000) if time is not available.
- Returns: A list of date and time information in the following order:
- Year
- Month
- Day
- Hour
- Minute
- Second
- Millisecond
Dashboard Control
txButton()
Simulates button press events for dashboard navigation and control. RaceCapture dashboard must be connected for function to have effect.
- params
- button_id: ID of button to transmit. 0 = left button;1 = right button;2 = ack/yes;3 = no
- state: State of button: 1 = pressed; 0 = not pressed
- returns
- (nothing)
ShiftX2/3 control
The following functions provide access to the ShiftX2 or ShiftX3 RGB sequential shift light. Available in firmware 2.15.0
sxSetConfig()
Configures the connected ShiftX device. This must be called prior to any other configuration function calls. All parameters are optional; call with no parameters to use the default settings:
sxSetConfig()
- params
- orientation: 0 (normal, 7-segment display below bar graph); 1 (inverted, 7-segment display above bar graph). Defaut value: 0
- brightness: 0 (automatic brightness control with ambient light sensor; 1-100: brightness percentage. Default value: 0
- CAN bus: 0 (connected to CAN1); 1 (connected to CAN2). Default value: 1
- CAN base address: base CAN address to use. Default value: 931328)
- Auto brightness scaling: Amplification value to tune ambient light sensor. 0-255 value; Default value: 51
- Enable / Disable button events: true (Enable button event broadcast to app); false (Disable button event broadcast to app)
- returns
- true if configuration message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it)
sxCfgLinearGraph()
Configures the the style and overall range for the linear graph.
- params
- Rendering Style: 0 (left->right); 1 (center); 2 (right->left)
- Linear Style: 0 (Smooth / interpolated); 1 (stepped)
- Low Range Threshold: The overall low range for the linear graph
- High Range Threshold: The overall high range for the linear graph (ignored if linear style = stepped)
- returns
- true if configuration message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it)
sxSetLinearThresh()
Configure a threshold for the linear graph. Each threshold is identified by an ID, and thresholds are processed from low to high IDs. 5 thresholds can be defined.
- params
- Threshold Id: Id for threshold to set. (0-4). Lower IDs are evaluated first.
- Segment Length: 0 -> number of LEDs on linear graph. (Ignored if linear style = smooth)
- Threshold Value: Value where this threshold is activated
- Red: Red LED value (0-255)
- Green: Green LED value (0-255)
- Blue: Blue LED value (0-255)
- Flash: 0-10Hz (0 = sold on)
- returns
- true if configuration message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it)
sxUpdateLinearGraph()
Update the linear graph with the current sensor value. ShiftX will apply the previously configured thresholds to set bar graph length, color and flash.
- params
- Value: current value representing the linear graph
- returns
- (none)
sxSetAlert()
Direct set an alert indicator. For ShiftX3, ID0=Alert LED on right side; ID1=Alert LED on left side.
- params
- Alert ID: ID of alert (0 -> # of alert indicators)
- Red: Red LED value (0-255)
- Green: Green LED value (0-255)
- Blue: Blue LED value (0-255)
- Flash: 0-10Hz (0 = sold on)
- returns
- true if update message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it)
sxSetAlertThresh()
Configures an alert threshold. Up to 5 thresholds can be configured per alert indicator. Thresholds are evaluated by ID, from low to high.
- params
- Alert ID: Id of Alert (0 -> # of alert indicators)
- Threshold ID: Id for threshold to set. (0-4). Lower IDs are evaluated first.
- Threshold Value: Value where this threshold is activated
- Red: Red LED value (0-255)
- Green: Green LED value (0-255)
- Blue: Blue LED value (0-255)
- Flash: 0-10Hz (0 = sold on)
- returns
- true if configuration message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it)
sxUpdateAlert()
Updates the current value for the specified Alert. ShiftX will apply the previously configured thresholds to set color and flash.
- params
- Alert ID: Id of Alert (0 -> # of alert indicators)
- Value: current value representing the alert
- returns
- true if update message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it)
sxSetDisplay()
Directly sets the value of the 7 segment display.
- params
- Digit index (must be 0)
- Charater: 0-9. Can set ASCII value by offsetting the value by 48 (e.g. ASCII - 48)
- returns
- true if update message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it)
sxSetLed()
Directly set any available LED on ShiftX
- params
- LED Index: 0 -> # of LEDs on device
- Number of LEDs to set: 0 -> # of LEDs on device (0 = set all remaining)
- Red: Red LED value (0-255)
- Green: Green LED value (0-255)
- Blue: Blue LED value (0-255)
- Flash: 0-10Hz (0 = sold on)
- returns
- true if update message was successfully broadcast to ShiftX (does not indicate if ShiftX has received it)
sxRxButton()
- params
- (none)
- returns
- nil if no button presses are available; otherwise:
- button_id (ID of button. left button = 0, right button = 1, yes = 2, ok/no = 3)
- state: (0 = not pressed; 1 = pressed)
local id, state = sxRxButton() if id ~= nil then println('button ' ..id ..' state ' ..state) end
Helper Functions
calcGear()
A convenience function to calculate the current gear of the vehicle. Available in firmware 2.15.0
Variation 1: Use built in GPS speed channel and RPM channel named "RPM"
- params
- Tire Diameter: Tire diameter, in cm.
- Final Drive Ratio: The ratio of the final drive
- Gear 1 Ratio: Ratio of 1st gear
- Gear 2 Ratio: Ratio of 2nd gear (optional)
- Gear 3 Ratio: Ratio of 3rd gear (optional)
- Gear 4 Ratio: Ratio of 4th gear (optional)
- Gear 5 Ratio: Ratio of 5th gear (optional)
- Gear 6 Ratio: Ratio of 6th gear (optional)
- returns
- detected gear (1-6) or nil if no gear was detected
local gear = calcGear(62.7, 3.45, 4.23, 2.52, 1.66, 1.22, 1.0, 0.8) if gear ~= nil then println('gear: ' ..gear) end
Variation 2: Specify Speed and RPM channel
- params
- Speed Channel name
- RPM Channel name
- Tire Diameter: Tire diameter, in cm.
- Final Drive Ratio: The ratio of the final drive
- Gear 1 Ratio: Ratio of 1st gear
- Gear 2 Ratio: Ratio of 2nd gear (optional)
- Gear 3 Ratio: Ratio of 3rd gear (optional)
- Gear 4 Ratio: Ratio of 4th gear (optional)
- Gear 5 Ratio: Ratio of 5th gear (optional)
- Gear 6 Ratio: Ratio of 6th gear (optional)
- returns
- detected gear (1-6) or nil if no gear was detected
local gear = calcGear('Speed', 'RPM', 62.7, 3.45, 4.23, 2.52, 1.66, 1.22, 1.0, 0.8) if gear ~= nil then println('gear: ' ..gear) end