Receive DMX-512 with an Arduino

By Max
arduino

Shiny and new out of the box!

Prologue: For Christmas, I received an Arduino.  If you’re not familiar with them, they’re like a little computer with a lot of pins to which you can connect outputs like LEDs, servos, relays, triacs, or anything you’d want to control, as well as photosensors, switches, anything you’d want to take an input from.  You write your program in the easy-to-learn Arduino environment, upload it to the Arduino board, and it’ll run your program automagically.  I’m not a programmer, but less than an hour after taking it out of the box I had it blinking an LED for me.  Buy one, they’re perfect for all of us who are trying to create some Theater Magic with no money or hope of getting any.

Well, Almost Perfect.  There’s been a way to send DMX with an Arduino for awhile, but when I started poking around for DMX reception code, I came up with zilch.  If you’re already savvy with microcontrollers and assembly code and avrdude and whatever-the-fuck-else, you probably know about this solution.  Me, I look at assembly code and I just hear a dull screaming in my head, nevermind all that other stuff that I don’t know how to do either.

So I figured that a great first project would be to remedy this situation, and write a program to receive DMX on the Arduino platform.  In the way of all Works in this Vale of Tears, this ended up being much more difficult and taking much longer than I initially anticipated.  But eventually I figured it all out, and so here it is!

Features:

  • In-the-field addressing from 1 to 512 via two tact switches (works with the previously released I/O Shield, here).
  • Address is stored in non-volatile EEPROM, so it is retained when power is lost to the Arduino.
  • Addressing hardware allows full use of the pins.
  • Number of addresses to receive is configurable.
  • Works with controllers that send less than the full 512 address set.
  • Break detection is done correctly by detecting a Low value of >88μS per ANSI E1.11-2008, rather than the frame error hack used by many devices.
  • Uses interrupt-based subroutines to eliminate processor-load related timing problems.
  • If the DMX data signal is lost, the Arduino will maintain the current state until new values are received.
  • The reception and user code run sequentially rather than at the same time, so they won’t interfere with each others’ timing.


You Will Need:

  • A copy of the latest release and the modified wiring_serial.c or HardwareSerial.cpp file.  See the instructions for what to do with the files.   *update*:  This post is now more than four years old.  Some people have reported success using the 1.0+ software, but I’d start with the older rev 0023 of the IDE and go from there once you get it working.  Download it here, under Previous IDE Versions.
  • An Arduino with an Atmega168 or Atmega368 processor.  Because of the timing-sensitive nature of DMX-512, some of the code had to be optimized by referring to particular registers on the Atmega168/368.  The code can easily be adapted to other processors, though.
  • An RS-485 to Serial Transceiver, such as the MAX485 or the TI 75176.  They’ll run you about $1, the MAX485 is a little more but it apparently has some kind of fancy overvoltage protection, so I used that.
  • A breadboard and some wires, also a 150Ω resistor to terminate the DMX line if necessary.

Instructions:

DMX uses a twisted pair of signal wires with opposite polarity to transmit information per RS-485.  However, your Arduino needs a serial signal, with a pin brought high for one and low for zero.  To convert between these protocols, you’ll need to wire up your MAX485 or 75176 in the following way:

Schematic Rev2

Here are some pictures which may help you:

The prototype from the left.

The prototype from the left.

 

The prototype from the right.

The prototype from the right.

Note 1: Starting with Rev11 of the software, I adjusted the pin layout slightly for better routing on the DMX I/O Shield.  The two gray wires in the above photos that are plugged into pins 3 and 4 should be plugged into pins 2 and 3, respectively, if you’re using the latest software.

Note 2: I’m using the Arduino protoshield here, which I highly recommend, they’re handy.  If you don’t have one, the pin layout is the same as if you ran directly into the Arduino board.

Note 3: if you want to retain the use of pins 1, 4, and 5, at the cost of being able to transmit as well as receive, you can connect the corresponding pins on the MAX485 to the ground on the Arduino board.  I’ve done it this way for possible future RDM functionality ;).

One Dumb Hack is necessary: rename your currently installed HardwareSerial.cpp file to HardwareSerial.cpp.backup, and put the modified HardwareSerial.cpp from this site in the same directory.  It’s located in:

(Arduino Install Directory)/hardware/cores/arduino/

