TCM System Functions

This is a reference for every native function callable from a MecScript script running on the TCM including:

  • General-purpose functions under System:: for debugging and time management.
  • TCM-specific functions under Runtime::, Device::, CAN:: and Output:: for reading live device state, talking to the CAN bus and driving script-controlled outputs.

Quick Reference

Strings & Debugging (System::)

FunctionSignaturePurpose
System::Printvoid Print(string str)Debug-print a string, no newline
System::PrintLinevoid PrintLine(string str)Debug-print a string plus newline
System::PrintIntvoid PrintInt(int i)Debug-print an integer
System::PrintFloatvoid PrintFloat(float f)Debug-print a float
System::PrintFormatvoid PrintFormat(string str, float f)Debug-print a format string with one float
System::PrintBuffervoid PrintBuffer(byte buf[], int capacity)Debug-print a byte buffer’s null-terminated content
System::StrLengthint StrLength(byte buf[], int capacity)Length of a buffer’s content up to its null terminator
System::StrCopyvoid StrCopy(byte dest[], int destCapacity, string src)Copy a string constant into a buffer, truncating to fit
System::StrAppendvoid StrAppend(byte dest[], int destCapacity, string src)Append a string constant onto a buffer’s content, truncating to fit
System::IntToStrvoid IntToStr(byte dest[], int destCapacity, int value)Format an integer as decimal text into a buffer
System::StrEqualsbool StrEquals(byte a[], int capacityA, byte b[], int capacityB)Compare two buffers’ null-terminated contents

Time

FunctionSignaturePurpose
System::NowMsuint NowMs()Device uptime in milliseconds (wraps every ~49.7 days)
System::NowUsuint NowUs()Device uptime in microseconds (wraps every ~71.58 min)

Script Yielding

FunctionSignaturePurpose
System::Yieldvoid Yield(uint t)Pause the script for t milliseconds
System::YieldUntiluint YieldUntil(uint lastTime, uint delay)Fixed-period pause that returns the updated lastTime for the next call

Runtime Channels (Runtime::)

FunctionSignaturePurpose
Runtime::Readint Read(uint id)Read a live channel value as an integer with the decimal point removed (123.4 reads as 1234)
Runtime::ReadRealfloat ReadReal(uint id)Read a live channel value as a float in real units
Runtime::Writebool Write(uint id, int value)Write a writeable channel value as an integer with the decimal point removed
Runtime::WriteRealbool WriteReal(uint id, float value)Write a writeable channel value as a float in real units

CAN Bus (CAN::)

FunctionSignaturePurpose
CAN::SetupNodebool SetupNode(uint node, bool enable, uint bitrateSelect, bool termination, bool listenOnly)Enable/disable a CAN node and set its bitrate, termination and listen-only mode
CAN::Sendvoid Send(uint node, uint id, byte buffer[], int length)Send a raw frame on CAN 1 or CAN 2
CAN::Readint Read(uint node, uint id, byte buffer[], int length)Poll the latest received frame for a node/id pair
CAN::Subscribevoid Subscribe(uint node, uint idMatch, uint idMask, func(uint id, byte data[], int length) handler)Register a callback for received frames matching an id/mask
CAN::Unsubscribevoid Unsubscribe(uint node, uint idMatch, uint idMask)Cancel a subscription registered with the same node/match/mask
CAN::Pollint Poll()Fire the handlers for any frames received since the last call

Output Control (Output::)

FunctionSignaturePurpose
Output::SetActiveLevelvoid SetActiveLevel(byte outputId, int level)Set a script output’s active polarity (0 = active-low, 1 = active-high)
Output::SetEffectiveResistancevoid SetEffectiveResistance(byte outputId, float ohms)Tell current control the load’s resistance
Output::SetFreqvoid SetFreq(byte outputId, float frequency)Set a script output’s PWM/current-chop frequency in Hz
Output::SetDutyvoid SetDuty(byte outputId, float dutyCycle)Drive a script output in PWM mode at a fixed duty (0-100)
Output::SetCurrentvoid SetCurrent(byte outputId, float milliAmps)Drive a script output in closed-loop current control

Device Information (Device::)

