This is a full-featured library for receiving and transmitting DMX on Teensy 3, Teensy LC, and Teensy 4. It follows the ANSI E1.11 DMX512-A specification.
Some notable features of this library:
readPacket
and get
)
and two forms of one write call (set
for single and multiple channels).Responder
API. Alternate start codes can not only be handled, for example, for Text
Packets or System Information Packets (SIP), but responses can be sent back
to the transmitter, for example for RDM.When the RX line is not being monitored, there are limitations in the handling of received DMX frame timing. For BREAK and Mark after BREAK (MAB) times, only the following cases are checked and not accepted as a valid DMX frame start:
The following case is accepted as a valid frame start, even though it isn't compliant with the DMX specification:
For example, if a BREAK comes in having a duration of 53us and then a MAB comes in having a duration of 43us, their sum is 96us, and so the packet will be accepted. More generally, this will allow BREAKs that are shorter than the minimum required 88us if the MAB is shorter than 44us.
This limitation does not exist if the RX line is monitored. To monitor the line,
connect it to a digital I/O-capable pin and call setRXWatchPin
with the pin
number. The pin cannot be the same as the RX pin.
The transmitter uses a UART to control all the output. On the Teensy, the UART runs independently. This means that any specified timings won't necessarily be precise. They will often be accurate to within one or maybe two bit times. An effort has been made, however, to make sure that transmitted timings are at least as long as the requested timings.
For example, if a 100us MAB is requested, the actual MAB may be 102 or 103us. If a 40us inter-slot time is requested, the actual time may be 44us. And so on.
Additionally, certain timings will have a minimum length that can't be shortened, for example the MBB. This is simply due to code execution time interacting with the interrupt and UART subsystems. For example, on a Teensy LC, the minimum MBB is about 119us, even if the requested value is 0us.
These are either in the works or ideas for subsequent versions:
The classes you'll need are in the qindesign::teensydmx
namespace: Receiver
and Sender
.
All class documentation can be found in src/TeensyDMX.h
.
Receiver
examples:
BasicReceive
: A basic receive exampleFlasher
: Change the flash speed of the board LED based on DMX inputSender
examples:
BasicSend
: A basic send exampleChaser
: Chases values across all channelsSendADC
: Sends the value from an ADC over a DMX channelSendTestPackets
: Sends test packets (start code 55h)Examples that show how to utilize synchronous and asynchronous transmission:
SIPSenderAsync
: Sends SIP packets asynchronouslySIPSenderSync
: Sends SIP packets synchronouslyExamples that show how to use a synchronous packet handler in a receiver:
SIPHandler
: Understands System Information Packets (SIP) (start code CFh)TextPacketHandler
: Understands text packets (start codes 17h and 90h)Transmitter timing examples:
RegenerateDMX
: Regenerates received DMX onto a different serial port and
with different timingsOther examples:
FastLEDController
: Demonstrates DMX pixel output using FastLEDA more complex example showing how to behave as a DMX USB Pro Widget is
in USBProWidget
.
Both transmission and reception operate asynchronously. This means that there's potentially a continuous stream of data being sent or received in the background.
The transmitter will keep sending the same data until it's changed externally
using one of the Sender::set
functions. Similarly, Receiver::readPacket
and
Receiver::get
will return only the latest data; if more than a small amount of
time elapses between calls, then the data may have been changed more than once.
Both Sender
and Receiver
have a mode where they can operate synchronously.
With Sender
, the stream can be paused and resumed, and packets inserted at
appropriate spots. Similarly, Receiver
can send received packets as they
arrive to start code-specific instances of Responder
.
First, create an object using one of the hardware serial ports, different from any serial ports being used for transmission:
namespace teensydmx = ::qindesign::teensydmx;
teensydmx::Receiver dmxRx{Serial1};
Before using the instance, start the serial port internals:
dmxRx.begin();
Using your own buffer whose length is at least len
bytes, check for a packet
having arrived, and if it has, copy len
values starting from channel
startChannel
:
// For this example, assume buf is at least len bytes long
int read = dmxRx.readPacket(buf, startChannel, len);
read
will contain the number of bytes read, -1 if no packet is available, or
zero if no values were read.
Note that channel zero contains the start code, a special value, usually zero, that occupies the first byte of the packet. The maximum DMX packet size is 513, but may be smaller, depending on the system.
Each call to readPacket
is independent, meaning that if no packet has arrived
after a call to this function, subsequent calls will return -1.
Retrieving 16-bit values is easy with one available 16-bit function:
get16Bit
for single words.This works the same as the 8-bit get
function, but uses the uint16_t
type instead.
The DMX receiver keeps track of three types of errors:
The counts can be retrieved via errorStats()
. This returns an ErrorStats
object containing each of the error counts. These metrics are reset to zero when
the receiver is started or restarted.
An associated concept is disconnection. A receiver is considered connected when it is receiving valid DMX packets. When any timeouts occur, or when invalid BREAKs are detected, then the receiver considers itself disconnected. As soon as valid packets reappear, the receiver is once again connected.
To determine whether a receiver is connected, call its connected()
function.
A callback function, to be notified when this event happens, can also be set
using onConnectChange
.
The following example sets the built-in LED according to the current connected state. It uses a lambda expression, but a normal function could be used instead.
dmxRx.onConnectChange([](Receiver *r) {
digitalWriteFast(LED_BUILTIN, r.connected() ? HIGH : LOW);
});
In actual fact, the connection detection only works for most of the cases where timeouts occur or when bad BREAKs happen. The one thing it can't do is detect when a BREAK condition occurs permanently, and, if none of the periodic interrupt timers (PIT) are available, when an IDLE condition occurs permanently. Unless more data comes in, no further UART interrupts will be generated, so it is up to the user's code to detect this case.
The Flasher
example contains an example of how to do this. In essence, the
readPacket
function will return a positive value if the desired data is
available in the last packet received. A timer can be reset when valid data is
received, and then subsequent code can use the difference between the current
time and the timer value to determine if there's been a timeout.
An example that uses elapsedMillis
to encapsulate the current time call:
constexpr uint32_t kTimeout = 1000; // In milliseconds
elapsedMillis lastPacketTimer{0};
uint8_t buf[250];
void loop() {
int read = dmxRx.readPacket(buf, 0, 217);
if (read == 217) { // Comparing to > 0 means that _some_ data was received
// All the requested data was received
// Do stuff with it
lastPacketTimer = 0;
}
if (lastPacketTimer < kTimeout) {
// Do work
} else {
// No connection
}
}
A second technique would be to use the value returned from
lastPacketTimestamp()
as something that closely approximates the true latest
timestamp. For example:
constexpr uint32_t kTimeout = 1000; // In milliseconds
void loop() {
if (millis() - dmxRx.lastPacketTimestamp() >= kTimeout) {
// Respond to the timeout
}
// Do work
}
In actuality, a timer could be used to detect this condition, but it was chosen to not do this because it would use up a timer, add one extra timeout-specifying method, and the user code is probably good enough.
In summary, the connected concept here has more to do with line noise and bad timing than it does with a physical connection. Perhaps a future release will rename this API concept or address it with the timer...
Short packets are nothing more than valid-looking packets that span a duration less than 1196us. The default is to discard them because they may indicate line noise.
It is possible to keep the data from these packets by enabling the "Keep Short
Packets" feature using the setKeepShortPackets
function. If these are kept
then the PacketStats::isShort
variable will indicate whether the associated
packet is a short packet.
Recall that the readPacket
function can atomically retrieve packet statistics
associated with the packet data. If packetStats()
is used instead, then
there's no guarantee that the values will be associated with the most recent or
next packet data retrieval calls.
Note that there is also an isKeepShortPackets
function that can be polled for
the current state of this feature.
Packet statistics are tracked and the latest can be retrieved from a
PacketStats
object returned by packetStats()
. Included are these variables:
size
: The latest received packet size.isShort
: Whether the last packet was a short packet, a packet having a
duration less than 1196us. Keeping these packets can be enabled with the
setKeepShortPackets
function.timestamp
: The timestamp of the last packet received, in milliseconds. This
is set to the time the packet was recognized as a packet and not the end of
the last stop bit.breakPlusMABTime
: The sum of the BREAK and MAB times, in microseconds. It's
not possible to determine where the BREAK ends and the MAB starts without
using another pin to watch the RX line. To set up a connected pin, see
setRXWatchPin
and the section above on
RX line monitoring.breakToBreakTime
: The latest measured BREAK-to-BREAK time, in microseconds.
Note that this is not collected at the same time as the other variables and
only represents the last known duration. This will be out of sync with the
rest of the values in the presence of packet errors.frameTimestamp
: The BREAK start timestamp, in microseconds.packetTime
: The duration of the last packet, in microseconds, measured from
BREAK start to the end of the last slot.breakTime
: The packet's BREAK time, set if RX line monitoring is enabled.mabTime
: The packet's MAB time, set if RX line monitoring is enabled.If the RX line is not being monitored, then the BREAK and MAB times will be set to zero.
There is also an optional parameter in readPacket
, a PacketStats*
, that
enables retrieval of this data atomically with the packet data.
These metrics are reset to zero when the receiver is started or restarted.
Error statistics are tracked and the latest can be retrieved from an
ErrorStats
object returned by errorStats()
. Included are these counts:
packetTimeoutCount
: Packet timeouts.framingErrorCount
: Framing error count, including BREAKs that were
too short.shortPacketCount
: Packets that were too short.longPacketCount
: Packets that were too long.There is the ability to notify specific instances of Responder
when packets
having specific start codes arrive. To implement the simplest form, simply
extend Responder
, override the receivePacket
function, and attach an
instance to one or more start codes using Receiver::setResponder
.
receivePacket
will be called for each packet received that has one of the
desired start codes.
As well, by default, handlers will "eat" packets so that they aren't available
to callers to the Receiver
API. To change this behaviour, override
Responder::eatPacket()
.
For example, let's say you want to change the local display when a text packet arrvies. The following partial code example shows how to do this.
class TextHandler : public teensydmx::Responder {
public:
static constexpr uint8_t kStartCode = 0x17;
void receivePacket(const uint8_t *buf, int len) override {
// The packet must contain at least 3 bytes (plus the start code)
if (len < 4) {
return;
}
uint8_t page = buf[1];
uint8_t charsPerLine = buf[2];
// Some checks should be made here for the data not ending in a
// NUL character
// Assume the existence of this function
setText(page, charsPerLine,
reinterpret_cast<const char *>(&buf[3]), len - 3);
}
}
TextHandler textHandler;
void setup() {
// ...
dmxRx.setResponder(TextHandler::kStartCode, &textHandler)
// ...
dmxRx.begin();
}
Responders can be added at any time.
Complete synchronous operation examples using SIP and text packets can be found
in SIPHandler
and TextPacketHandler
.
Protocols such as RDM need the ability, not only to process specific packets,
but to respond to them as well. Timing is important, so a Responder
implementation can also be notified of each byte as it arrives. The function of
interest is processByte
.
As bytes are received, the implementation tracks some internal state. When it is
decided that a response is necessary, it returns a positive value indicating how
many bytes it placed into the output buffer, for transmitting back to the
transmitter. The Responder
needs to implement outputBufferSize()
in order
for any response to be sent. processByte
will be passed a buffer at least as
large as the value returned from outputBufferSize()
.
Some other functions that specify some timings should also be implemented.
Please consult the Responder.h
documentation for more details.
Because all processing happens within an interrupt context, it should execute as
quickly as possible. Any long-running operations should be executed in the main
loop (or some other execution context). If the protocol allows for it, the
Responder
can reply with a "not yet" response, and then return any queued
processing results when ready.
A more complete example is beyond the scope of this README.
First, create an object using one of the hardware serial ports, different from any serial ports being used for receive:
namespace teensydmx = ::qindesign::teensydmx;
teensydmx::Sender dmxTx{Serial2};
Before using the instance, optionally set up the packet size and refresh rate, and then start the serial port internals to begin transmission:
// Optional: dmxTx.setPacketSize(100);
// Optional: dmxTx.setRefreshRate(40);
dmxTx.begin();
Set one or more channel values using one of the set
functions:
// Set channel 6 to 219
dmxTx.set(6, 219);
The other set
function can set multiple channels at once. This is left as an
exercise to the reader.
Setting 16-bit values is easy with two available 16-bit functions:
set16Bit
for single words, andset16Bit
for an array of words.These work the same as the 8-bit set
functions, but use the uint16_t
type instead.
The packet size can be adjusted and retrieved via setPacketSize
and
packetSize()
. Smaller packets will naturally result in a higher
refresh rate.
This can be changed at any time.
The minimum packet time is 1204us, and so as long as the actual time doesn't fall short of this, there is no minimum packet size. The equation is:
Packet Size >= max{(1204us - BREAK - MAB)/44us, 0}
Note that because the library operates asynchronously, if the packet size needs to be changed at the same time as the data, both must be set atomically. There are several ways:
Disable the interrupts:
__disable_irq();
dmxTx.setPacketSize(...);
dmxTx.set(...);
__enable_irq();
The disadvantage of this approach is that it disables all interrupts, possibly affecting the behaviour of other libraries. Instead of global interrupt disable, only the IRQ of the specific serial port in use should be disabled, but this is (currently) beyond the scope of this document.
Pause and resume:
dmxTx.pause();
while (dmxTx.isTransmitting()) {
yield();
}
dmxTx.setPacketSize(...);
dmxTx.set(...);
dmxTx.resume();
The disadvantage of this approach is that it uses more code and effectively pauses execution.
Use the setPacketSizeAndData()
function:
dmxTx.setPacketSizeAndData(...);
This is probably the easiest approach.
The transmission rate can be changed from a maximum of about 44Hz down to as low
as you wish. See the setRefreshRate
and refreshRate()
in Sender
.
Note that the rate won't be higher than the limits dictated by the protocol,
about 44Hz, no matter how high it's set. The default is, in fact, INFINITY
.
This can be changed at any time.
If the MBB time is also specified and it would conflict with the desired rate, then the larger of the two possible MBB times will be used to achieve either the specified rate or the specified MBB. See MBB time for more information.
Sender
is an asynchronous packet transmitter; packets are always being sent.
To ensure that certain packets are adjacent to others, such as for System
Information Packets (SIP), the API provides a way to send packets synchronously.
Firstly, the pause()
function pauses packet transmission, the resume()
function resumes transmission, and resumeFor(int)
resumes transmission for a
specific number of packets, after which transmission is paused again.
There are two ways to achieve synchronous operation. The first is with
isTransmitting()
. It indicates whether the transmitter is sending anything
while paused---it always returns true
when not paused---and can be used
to determine when it's safe to start filling in packet data after a resumeFor
or pause()
call.
The second way is to provide a function to onDoneTransmitting
. The function
will be called when the same conditions checked by isTransmitting()
occur. It
will be called from inside an ISR, so take this into account.
It is important to note that when utilizing the pause feature, changing data via
the set
functions should only be done while not transmitting. Pausing doesn't
immediately stop transmission; the pause happens after the current packet is
completely sent. Changing the data may affect this packet.
Let's say you want to send a SIP packet immediately after a regular packet. The following code shows how to accomplish this using the polling approach:
// Before the code starts looping, pause the transmitter
dmxTx.pause();
// Loop starts here
fillRegularData();
dmxTx.resumeFor(1); // Send one regular packet
while (dmxTx.isTransmitting()) { // Wait for this packet to be sent
yield();
}
fillSIPData();
dmxTx.resumeFor(1); // Send the SIP data
while (dmxTx.isTransmitting()) { // Wait for this packet to be sent
yield();
}
Using the asynchronous notification approach requires keeping track of some state, and is slightly more complex than the polling approach.
Other functions of interest are isPaused()
and resumedRemaining()
.
isPaused()
indicates whether the transmitter is paused (but still potentially
transmitting). resumedRemaining()
returns the number of packets that will be
sent before the transmitter is paused again.
Complete synchronous operation examples using SIP can be found in
SIPSenderAsync
and SIPSenderSync
. The first uses the asynchronous
notification approach and the second uses the polling approach.
The BREAK and MAB times can be specified in two ways:
setBreakTime
and setMABTime
functions, orsetBreakSerialParams
function.The default times are set, in both cases, to approximately 180us for the BREAK and approximately 20us for the MAB.
The mode is switched between these two options using the
setBreakUseTimerNotSerial
function. The default is to use
serial parameters.
This is the first way to generate these times.
The BREAK will be transmitted with a duration reasonably close to the specified value, but the actual MAB time may be larger than requested. This has to do with how the UARTs on the chip work.
This feature uses one of the PIT timers via PeriodicTimer
(or, optionally,
the IntervalTimer
API), but if none are available, then the transmitter will
fall back on using the baud rate generator with the specified serial
port parameters.
The BREAK timing is pretty accurate, but slightly shorter and longer times have been observed.
(If using the IntervalTimer
API, there's some inaccuracy. It doesn't provide a
way to execute an action (in this case, starting a BREAK) just before the timer
starts. Instead, the timer will have already started and some time elapsed
before the BREAK can start.
Efforts have been made to make the BREAK time be at least the amount requested, but it likely won't be exactly the requested duration.)
The MAB time may be longer than requested. The reason is that it's not possible to immediately start sending a character using the UART on the Teensy chips. It seems that the best resolution one can get is "somewhere within one or two bit times".
To illustrate: BREAK ->(immediate) MAB ->(not immediate) First packet character
For example, if a timer aims for a 23us MAB, and then a character is sent to the UART after the timer expires, then that character might start after 25us. If the timer is adjusted so that it expires 2us earlier, then the character might still appear too late, still after 25us, for example. A further adjustment of 2us, for a timer duration of 19us, might result in the character appearing after 21us, earlier than requested.
When a character starts, it appears that the UART performs its functions asynchronously, and so it is not possible to achieve exact timing. The code adjusts the MAB time under the covers to achieve times that are as close to the requested time as possible without going under, but it is often not possible to be more precise than "within one or two bit times", depending on the processor.
This is the second way to generate these times.
The times are restricted to having a BREAK:MAB ratio of 9:2, 10:2, 9:1, 10:1, 9:3, 8:2, or 11:1. These correspond to the UART formats, 8N2, 8E2, 8N1, 8E1, 8O2, 7O1, and 9E1. For additional information on this subject, see the BREAK Timing in DMX512-A note.
The BREAK time will be fairly accurate, but the MAB time will be a little longer than expected, by up to at least several bit times.
This is a less flexible way to specify the BREAK and MAB times. The baud rate is changed just for these and then changed back to 250kbaud (8N2) for the packet data. The act of changing the baud rate can introduce a delay, somewhere up to one full character.
This mode is also used as a fallback if the system doesn't have the timers available.
The inter-slot MARK time can be set with the setInterSlotTime
function and
retrieved using the interSlotTime()
function. Note that the MARK time should
be accurate to within one or two bit times due to internal UART details. See
A note on MAB timing for more information.
The MARK before BREAK (MBB) time can be set with the setMBBTime
function and
retrieved using the mbbTime()
function. Note that the time should be accurate
to within one or two bit times due to internal UART details. See
A note on MAB timing for more information.
Note also that there will always be some minimum transmitted MBB due to how the code and UART interact.
If the refresh rate is set as well then the actual MBB time will be whichever makes the packet larger. For example, if the MBB is set to 100us, but adding this to the packet would result in a rate that's slower than specified, then 100us is used. On the other hand, if adding the same MBB would make the specified rate faster, then enough additional time will be added so that the rate is correct.
Several Sender
functions that return a bool
indicate whether an operation
was successful. Prior versions of the library did nothing with, or silently
ignored, bad arguments.
The status-returning functions are as follows:
setPacketSize
,set
functions,set16Bit
functions,setRefreshRate
, andresumeFor
functions.The same serial port can't be used for simultaneous transmit and receive. This is because the library uses the serial port hardware for data instead of direct pin control. The break portion of a DMX frame needs to be transmitted at a different baud rate than the slots (channels), and since reception and transmission aren't necessarily synchronized, two different serial ports must be used.
Use qindesign::teensydmx::Receiver
to receive and
qindesign::teensydmx::Sender
to transmit.
From a UART perspective, there are two parts to a DMX frame:
The total frame time is approximately:
10 bits 20 us + 513 slots 11 bits * 4us = 22772us, or a rate of about 43.91Hz.
The total frame time may be a little longer due to switching baud rates internally and the existence of some interrupt and code execution latency.
Some setups may require that an external part be enabled when transmitting or receiving. For example, an RS485 transceiver may require enabling or disabling specific buffers. That may be accomplished by using one of the GPIO pins. Please be sure the logic levels are compatible.
This code is not thread-safe and should be handled appropriately if utilized in a concurrent context.
The Receiver::setResponder
function dynamically allocates memory. On small
systems, this may fail. The caller can check for this condition by examining
errno
for ENOMEM
. If this occurs, then the function will return nullptr
,
but otherwise fails silently. Additionally, all responders are wiped out,
including any previously-set responders.
DMX uses RS-485 differential signalling. This means that a transceiver is needed between the Teensy and the DMX lines. See DMX512 for DMX connector pin guidance.
It is beyond the scope of this document to describe how to accommodate transmission line effects of long lines.
Receiver
and driving the TX pinBy default, when a Receiver
is used, the TX pin for its serial port is
enabled. This means that the line is driven. This default state was chosen
because custom responders may wish to transmit information. Additionally, the
caller does not need to remember to enable the transmitter when adding a
custom responder.
If it is known that there are no responders or that no responders will send
data, then the TX pin can be disabled so that the UART hardware isn't driving
the line. The Receiver::setTXEnabled
function can be called either during
operation or outside a begin
and end
pair.
Be aware that if the receiver is currently in operation, enabling the transmitter will cause an 11-bit idle character to be queued for output and the line to remain high after that.
By default, this library internally uses PIT timers via Teensy's default
IntervalTimer
API. For more accurate BREAK timing, a custom API,
PeriodicTimer
, can be used instead. Globally define the
TEENSYDMX_USE_PERIODICTIMER
macro when building and the library will use this
custom API. However, be aware that conflicts may occur if other libraries in
your project use IntervalTimer
.
Code style for this project mostly follows the Google C++ Style Guide.
Other conventions are adopted from Bjarne Stroustrup's and Herb Sutter's C++ Core Guidelines.
Inspirations for this library:
Copyright (c) 2017-2021 Shawn Silverman