The reason for this is that the Arduino software defines the USART_RX_vect serial reception interrupt, and includes it in your compiled code, even if you don’t use any serial functions.  This will, I hope, be fixed in a future release, but until it is this is the work-around.  You can read more about the issue here.  Once you’ve uploaded the sketch and it’s working to your satisfaction, you can undo this part to regain your normal serial library functionality.

Finally, fire up the Arduino software, and put what you want the Arduino to do with the received values in the action() loop. The received values are stored in the dmxvalue[] array. The downloaded sketch contains example code to print out each of the values to the serial port, and set PWM pins 5 and 6 to the first and second value in the array, respectively, but this can of course be changed to anything you want.

That’s it, let me know how it works for you!  You may want to keep reading for the Known Limitations, etc.

Known Limitations:

  • Atmega168 and Atmega328 based processors only (you will have to rename the registers and interrupt vectors if you want to use it for another processor).
  • I personally only test the software with a USB-DMX Pro controlled via Lightfactory, since that’s what I have laying around.  But it handles a variety of frame rates, break lengths, etc. just fine.  The consensus seems to be that it works just fine with other controllers.
  • Because I needed access to exact timing, I had to use the Timer2 functionality, so pins 3 and 11 cannot be used for PWM.  The Timer2 issue is also the most frequent cause of incompatibility problems when using community-developed libraries.  See the comments for remedies if you’re affected by this.
  • Will not detect bad addressing.  For example, with it set to receive the default 8 channels, “dmxaddress=510;” would give you two good channels and six channels of junk.  Or “dmxaddress=50;” when only 55 addresses are sent by the controller.  Edwin Dolby at Laser Productions had an elegant idea to address this, namely that you could use the constrain function to map out of bounds values to the correct 0-511 range.  However, I have decided not to implement this by default, as without some kind of numerical readout I think the values should just be set to what you set them.  But, easy to implement if you decide you want it!
  • When addressing, sometimes when you hit the 0 or 1 switch it doesn’t take.  I’ve programmed the LED to turn off briefly if the bit was successfully entered, so if you don’t see it go off, you’ll have to hit the switch again until it takes.  I don’t know why it’s doing this, if you have some time to wade through the logic let me know why and I’ll update the code. Ron Barber was good enough to figure out why it was doing this and show me how to fix it.  Thanks Ron!

Future Development:

  • Add a dip switch and code to allow in-the-field addressing.
  • Reduce the number of Atmega168-specific functions to improve code portability.
  • Design a shield for better durability, signal pass-through, termination, etc. Check here!
  • Add frame error and data overrun error handling routines.
  • Add RDM functionality.
  • Develop a separate DMX monitor application in Processing or the like.
  • Timer2 is currently used for break detection.  I’m thinking that I could re-write the code so that it records the configuration register values currently existing, sets them to what it needs, and then puts them back the way it found them.  That way, you would be able to use your other libraries that rely on this timer (of which there are apparently a lot), as long as they didn’t need to run during break detection.  Advantages and disadvantages to this, obviously.  But the #1 issue seems to be ‘doesn’t work with library X’, so for most of you this would be an improvement.  Or a polling loop might even be good enough, and then we could forgo the timer business altogether.
  • The documentation for this project has sprawled out onto so many posts and comments that it’s difficult for even me to find, I’m looking at trying to consolidate everything into a minisite or something.  I’d also like to add a big ‘how it works’ section, which would help those of you trying to customize the code.