FunctionSignaturePurpose
Device::ReadSerialNumberuint ReadSerialNumber()Read the device’s serial number
Device::ReadVendorKeyuint ReadVendorKey(int keyId)Read one of two vendor keys (keyId 1 or 2), typically used to lock a script to a specific device

Calling Convention

Every native function is called through its namespace.

float rpm = Runtime::ReadReal(RT_ENGSPD);
CAN::Poll();
System::Yield(10);

Calling a native bare (Yield(10);, Poll();) or through the wrong namespace (System::Runtime::Read(1);) fails to compile. Function names are case-sensitive and must match the names in this manual exactly.

A callback handler passed to CAN::Subscribe (a func-typed parameter) is the one exception: it’s a bare script function name, not called through any namespace - see CAN Receive Callbacks.

Runtime ids (the uint id arguments to the Runtime:: functions) are plain numbers assigned by the device’s .mdef. Rather than hard-coding them, #include "mtc.mec" and use the RT_ names it defines - see Include Files.

Every CAN:: function takes a node as its first argument, numbered from zero: 0 is the bus MectriCal labels CAN 1 and 1 is CAN 2. CAN::Subscribe and CAN::Unsubscribe also accept 2 for both buses; everywhere else 2 is rejected. The include file provides CAN1, CAN2 and CAN_BOTH for these.


Included Device Definition Files

Device header file(s) ship along side the compiler, so a script can refer to channels, buses, bitrates, etc by name instead of by number. Include it at the top of the script:

#include "tm16.mec"

The file name is the device’s name in lower case: mtc.mec for the MTC, tm16.mec for the TM16. The compiler already knows where the shipped headers live, so the plain file name works wherever the script itself is saved. Including the same file more than once (e.g. from two of your own include files) is harmless.

GroupNamesMeaning
ConstantsLOW, HIGH0 and 1, for Output::SetActiveLevel
CAN busesCAN1, CAN2, CAN_BOTHThe node argument of the CAN:: functions (0, 1, 2)
CAN BitratesCAN_BITRATE_125K, CAN_BITRATE_250K, CAN_BITRATE_500K, CAN_BITRATE_1M, CAN_BITRATE_CUSTOMThe bitrateSelect argument of CAN::SetupNode
Runtime ChannelsRT_ENGSPD, RT_GEAR, RT_BATTVOLTS, …The Runtime ID of every channel, for the Runtime:: functions

A runtime channel’s name is RT_ followed by its abbreviation in upper case (the “Engine Speed” channel becomes RT_ENGSPD). Each define carries the channel’s full label as a trailing comment, so the quickest way to find a channel is to open the header and search for the channel name.

You are free to define your own constants too.

#include "tm16.mec"

#define MY_SOLENOID 4

float rpm = Runtime::ReadReal(RT_ENGSPD);
CAN::SetupNode(CAN2, true, CAN_BITRATE_500K, true, false);
Output::SetActiveLevel(MY_SOLENOID, LOW);

The header only provides names - it doesn’t change what any function does. A channel that isn’t writeable still refuses Runtime::Write whether it’s addressed by RT_ name or by number.

Info

#define is used in preference to const uint declarations because unused defines have no effect on the compiled output. If you create 100 variable declarations (const or not), you will add 100 variables to the compiled script binary, that must also take up space on the stack when running.


String/Debug Output

Print, PrintLine, PrintInt, PrintFloat, PrintFormat and PrintBuffer all write to the same destination: a debug message sent to a connected PC over the device’s Ethernet port, rate-limited so a busy loop can’t flood it. None of them do anything unless all of the following are true:

  • MectriCal is connected to the device and has debug output active, AND
  • The specific script has its “Debug” option enabled in its configuration.

[IMPORTANT] Always disable debug when it’s no longer required.

System::Print("state=");
System::PrintInt(state);
System::PrintLine(" (idle)");
System::PrintFormat("battery: %f V\n", batteryVolts);

str in Print/PrintLine/PrintFormat must be a string - a compile-time string constant, not a byte[] buffer. Use PrintBuffer for buffer content instead (see String Buffers).

System::Print

void System::Print(string str)