Release History and Notes:

  • 9 October 2010: Rev15.
    • Tested and working with IDE version 0021.  I have not tested it with the new Arduino Uno hardware, but can’t think of any reason why it wouldn’t work.  If you have any success or otherwise with the new hardware, drop a line in the comments.
    • A bug has been fixed in the addressing routine caused by button debounce, and the addressing routine logic has been simplified and made clearer.  Big thanks to Ron Barber for pointing out the source of the bug and contributing new code.
    • There is now a check when the previously stored address is read from EEPROM to ensure that it is in the valid range of 1-511, to prevent a bad value being read in from uninitialized EEPROM.
    • Fixed a potential bug in the break detection routine that could cause the read values to be off by one in cases where the break from the microcontroller was exactly 88uS.
  • 23 June 2010: Rev14
    • Tested and working with IDE version 0018.
  • 9 July 2009: Rev13
    • Tested and working with IDE version 0016.
    • The number of channels to receive is now easily user-configurable.
    • Replaced static variables with #define statements for memory optimization (+48 bytes, woot!).
  • 12 May 2009: Rev12
    • In-the-field addressing via two tact switches (works with the previously released I/O Shield, here).
    • Address is stored in non-volatile EEPROM, so it is retained when power is lost to the Arduino.
    • Addressing hardware allows full use of the pins (which is why I didn’t use the more conventional dip switch setup).
    • Some of the variables were localized, since the sketch is now getting pretty complex.
  • 27 April 2009: Rev11
    • Adjusted pin layout for better routing on the DMX I/O Shield.  Pins 3 and 4 in Rev10 are now pins 2 and 3, respectively.
  • 1 April 2009: Rev10
    • Cleaned up and improved code commenting.
    • Adjusted HardwareSerial.cpp (included) so the code will compile on Arduino software release 0015.  If you’re still using 0014 or 0013, you’ll replace wiring_serial.c instead (also included).
    • Replaced manual register configuration of the USART with the Arduino function serial.Begin(250000), which apparently works just as well and reduces the number of Atmega168-specific register calls considerably.
    • Moved the action() loop (what you want the Arduino to do with the received values) to its own tab, to make the code easier to use.
  • 20 March 2009: Rev09
    • First release
  • Rev00-Rev08: Pre-release betas.

The Code: Here is the .pde sketch file.  It may be of general interest as well if you’re trying to write interrupt-based programs for the Arduino.  In the download, there is also a tab for the user code and another for in-the-field addressing module.

[cc]

/***********************************************************
* DMX-512 Reception                                        *
* Developed by Max Pierson                                 *
* Version Rev15 9 Oct 2010                                 *
* Released under the WTFPL license, although I would       *
* appreciate Attribution and Share-Alike                   *
* See blog.wingedvictorydesign.com for the latest version. *
************************************************************/

/******************************* Addressing variable declarations *****************************/

#include <EEPROM.h>
#define NUMBER_OF_CHANNELS 8
//the number of channels we want to receive (8 by default).

#define SWITCH_PIN_0 11 //the pin number of our "0" switch
#define SWITCH_PIN_1 12 //the pin number of our "1" switch
unsigned int dmxaddress = 1;
/* The dmx address we will be listening to.  The value of this will be set in the Addressing()
*  function and read from EEPROM addresses 510 and 511.

/******************************* MAX485 variable declarations *****************************/

#define RECEIVER_OUTPUT_ENABLE 2
/* receiver output enable (pin2) on the max485.
*  will be left low to set the max485 to receive data. */

#define DRIVER_OUTPUT_ENABLE 3
/* driver output enable (pin3) on the max485.
*  will left low to disable driver output. */

#define RX_PIN 0   // serial receive pin, which takes the incoming data from the MAX485.
#define TX_PIN 1   // serial transmission pin

/******************************* DMX variable declarations ********************************/

volatile byte i = 0;              //dummy variable for dmxvalue[]
volatile byte dmxreceived = 0;    //the latest received value
volatile unsigned int dmxcurrent = 0;     //counter variable that is incremented every time we receive a value.
volatile byte dmxvalue[NUMBER_OF_CHANNELS];
/*  stores the DMX values we're interested in using--
 *  keep in mind that this is 0-indexed. */
volatile boolean dmxnewvalue = false;
/*  set to 1 when updated dmx values are received
 *  (even if they are the same values as the last time). */

/******************************* Timer2 variable declarations *****************************/

volatile byte zerocounter = 0;
/* a counter to hold the number of zeros received in sequence on the serial receive pin.
*  When we've received a minimum of 11 zeros in a row, we must be in a break.  */