Prints a string literal with no newline.

System::Print("hello");

System::PrintLine

void System::PrintLine(string str)

Prints a string literal followed by a newline. Use it for the last piece of a line built up from several Print/PrintInt calls. An empty string "" is not accepted as an argument, so end the line with real text, or use PrintFormat with a \n in its format string.

System::PrintLine("hello");

System::PrintInt

void System::PrintInt(int i)

Prints i as a single integer value.

int i = 100;
System::PrintInt(i); // 100

System::PrintFloat

void System::PrintFloat(float f) 

Prints f as a decimal float (%f format).

int f = 123.4;
System::PrintFloat(f); // 123.4

System::PrintFormat

void System::PrintFormat(string str, float f) // 

Prints str as a printf-style format string with f as its one and only argument.so only a single %f-style specifier makes sense. Anything else in the string that consumes an argument is undefined, the same way a mismatched printf format is in C.

System::PrintFormat("The value is %f", 123.4); // The value is 123.4

System::PrintBuffer

void System::PrintBuffer(byte buf[], int capacity)

Prints buf’s contents up to its null terminator, or up to capacity bytes, whichever comes first. See StringBuffers.


String Buffers

string constants are immutable and can’t be built or modified at runtime - for text a script assembles itself (formatting a value, building a label from CAN data, etc.) it needs a byte[] buffer instead, plus the five string natives that operate on it. All five are C snprintf-style: every one takes an explicit capacity and truncates rather than overflowing.

byte msg[32];
System::StrCopy(msg, 32, "state=");

byte num[16];
System::IntToStr(num, 16, 42);

// StrAppend's source is a string constant only - buffer-to-buffer append isn't supported
System::StrAppend(msg, 32, "42");

System::PrintBuffer(msg, 32);   // msg is byte[] - use PrintBuffer, not Print/PrintLine

Two easy mistakes to make:

  • StrCopy/StrAppend’s source (src) is always a string constant, never another byte[] buffer. There’s no buffer-to-buffer append.
  • A byte[] buffer can never be passed where a string parameter is expected. A freshly declared buffer is zero-filled, so StrLength on one that’s never been written returns 0.

System::StrLength

int System::StrLength(byte buf[], int capacity)

Scans up to capacity bytes for a \0 and returns how many bytes precede it: 0 if buf starts with \0, capacity if no terminator is found.

System::StrCopy

void System::StrCopy(byte dest[], int destCapacity, string src)

Copies src into dest, truncating and null-terminating to fit within destCapacity.

System::StrAppend

void System::StrAppend(byte dest[], int destCapacity, string src)

Appends src onto dest’s existing null-terminated content, truncating and null-terminating to fit within destCapacity.

System::IntToStr

void System::IntToStr(byte dest[], int destCapacity, int value)

Formats value as decimal text into dest, truncating and null-terminating to fit within destCapacity.

System::StrEquals

bool System::StrEquals(byte a[], int capacityA, byte b[], int capacityB)

Returns true if a and b’s null-terminated contents are identical, each scanned up to its own capacity.


Timing

uint nowMs = System::NowMs();
uint nowUs = System::NowUs();

NowMs/NowUs read the device’s uptime from the same free-running hardware timer, but with different wrap periods.

Tip

Write comparisons the wraparound-safe way (unsigned subtraction) rather than assuming now only ever increases: (uint)(now - start) >= threshold)

System::NowMs

uint System::NowMs()

Uptime in milliseconds. Wraps every ~49.7 days (2^32 milliseconds), which makes it the safer default for a script tracking longer-running state (e.g. time since ignition-on).

System::NowUs

uint NowUs()

Uptime in microseconds. Wraps every ~71.58 minutes (2^32 microseconds). Because the two clocks wrap at different points, NowMs() and NowUs() / 1000 only agree with each other for the first ~71.58 minutes after boot - once NowUs has wrapped, NowMs keeps counting while NowUs has reset near zero, so don’t rely on them staying numerically related.

System::Yield

void System::Yield(uint t)

Pauses the calling script for t milliseconds, letting other threads (and the rest of the script scheduler) run. This is the standard way to pace a script’s own loop instead of spinning:

while (1) {
    // ... do work ...
    System::Yield(20);   // ~50 Hz loop
}

System::YieldUntil

uint System::YieldUntil(uint lastTime, uint delay)

A fixed-period yield: sleeps until lastTime + delay, then returns the new lastTime (lastTime + delay) for the caller to feed back in on the next iteration. Unlike Yield, which always sleeps for a fixed duration from now, this keeps a loop’s period accurate even if the loop body’s own work takes a variable amount of time each iteration:

uint lastWake = System::NowMs();
for (;;) {
    // ... do work ...
    lastWake = System::YieldUntil(lastWake, 20);   // 20 ms period, not 20 ms + work time
}

The function takes and returns lastTime explicitly rather than updating it in place (MecScript has no reference parameters) - always reassign the return value back onto the variable you pass in, or the period will drift.


Runtime Channels

Runtime channels are the live values used throughout the TCM (engine RPM, gear, clutch pressures, launch targets and so on). Each is identified by its Runtime ID, available by name as RT_... from the device’s include file.

Tip

See the Runtimes reference document for a list of all runtime channels, their #define names, factors, decimals etc.

Channels come in two flavours from a script’s point of view:

  • Read/Write work in the channel’s integer representation: the real value with its decimal point removed, so a channel displayed as 123.4 (one decimal place) reads as 1234, and writing 1234 sets it to 123.4. A channel with no decimal places reads and writes as-is.
  • ReadReal/WriteReal work in floating point units (123.4) and are the simpler choice unless you specifically want integer maths. The TCM is equipped with an FPU so floating point operations are trivial.

Reads of an ID that doesn’t resolve to anything return 0. Writes only succeed (return true) if the target channel is writeable. Lots of channels are computed outputs, not inputs, and will refuse the write.

Important

Channels driven by Input Functions such as Engine Speed must have their input assignment set to Script or they cannot be written to.

#include "tm16.mec"

void main() {
    // Engine Speed has 1DP precision
    int rpmInt = Runtime::Read(RT_ENGSPD) / 10; // 6500.0 rpm reads as 65000
    float rpm  = Runtime::ReadReal(RT_ENGSPD);  // 6500.0

    Runtime::Write(RT_USERCH1, rpmInt + 100);
    Runtime::WriteReal(RT_USERCH2, rpm + 100.0);
}

main();

Runtime::Read

int Runtime::Read(uint id)

Reads the channel as an integer with the decimal point removed. Returns 0 if id is unknown.

int anv1 = Runtime::Read(RT_ANV1); // 3DP: 1.234V = 1234

Runtime::ReadReal

float Runtime::ReadReal(uint id)

Reads the channel as a float in its real units. Returns 0 if id is unknown.

float anv1 = Runtime::ReadReal(RT_ANV1); // 3DP: 1.234V = 1.234

Runtime::Write

bool Runtime::Write(uint id, int value)

Writes value, an integer with the decimal point removed, to the channel. Returns true if the channel accepted the write, false if id is unknown or the channel is not writeable.

// Vehicle speed is 1DP so 1234 = 123.4 km/h
if (!Runtime::Write(RT_VEHICLESPEED, 1234)) {
    System::Print("Vehicle Speed not assigned to Script");
}

Runtime::WriteReal

bool Runtime::WriteReal(uint id, float value)

Writes value, a float in the channel’s real units. Returns true if the channel accepted the write, false if id is unknown or the channel is not writeable.

if (!Runtime::WriteReal(RT_VEHICLESPEED, 123.4)) {
    System::Print("Vehicle Speed not assigned to Script");
}

CAN Bus

Every CAN:: function takes a node as its first argument (0 indexed):

  • 0 = CAN 1,
  • 1 = CAN 2
  • Subscribe/Unsubscribe also accept 2 = both buses.

Node Setup

CAN::SetupNode

bool CAN::SetupNode(uint node, bool enable, uint bitrateSelect, bool termination, bool listenOnly)