void setup() {

  /******************************* Max485 configuration ***********************************/

  pinMode(RECEIVER_OUTPUT_ENABLE, OUTPUT);
  pinMode(DRIVER_OUTPUT_ENABLE, OUTPUT);
  digitalWrite(RECEIVER_OUTPUT_ENABLE, LOW);
  digitalWrite(DRIVER_OUTPUT_ENABLE, LOW);    //sets pins 3 and 4 to low to enable reciever mode on the MAX485.

  pinMode(RX_PIN, INPUT);  //sets serial pin to receive data

  /******************************* Addressing subroutine *********************************/

  pinMode(SWITCH_PIN_0, INPUT);           //sets pin for '0' switch to input
  digitalWrite(SWITCH_PIN_0, HIGH);       //turns on the internal pull-up resistor for '0' switch pin
  pinMode(SWITCH_PIN_1, INPUT);           //sets pin for '1' switch to input
  digitalWrite(SWITCH_PIN_1, HIGH);       //turns on the internal pull-up resistor for '1' switch pin

  /* Call the addressing subroutine.  Three behaviors are possible:
  *  1. Neither switch is pressed, in which case the value previously stored in EEPROM
  *  510 and 511 is recalled,
  *  2. Both switches are pressed, in which case the address is reset to 1.
  *  3. Either switch is pressed (but not both), in which case the new address may
  *  be entered by the user.
  */
  //set this equal to a constant value if you just want to hardcode the address.
  dmxaddress = Addressing();

  /******************************* USART configuration ************************************/

  Serial.begin(250000);
  /* Each bit is 4uS long, hence 250Kbps baud rate */

  cli(); //disable interrupts while we're setting bits in registers

  bitClear(UCSR0B, RXCIE0);  //disable USART reception interrupt

  /******************************* Timer2 configuration ***********************************/

  //NOTE:  this will disable PWM on pins 3 and 11.
  bitClear(TCCR2A, COM2A1);
  bitClear(TCCR2A, COM2A0); //disable compare match output A mode
  bitClear(TCCR2A, COM2B1);
  bitClear(TCCR2A, COM2B0); //disable compare match output B mode
  bitSet(TCCR2A, WGM21);
  bitClear(TCCR2A, WGM20);  //set mode 2, CTC.  TOP will be set by OCRA.

  bitClear(TCCR2B, FOC2A);
  bitClear(TCCR2B, FOC2B);  //disable Force Output Compare A and B.
  bitClear(TCCR2B, WGM22);  //set mode 2, CTC.  TOP will be set by OCRA.
  bitClear(TCCR2B, CS22);
  bitClear(TCCR2B, CS21);
  bitSet(TCCR2B, CS20);   // no prescaler means the clock will increment every 62.5ns (assuming 16Mhz clock speed).

  OCR2A = 64;
  /* Set output compare register to 64, so that the Output Compare Interrupt will fire
  *  every 4uS.  */

  bitClear(TIMSK2, OCIE2B);  //Disable Timer/Counter2 Output Compare Match B Interrupt
  bitSet(TIMSK2, OCIE2A);    //Enable Timer/Counter2 Output Compare Match A Interrupt
  bitClear(TIMSK2, TOIE2);   //Disable Timer/Counter2 Overflow Interrupt Enable          

  sei();                     //reenable interrupts now that timer2 has been configured. 

}  //end setup()

void loop()  {
  // the processor gets parked here while the ISRs are doing their thing. 

  if (dmxnewvalue == 1) {    //when a new set of values are received, jump to action loop...
    action();
    dmxnewvalue = 0;
    dmxcurrent = 0;
    zerocounter = 0;      //and then when finished reset variables and enable timer2 interrupt
    i = 0;
    bitSet(TIMSK2, OCIE2A);    //Enable Timer/Counter2 Output Compare Match A Interrupt
  }
} //end loop()

//Timer2 compare match interrupt vector handler
ISR(TIMER2_COMPA_vect) {
  if (bitRead(PIND, PIND0)) {  // if a one is detected, we're not in a break, reset zerocounter.
    zerocounter = 0;
    }
  else {
    zerocounter++;             // increment zerocounter if a zero is received.
    if (zerocounter == 20)     // if 20 0's are received in a row (80uS break)
      {
      bitClear(TIMSK2, OCIE2A);    //disable this interrupt and enable reception interrupt now that we're in a break.
      bitSet(UCSR0B, RXCIE0);
      }
  }
} //end Timer2 ISR

ISR(USART_RX_vect){
  dmxreceived = UDR0;
  /* The receive buffer (UDR0) must be read during the reception ISR, or the ISR will just
  *  execute again immediately upon exiting. */

  dmxcurrent++;                        //increment address counter

  if(dmxcurrent > dmxaddress) {         //check if the current address is the one we want.
    dmxvalue[i] = dmxreceived;
    i++;
    if(i == NUMBER_OF_CHANNELS) {
      bitClear(UCSR0B, RXCIE0);
      dmxnewvalue = 1;                        //set newvalue, so that the main code can be executed.
    }
  }
} // end ISR
[/cc]

P.S.: There’s a really good comment thread for this post and it may answer your question, especially if it is of the form ‘will it work with this other Arduino library?’ So take a gander at that before writing a comment, if you would.


One Response to “Receive DMX-512 with an Arduino”

Leave a Reply