Configures and restarts a CAN node from the script, replacing the node’s settings from the calibration. Returns true on success, false if node is not 0 or 1.

  • enable - false turns the node off entirely (no transmit, no receive, termination off). The other arguments are still stored but have no effect until the node is enabled again.
  • bitrateSelect
    • 0 = Custom bit timing
    • 1 = 125 kbit/s
    • 2 = 250 kbit/s
    • 3 = 500 kbit/s
    • 4 = 1 Mbit/s
    • *Any other value leaves the bit timing as it was.
  • termination - switches the node’s on-board 120R termination resistor on or off.
  • listenOnly - true puts the node in silent mode: it receives frames but never transmits or acknowledges, and the node’s configured CAN transmit channels are stopped. Use it to read from a bus the TCM must not disturb.
// CAN 2: enabled, 500 kbit/s, termination on, normal (not listen-only) mode
bool canOk = CAN::SetupNode(CAN2, true, CAN_BITRATE_500K, true, false);

Calling it restarts the node, so any frames in flight on that bus are lost. Call it once at script start, NOT from inside the loop. The new settings are not saved to flash by the call itself, so a script that depends on them should apply them every time it starts.

Raw CAN I/O (polling)

Send/Read are the simple, polling pair. Both target one bus, so node must be 0 or 1. 2 is rejected (Send does nothing, Read returns -1).

#include "mtc.mec"

byte txBuf[8];
byte rxBuf[8];

void doCan() {
    txBuf[0] = 1;
    CAN::Send(CAN1, 0x100, txBuf, 8);

    int n = CAN::Read(CAN2, 0x200, rxBuf, 8);
    if (n > 0) {
        System::PrintInt(rxBuf[0]);
    }
}

doCan();

CAN::Send

void CAN::Send(uint node, uint id, byte buffer[], int length)

Queues a CAN message with identifier id and the first length bytes of buffer (at most 8) for transmission on node. The call returns as soon as the frame is queued; it does nothing if node is not 0 or 1 or length is 0.

byte txBuf[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
CAN::Send(CAN1, 0x100, txBuf, 8);

CAN::Read

int CAN::Read(uint node, uint id, byte buffer[], int length)

Copies the most recently received frame with identifier id on node into buffer, up to length bytes, and returns the number of bytes copied. Returns -1 if no frame with that id has been seen on that bus yet.

byte rxBuf[8];
int read = CAN::Read(CAN2, 0x200, rxBuf, 8);
if (read > 2) {
    int engineSpeed = (rxBuff[1] << 8) | rxBuff[0]; // 0DP
    Runtime::Write(RT_ENGSPD, engineSpeed * 10); // 1DP
}

The device keeps the latest frame for each node/id pair a script has asked about, and each Read call copies out of that store, so reading a frame doesn’t consume it: the same frame is returned again until a newer one arrives. The system holds a fixed number of node/id pairs (16, shared across all running scripts); once it’s full, Read on a pair it isn’t already tracking returns -1. This is fine for a handful of ids a script cares about. If you need every frame on a range of ids, or lower latency, use the callback API below instead.

CAN Receive Callbacks

CAN::Subscribe registers a script function to be called for every received frame whose id matches an id/mask pair, on CAN 1, CAN 2 or both. One subscription can cover many ids (see Id/Mask Matching). Handlers don’t run the instant a frame arrives: matching frames are queued for the script, and CAN::Poll() - called from the script’s own loop - runs each handler in turn on the script’s own thread. This means a callback can never delay real CAN traffic, but also means it only ever fires when the script calls CAN::Poll().

void onEngineData(uint id, byte data[], int length) {
    if (length >= 2) {
        Runtime::Write(RT_TPS, (data[0] << 8) | data[1]);
    }
}

CAN::Subscribe(CAN1, 0x0CF00400, 0x1FFFFF00, onEngineData);

while (true) {
    CAN::Poll();
    System::Yield(10);
}

CAN::Subscribe

void CAN::Subscribe(uint node, uint idMatch, uint idMask, func(uint id, byte data[], int length) handler)

Subscribes a handler to a range of CAN messages:

  • node - 0 = CAN 1, 1 = CAN 2, 2 = both (CAN1, CAN2, CAN_BOTH from the include file).
  • idMatch/idMask - a frame matches when (frame.id & idMask) == (idMatch & idMask). A mask of 0 matches every id on the node.
  • handler - a bare script function name (no parentheses, no namespace), which must be declared with exactly this signature:
void handler(uint id, byte data[], int length) { ... }

id is the received frame’s identifier, data holds its payload and length is how many of those bytes are valid (0-8). A handler with the wrong parameter count or types is rejected at compile time.

data is only valid until the handler returns. Index it, or pass it straight on to another function that takes a byte array (such as CAN::Send), but copy it into a script-declared array if you need the bytes afterwards. Each frame delivered to a handler also uses a little extra script stack on top of the handler’s own locals, so a script running very close to its stack limit can halt with a stack-overflow fault on delivery rather than silently missing the callback.

Calling Subscribe again with the same node/idMatch/idMask replaces the existing subscription’s handler rather than adding a second one.

CAN::Unsubscribe

void CAN::Unsubscribe(uint node, uint idMatch, uint idMask)

Removes a subscription. Pass the exact same three values it was registered with.

CAN::Poll

int CAN::Poll()

Runs the handlers for every matching frame received since the last call, oldest first, and returns how many handlers were fired. A subscribing script must call it once per loop iteration, before yielding, or queued frames simply sit until the next call.

The queue holds a fixed number of frames per script. If a script falls behind a busy bus (e.g. it’s blocked doing other work), the oldest undelivered frames are dropped rather than the queue growing. Keep the loop tight and call Poll() regularly if you’re subscribing to high frequency message(s) or a wide mask. Calling Poll() from inside a handler (directly or indirectly) does nothing and returns 0.

Id/Mask Matching

The match is a bitwise AND against both sides, not a range check:

(frame.id & idMask) == (idMatch & idMask)
  • Bits set in idMask are the ones that must match.
  • Bits clear in idMask are don’t-care and match any value.

A few common patterns:

CAN::Subscribe(CAN1, 0x100, 0xFFFFFFFF, handler1);   // exact id 0x100 only
CAN::Subscribe(CAN1, 0x100, 0x700,      handler2);   // every id from 0x100-0x1FF
CAN::Subscribe(CAN1, 0,     0,          handler3);   // every id on CAN 1 (not recommended)

The frame’s actual ID is always passed to the handler as its first argument, so a single wide-mask subscription can still tell which specific id triggered each call:

void handler2(uint id, byte data[], int length) {
    if (id == 0x101) { ... }
    else if (id == 0x150) { ... }
}

Output Control

Script outputs are a dedicated pool of up to 24 output channels that can be used to drive solenoids etc.
outputId ranges from 1-24, not 0-based. ID 0 or anything above 24 resolves to nothing and does nothing.
Each output has to be assigned to a physical pin in the device’s configuration before a script can usefully drive it. An unassigned output accepts every call here without error but has no effect on hardware.

Info

The script has no way of knowing which physical output the user assigned to a given Script Output.
Eg: Script Output 1, with ID 1, maybe be assigned to drive Solenoid Output 7 (or any other output pin by the end user).

#include "tm16.mec"

#define CENTRE_DIFF_SOLENOID 6

void SetupSolenoids() {
    Output::SetActiveLevel(CENTRE_DIFF_SOLENOID, LOW);        // Active low
    Output::SetFreq(CENTRE_DIFF_SOLENOID, 2000.0);            // 2000 Hz
}

SetupSolenoids();

float TorqueSplitCurrent() { ... }

// Main Script Loop
while(1) {
    float diffMa = TorqueSplitCurrent();
    Output::SetCurrent(CENTRE_DIFF_SOLENOID, diffMa); // Closed-loop current control, mA
    System::Yield(5); // 200 Hz loop
}
Info

SetDuty and SetCurrent set the output’s drive mode. Calling one switches the output into that mode and zeroes the other’s setpoint, so the two are mutually exclusive per output.
Whichever was called most recently wins.
SetFreq applies to both modes.

Output::SetActiveLevel

void Output::SetActiveLevel(byte outputId, int level)

Sets whether the output is driven active-high (1) or active-low (0). LOW and HIGH definitions are in the device include file.

Output::SetActiveLevel(MY_SOLENOID, LOW);

Output::SetEffectiveResistance

void Output::SetEffectiveResistance(byte outputId, float ohms)

Auxiliary Outputs Only
Tells the current control system the resistance of the connected load. Used to help translate the current target into a drive duty. Only relevant in current-control mode when the output is assigned to an auxiliary output rather than a solenoid output.

void Output::SetEffectiveResistance(MY_SOLENOID, 9.5);
Info

If the output’s effective resistance is set to 0 (Recommended and default), the system will work it out on it’s own. The only drawback is that the first application of the solenoid may take a few extra milliseconds to settle on the current target.

Tip

Where possible, preference using the solenoid outputs, not auxiliary outputs to drive current-controlled loads.

Output::SetFreq

void Output::SetFreq(byte outputId, float frequency)

Sets the output’s switching frequency in Hz:

  • PWM rate in PWM (duty) mode.
  • Base frequency in current-control mode.

PWM Range: 0.5 - 20000 Hz
Current Control Range: See below

Output::SetFreq(MY_SOLENOID, 1000.0); // 1000 Hz
Current Control Frequency

When an output is in current control mode, it’s frequency must be one of the following options:

  • 110 Hz
  • 200 Hz
  • 300 Hz
  • 400 Hz
  • 500 Hz
  • 600 Hz
  • 700 Hz
  • 800 Hz
  • 900 Hz
  • 1000 Hz
  • 2000 Hz
  • 3000 Hz
  • 4000 Hz
PWM Mode Frequency

In PWM mode, any frequency up to 20000 Hz (20 KHz) is fine.
Once the duty cycle has been set, putting the output into fixed PWM mode, the frequency can be changed at will, even without updating the duty cycle again. This makes it possible to do variable frequency outputs such as a tacho output.

Output::SetDuty

void Output::SetDuty(byte outputId, float dutyCycle)

Puts the output in fixed-duty PWM mode at dutyCycle percent (0-100) and clears any current target.

Output::SetDuty(MY_SOLENOID, 12.3); // 12.3%

Output::SetCurrent

void Output::SetCurrent(byte outputId, float milliAmps)

Puts the output in closed-loop current-control mode with a target of milliAmps and clears any duty setpoint.

Output::SetCurrent(MY_SOLENOID, 900.0); // 900mA or 0.9A

Output Current Range

  • Solenoid Outputs in single channel mode can command up to 1.5A.
  • Solenoid Outputs in paired channel mode can command up to 2.7A.
  • Auxiliary Outputs can command up to 5A. (high side or low side).
Info

Solenoid Outputs are the preferred output for current controlled loads.


Device Identity

uint serial = Device::ReadSerialNumber();
uint key1   = Device::ReadVendorKey(1);
uint key2   = Device::ReadVendorKey(2);   // any keyId other than 1 or 2 returns 0

A common use is locking a script to a specific device or vendor: compare the serial number and/or a vendor key that only the vendor knows and gives to the user, against an expected value at script start and refuse to run if it doesn’t match.

bool AuthorizeScript(uint serial, uint key) {
    // Some kind of non trivial cypher...
    const uint expected = ((serial & 0xAA55AA55) << 16) + (serial ^ 0xDEADBEEF);
    return key == expected;
}

const uint serial = Device::ReadSerialNumber();
const uint key1   = Device::ReadVendorKey(1);

if (!AuthorizeScript(serial, key1)) {
    // Invalid key
    System::Print("Key Invalid. Script will not run.");
    return; // Returning from the scripts top level will terminate execution.
}

Device::ReadSerialNumber

uint Device::ReadSerialNumber()

Returns the device’s serial number.

Device::ReadVendorKey

uint Device::ReadVendorKey(int keyId)

Returns one of two general-purpose 32-bit calibration values (“Script Vendor Hardware Key 1/2”), set like any other calibration value in MectriCal. keyId is 1 or 2; any other value returns 0.

Info

The Script Vendor Hardware Key # variables are kept at the device level. This means that uploading a cal file with different values in the keys, will not change the values in the device. They will be ignored from the cal file data. This stops the sharing of cal files that run the same scripts from breaking script execution when uploaded.