message:
How to use components that don't have a shield?

I recently started messing around with an Arduino and I have made a few "gadgets" using shields. I then wondered how I would go about using things I can't find shields for.

One specific thing I want to do is to be able to use the larger e-paper displays from Pervasive Displays (7'' and 10'') but a brief consultation with Google found no Arduino kits or shields. I then looked through the documentation of the timing controller for the 7'' display and found the information required to be able to use it (initiation, sending data to be drawn, opcodes, etc.). I then decided to check the Github repo for the examples for the 2'' displays and they seem to just do what the documentation says to do.

Is my observation naive here? Is it really as straightforward as following the documentation? No magic sauce?

Note: I don't have a clue how complex using the 7'' display actually is, I just used it as an example because I had just looked it up...

body:
Your observation is correct. Everything breaks down to some number of physical connections and some protocol for communicating with the device. Shields and libraries associated with them do most of the work for you, but not everything comes in a shield.

There are some common protocols for interfacing with devices, including [SPI][1] and [I2C][2]. From a quick peek at the [driver interface sheet][3], it looks like they're using SPI. Well, your [Arduino already supports that][4] so you can hit the ground running with this display. You just need to know what commands to send to it, which you can find from the display's datasheet.

**Note:** It looks like the 2" screen requires 3.3V while the 7" one supports up to 7V.

  [1]: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
  [2]: http://en.wikipedia.org/wiki/I²C
  [3]: http://www.pervasivedisplays.com/products/2inch
  [4]: http://arduino.cc/en/Reference/SPI


sender: user

message:
Manchester Library Won't Compile for Attiny85

I am creating a wireless sensor using an Attiny85.  I want to send the data to an arduino uno, so I purchased the 315mhz rf link kit from spark fun.  Since the Attiny85 does not have a TX I decided to use the Manchester library however it won't compile on the Attiny85.

I followed the steps from this blog :
http://mchr3k-arduino.blogspot.mx/2012/01/wireless-sensor-node-part-2.html?showComment=1338749638806#c853067277980266192

Here is the code I am using:

        #include <WProgram.h> //otherwise it says it can't find Arduino.h
        #include <Manchester.h> //include the library to comunicate
        #define TxPin 2 //the pin that is used to send data

     int sensorPin = 4;
     int ledPin = 3;
     int count = 50;

     void setup(){
      pinMode (ledPin, OUTPUT);
      man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
      man.setupTransmit(TxPin, MAN_1200); //set transimt pin
    }

    void loop(){
      if (count == 50){
       digitalWrite (ledPin, HIGH);
       count = 0;
       }
       int data = analogRead(sensorPin);
       man.transmit(data); //transmits and reads the data
       delay (100);
       count ++;
     }

Here is the error message:

    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp: In function 'void MANRX_SetupReceive(uint8_t)':
    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'TCCR2A' was not declared in this scope
    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'WGM21' was not declared in this scope
    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'TCCR2B' was not declared in this scope
    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'CS21' was not declared in this scope
    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:369: error: 'OCR2A' was not declared in this scope
    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'TIMSK2' was not declared in this scope
    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'OCIE2A' was not declared in this scope
    /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:380: error: 'TCNT2' was not declared in this scope

sender: assistant

body:
attiny is missing an option required to allow the Manchester library to function properly on ATtinyX5 devices, specifically definition of `__AVR_ATtinyX5__` when a device is selected. In fact, it's missing quite a few things.

The package I use for ATtinyX5 support is arduino-tiny. I have verified that it defines that symbol properly. I recommend that you dump your current support package and install arduino-tiny instead.


body:
Having struggled through this myself, I can confirm that Joel's solution works.

There are quite a lot of posts around that suggests that you can't get the Manchester to work with Arduino1.0x and you need 0020. But you can.

The key is to use the arduino-tiny from the link above, put the tiny folder which you get from there in /hardware and then rename it to attiny and “prospective boards” to boards.

I realise that this doesn’t say any more than Joel already has, but there is so much conflicting and contradictory information around I thought it would be worth adding in my experience


body: Got the same problem using this lib with a 8 MHz Trinket, but managed to solve it by adding `#define __AVR_ATtinyX5__` to the file hardware/attiny/variants/tiny8/pins_arduino.h. I'm using the Adafruit support package for ATtiny. Perhaps a bit of a hack, but I can still build for the UNO, by selecting board in Arduino IDE 1.0.5.


message:
Arduino Mega & WiFi Shield; why web server every time says my A7 pin reads 0V?

I have got Arduino Mega 2560, Arduino WiFi Shield and resistor 1.5K.

Now PWM 2 is attached to the resistor then attached GND. 5V is attached between PWM2 and resistor's up point. I want to read the Arduino Mega's A7 analog input point in order to print this value on an Android Phone's web browser but, I get zero value every time surprisingly. It should be like 235, 350 something like integer or float kinds as usual.

According to Android Phone's Google Chrome Web Browser Page, why there are too many zeros in the HTML? It should be different from zeros because I have already added a short wire to Analog A7 so as to make an antenna.

A photo of my setup:

![My workside][1]

Screenshot of my Android web browser

![Android Phone Screen][2]

Serial Monitor output

![Arduino IDE & Serial Monitor][3]

My code:

    #include <SPI.h>
    #include <WiFi.h>

    char ssid[] = "Connectify-me";
    char pass[] = "***";
    int status = WL_IDLE_STATUS;
    float PPG = analogRead(A7);
    boolean door_status = false;
    WiFiServer server(80);
    void setup() {
      Serial.begin(9600);
      while ( status != WL_CONNECTED) {
        Serial.print("Yazdigin SSID araniyor: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        delay(10000);
      }
      server.begin();
      printWifiStatus();
    }
    void loop() {
      WiFiClient client = server.available();
      if (client) {
        Serial.println("Deger gonderildi");
        Serial.print(PPG);
        while (client.connected() & client.available()) {
              client.println("");
              client.println("");
              client.println("
");
              client.print(PPG);  //The value should different from zeros but everytime 0
              client.println("
");
              client.println("
");
              client.println("");
              client.println("");
          }
        }
        delay(3000);
          client.stop();
          Serial.println("client disonnected");
      }
      void printWifiStatus() {
      Serial.print("Baglandigimiz SSID: ");
      Serial.println(WiFi.SSID());
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Addressi browserda ac: ");
      Serial.println(ip);
      long rssi = WiFi.RSSI();
    }

  [1]: https://i.stack.imgur.com/MFCwt.jpg
  [2]: https://i.stack.imgur.com/tH4Jq.png
  [3]: https://i.stack.imgur.com/vba5T.png

body: The capacitor in the sample-and-hold circuit in the ADC frontend is tied to ground and it is *very* leaky. Unless you have a low or medium impedance output connected to it, you will always read the ground value. An antenna is a *very* high impedance device.


body: You are reading the input pin `float PPG = analogRead(A7);` only in the startup code of your program. Move that into the loop to have it updated before using it.


message:
Connect Arduino with fischertechnik TX Controller

Is it possible to cinnect the Arduino with a fischertechnik TX Controller? Maybe with I²C, but i want to use I²C for something else on the arduino. So are there multiple I²C Ports on the Arduino (I haven't got one yet)?

body:
As described in the [Wire library][1] that brings supports I²C support to Arduino, except for the **DUE** that has 2 pairs of pins for 2 I²C buses, **other Arduino boards support one I²C connection**.

However, this is when you want to use hardware facilities of ATMEL chips that these limitations apply; there is a [software I²C library][2] exists that allows using other pins for I²C. One major drawback, though, is that it is very slow; not sure if this is a problem in your situation.

One important thing though: the principle of I²C is to be able to plug several slave devices (more than 100) to one master device. In general, Arduino is the master device, but the Wire library can be used as master or slave. Wouldn't that fit your requirements?

In this situation, you could just use the same I²C bus for everything, including connection to Fischertechnik TX controller.

  [1]: http://arduino.cc/en/Reference/Wire
  [2]: http://playground.arduino.cc/Main/SoftwareI2CLibrary


message:
Understanding the compilation/linking/upload process (so I don't have to use the IDE)

I have started to play with and arduino UNO quite recently (without any prior experience with micro-controllers). I would like to use emacs instead of the IDE, and I'd also like to know what the IDE does under the hood, in order to be able to write my own makefile. The tutorials I've found are either outdated, or are presented as a series of steps without any explanation. I'd appreciate it if someone could explain to me how the whole compliation/linking/upload process works using gcc-avr and avr-dude, and how it is used by the IDE.

body:
If you want an *exact* duplication of what the IDE does but want it driven from the command line, that's what Ino is for. The full Arduino build process involves copying a lot of files from a lot of places, and is generally not trivial to duplicate.

If you're ready to let go of .ino files and the Arduino libraries, you get a much simpler toolset. avr-gcc compiles, avrdude uploads, and you're done. Here's one of my makefiles from a simple project:

    CC=avr-gcc
    CXX=avr-c++
    CXXFLAGS=-Wall -Wextra -mmcu=atmega1284p -Os
    CFLAGS=$(CXXFLAGS)
    BINARY=ledmatrix
    OBJECTS=

    all: $(BINARY)
    ↹@avr-size $<

    $(BINARY): $(OBJECTS)

    clean:
    ↹@rm -f $(BINARY) $(BINARY).hex $(OBJECTS)

    upload: $(BINARY).hex
    ↹@avrdude -c usbasp -p m1284p -U flash:w:$<:i

    %.hex: %
    ↹@avr-objcopy -j .text -j .data -O ihex $< $@

    .PHONY: all clean upload

If copying-and-pasting, be sure to replace all "↹" with tab characters.

**EDIT:**

I have created a repository with my buildsystem on Github.


body:
Here is a high-level overview of Arduino's compilation process, for folks like me who found this post while hunting for one:

**The compilation process**

The arduino code is actually just plain old c without all the header part (the includes and all). when you press the 'compile' button, the IDE saves the current file as arduino.c in the 'lib/build' directory then it calls a makefile contained in the 'lib' directory.

This makefile copies arduino.c as prog.c into 'lib/tmp' adding 'wiringlite.inc' as the beginning of it. this operation makes the arduino/wiring code into a proper c file (called prog.c).

After this, it copies all the files in the 'core' directory into 'lib/tmp'. these files are the implementation of the various arduino/wiring commands adding to these files adds commands to the language

The core files are supported by pascal stang's procyon avr-lib that is contained in the 'lib/avrlib' directory

At this point the code contained in lib/tmp is ready to be compiled with the c compiler contained in 'tools'. If the make operation is succesfull then you'll have prog.hex ready to be downloaded into the processor.

https://www.arduino.cc/en/Main/Documentation


message:
How can I connect the Tamiya double gearbox to Arduino Uno?

I'm working on building my first robot. this is my first foray into DIY electronics. I already have an Arduino Uno, and I have ordered the [Tamiya double gearbox][1] here. My goal is to control the gearbox to move the robot, but from what I've already read, I need to have something between the Ardiuno and the motors. It seems like people have trouble doing that because the included motors are low voltage, so the Arduino motor shield won't easily work.

I'm looking for a clear solution to making this thing run, in the simplest way possible. One thing I'm considering is replacing the motors in the gearbox [with these motors][3]. If I do that, am I right in thinking I could run them from the Arduino motor shield?

If there is a simpler (or cheaper!) way of making it work than being stuck on the Arduino Motor shield, I'm game for that. I've just gravitated to that solution because it seems simpler as an electronics noob. (I haven't bought that shield yet.) But I'm really open to other solutions, so if you can, I'd appreciate the advice!

  [1]: http://www.pololu.com/product/114
  [3]: http://www.amazon.com/dp/B00JR6IY4M/ref=wl_it_dp_o_pC_S_ttl?_encoding=UTF8&colid=FUN60MOL7TVV&coliid=I4943V9GBF96U

body:
Here's what I've found about both the motor shield and the motors:

 - Motors are 3-6V and will use a lot of amperage. **This may be a problem with a mobile robot.** You'll have to figure out a power source that can provide 4+ amps... on battery power that's a lot. Personally, I would go with a continuous rotation servo for a compact, light robot.
 - Motor sheild can provide 2x 2A channels at 5-12 V ([Source](http://www.makershed.com/Official_Arduino_Motor_Shield_p/mksp12.htm?gclid=CIyNjIKygb4CFe5aMgodpQcAuw)) using the two `+` and `-` terminals on the bottom left side of the shield. You must connect external power, because USB can't provide enough power. I can't find if the motor shield will limit current if it goes over, but if you do use the gearbox, I'd recommend another route for control that's 1/6rd the price.

[This chip was recommended by Pololu on the product page.](http://www.pololu.com/product/2130)

![][1]

**Time to whip out your soldering iron!** Really, soldering is a great investment and you'll get to a point soon where you'll *need* one; there will be no other alternative. Luck for you, you only have to solder 16 joints. Headers are included.

Diagrams from Pololu's site:

>![][2]

>![][3]

>![][4]
*(Click to enlarge ^^^)**

*I added a little text to this image.

  [1]: https://i.stack.imgur.com/adDy1.jpg
  [2]: https://i.stack.imgur.com/t7iEx.png
  [3]: https://i.stack.imgur.com/vwiM4.jpg
  [4]: https://i.stack.imgur.com/DyuR1.png


body:
The FA130 type electric motors in the Tamiya Double Gearbox Kit (No. 70168) are 1.5v-3v DC motors with current ratings of 0.20A (no load), 0.66A (@ max. efficiency) and 2.2A (stall), see [1.5-3V DC Motor 6990 RPM][1]. They are not high current motors.

  [1]: https://www.jameco.com/z/FA-130RA-2270-Mabuchi-Motor-Company-1-5-3V-DC-Motor-6990-RPM_2192755.html


message:
Level detection of 3.3V from 5V arduino

A quick question about microcontroller digital level on I/O pins. I have a photo interrupter which is powered at 3.3V which is interfaced to Arduino UNO running at 5V.

For microcontroller to detect high or low level is determined by signal higher than 5V*(2/3) = 3.33V is high and signal lower than 5V*(1/3) is low. What I don't understand is that arduino is able to detect the level change from the photo interrupter. Doesn't the supply on pins have to be greater than (2/3) or Vcc in order for it to detect logic high? The circuit works and I am able to count pulses from the interrupter but I want to know why that works considering the photo interrupt only gets about 3.23V.

Please clarify

body: You've... misread the datasheet. The '328 input high voltage (VIH) for most pins is 0.6VCC minimum for devices with a 2.4-5.5V supply. This means that a 5V device has a 3V threshold.


body:
The designed threshold of the '328 logic is 45% of Vcc for all supply voltages, except the tolerance reduces from +/-25% of Vcc {<3V} to +/-15% of Vcc{>3}  This tolerance is due to temperature and process variation.

Keep in mind that the smaller the difference between the "actual" threshold and your input is your immunity to noise and it will work if there is low noise. Thus 45+15% = 60%* 5V=3V is guaranteed.  What is not guaranteed, is the accuracy of your 5V regulator which if say 10% high will increase the threshold 10% above  3V or 3.3V.   So then 3.1 would not be guaranteed. So ensure accuracy of 5 V is below 5.04 minus your noise immunity requirements.


message:
Servo won't stop rotating

I have an Arduino Uno R3 board and after some time not in use it seems to have corrupted. My code is below, basically I want to rotate a servo 90 degrees every 12 hours but as soon as I plug it in the servo starts rotating non-stop. Have tried multiple delay steps and shortening and lengthening the write but the same effect happens.

    #include <Servo.h>

    Servo myservo;

    void setup {
      myservo.attach(10);
    }

    void loop() {
      myservo.write(90);
      delay(3600000);
    }

body:
I suppose you are using a continuous servo otherwise you wouldn't be able to make it turn 90° more than twice (a normal servo has a varying angle of only 180°).

Now if you are using a continuous servo, you have to be aware that the value you pass to `myservo.write()` does not represent an angle anymore!

With a continuous servo, the value passed to `myservo.write()` now means a speed of rotation where, but the range of acceptable values is the same as for a normal servo, i.e. `[0; 180]`:

- `0` means max speed clockwise
- `90` means no motion
- `180` means max speed counter-clockwise

Now if you want to turn the servo exactly 90°, then you must know the max speed of the servo, and from that, compute the time during which you must let it turn:

    // Start turning clockwise
    myservo.write(0);
    // Go on turning for the right duration
    delay(TURN_TIME);
    // Stop turning
    myservo.write(90);

The problem here is to compute `TURN_TIME`. For this, you must check the datasheet of your servo.

On my own servo, a [Feetech Micro 1.3kg Continuous Rotation Servo FS90R][1], the max speed is:

- 0.12s/60° when powered with 4.8V
- 0.10s/60° when powered with 6V

However, with the Arduino UNO, the supplied voltage should be **exactly 5V, neither 4.8V, nor 6V**.

If we take a linear approximation, then we can apply the following formula to find out the speed `T` (in **s/60°**):

    T = (0.12 - 0.10) * (V - 4.8) / (4.8 - 6.0) + 0.12

Hence, for 5V, we can take it for granted that the max speed should be:

    T = (0.12 - 0.10) * (5.0 - 4.8) / (4.8 - 6.0) + 0.12 = 0.116667

Since we need 90°, this means we must run the servo at its max speed during:

    T' = T * 1.5 = 0.175s

Hence we now have the following program:

    #include <Servo.h>

    #define TURN_TIME 175

    Servo myservo;

    void setup {
        myservo.attach(10);
        // Initially the servo must be stopped
        myservo.write(90);
    }

    void loop() {
        // Start turning clockwise
        myservo.write(0);
        // Go on turning for the right duration
        delay(TURN_TIME);
        // Stop turning
        myservo.write(90);

        // Wait for 12h
        delay(12 * 3600 * 1000);
    }

Of course, you will need some experiments to find the **exact** right values; you may also find out that the servo may be sensitive to noise and even when it should not move (value = `90`), it does move (not fast, but still it moves).

  [1]: http://www.feetechrc.com/product/analog-servo/micro-1-3kg-cm-360-degree-continuous-rotation-servo-fs90r/


body:
That was useful.
I was getting the same rotation thing when I had servos at 90. What I did to stop that was use the detach command. Using the Particle Photon with a continuous servo attached.

    bool state = LOW;

    Servo servo1;
    Servo servo2;// create servo object to control a servo
                    // a maximum of eight servo objects can be created

    int pos = 90;    // variable to store the servo position

    void setup()
    {
      servo1.attach(D0);
      servo2.attach(D1);
      Spark.function("test", testFunction);
      servo1.attach(10);
      servo1.write(90);
      servo2.attach(10);
      servo2.write(90);
    }

    void loop()
    {
        servo2.detach(), servo1.detach();
        delay (25);
        servo2.attach(D0), servo1.attach(D1);
        delay (25);
        servo1.write(0), servo2.write(180);
        delay (1000);
        servo2.write(180), servo1.write(0);
        delay (1000);
        //I did this to make the servo not move when it is at 90.
        servo2.detach(), servo1.detach();
        delay (25);
        servo1.write(90), servo2.write(90);
        delay (1000);
        //end
        //You must attach the servos again to make them move again.
        servo2.attach(D0), servo1.attach(D1);
        delay (25);
        //end
        servo1.write(180), servo2.write(0);
        delay (1000);
        servo2.write(180), servo1.write(100);
        delay (1000);

    }

    int testFunction(String args) {

        return 200; // This is checked in the web app controller for validation
    }


message:
RFID/NFC (13.56 MHz), is it possible to send raw bytes and receive response?

I'm trying to implement a card reader (i.e. credit cards) for shopping purposes, and AFAIK those cards are ISO 14443-A compliant (Mifare Classic 1K). I already made an Android app that can send custom APDU to read specific sectors by using raw SendBytes().

Since I need to build a circuit with a custom antenna, I chose Arduino-uno with a NFC module (was thinking about StrongLink SL013), I wanted to know if it's possible to send raw bytes and receive the response from the tag. I only found some higher-level implementation (readSector, writeSector and so on).

body:
RFID protocols require either passive or active tags.  Depending on which you use, either the tag or reader regularly transmits pulses.  Check www.rfidreader.com for more info.  https://www.rfidjournal.com provides valuable resources as well.

Many companies invest heavily in developing RFID technology.  You would be well advised not to reinvent wheels without reeeeally deeeeeep pockets.


body:
This would differ per device/reader.
Currently, I'm in a project with a TRF7970a RFID reader. I've seen it it's datasheet that it does have options to send RAW values as it does not support every protocol (NXP has patent on one?) thus the chip doesn,t parse it, but can send it to the mcu completely.
In short, yes this is possible.
But using a reader that is compliant with your protocol might supress your development cost/time


message:
XBee, external libraries and passing structures as arguments

I have very weird problem with a library I am creating. The library will be used to communicate between Arduino modules using XBee Series 1 modules. Library is very simple wrapper library around Arduino XBee library.

I have one function that reads received packet and sends it back. At the moment it is implemented as a simple "echo" service - the function just displays the data received and sends it back to per-defined address.

At the moment I have three versions of this function, out of which one is not working.

 1. A function taking no arguments: void processPacket()
 2. A function taking structure as a value as an argument: void processPacket(valuesStruct valuesStructData) - THIS VERSION OF THE FUNCTION IS NOT WORKING!
 3. A function taking pointer to the structure as an argument: void processPacket(valuesStruct* valuesStructData)

At this moment I noticed strange behavior in the 2nd version of the function. I do nothing with the passed argument - the content of all three functions is **the same.** In 2nd case the function reads wrong values from received XBee packet. In the 1st and 3rd case the function performs correctly.

Code:

**ExampleLib.h**

    #ifndef ExampleLib_h
    #define ExampleLib_h

    #include "Arduino.h"
    #include <XBee.h>

    #define ADDRESS_BROADCAST 0xffff
    #define ADDRESS_PC 0x3333

    typedef struct
      {
        int valA;
        int valB;
        int valC;
      } valuesStruct;

    class ExampleLib
    {
    public:
        ExampleLib();
        void setSerial(Stream &serial);
        boolean tryReceivePacket();
        void processPacket();
        // THIS FUNCTION IS NOT WORKING!
        void processPacket(valuesStruct valuesStructData);
        void processPacket(valuesStruct* valuesStructData);
    private:
        XBee xbee;
        Rx16Response rx16;
    };

    #endif

**ExampleLib.cpp**

The value read in line `byte* packetData = rx16.getData();` is wrong when we trigger `processPacket(valuesStruct valuesStructData)` function. In other cases the behavior is correct.

    #include "Arduino.h"
    #include <XBee.h>
    #include "ExampleLib.h"

    ExampleLib::ExampleLib()
    {
     xbee = XBee();
     rx16 = Rx16Response();
    }

    void ExampleLib::setSerial(Stream &serial)
    {
     xbee.setSerial(serial);
    }

    boolean ExampleLib::tryReceivePacket()
    {
     xbee.readPacket();

      if (xbee.getResponse().isAvailable()) {
        // got something

        if (xbee.getResponse().getApiId() == RX_16_RESPONSE) {
          // got a rx packet

          xbee.getResponse().getRx16Response(rx16);
          return true;
        }
        else {
          return false;
        }
      }
      else if (xbee.getResponse().isError()) {
        //nss.print("Error reading packet.  Error code: ");
        //nss.println(xbee.getResponse().getErrorCode());
        // or flash error led
        return false;
      }

      return false;
    }
    void ExampleLib::processPacket()
    {
      byte* packetData = rx16.getData();
      byte dataLength = rx16.getDataLength();
      Serial.print("START L:");
      Serial.println(dataLength);
      for (int i = 0; i < dataLength; i++) {
        Serial.print(packetData[i]);
     Serial.print(" - ");
      }
      Serial.println("END");

      //16-bit addressing: Enter address of remote XBee, typically the coordinator
      Tx16Request tx = Tx16Request(ADDRESS_PC, packetData, sizeof(packetData));
      xbee.send(tx);
    }

    void ExampleLib::processPacket(valuesStruct valuesStructData)
    {
      processPacket();
    }

    void ExampleLib::processPacket(valuesStruct* valuesStructData)
    {
      processPacket();
    }

**Arduino sketch**

    #include <XBee.h>
    #include <ExampleLib.h>

    ExampleLib exampleLibObj = ExampleLib();

    void setup()
    {
      Serial.begin(9600);
      exampleLibObj.setSerial(Serial);
    }

    void loop()
    {

      boolean isPacketReceived = exampleLibObj.tryReceivePacket();

      if (isPacketReceived) {
        // leave only one section, the rest should be commented

        //Section 1: working
        exampleLibObj.processPacket();

        //Section 2: not working
    //    valuesStruct test;
    //    test.valA = 0;
    //    test.valB = 0;
    //    test.valC = 0;
    //    exampleLibObj.processPacket(test);

        //Section 3: working
    //  valuesStruct* test;
    //  test->valA = 0;
    //  test->valB = 0;
    //  test->valC = 0;
    //  exampleLibObj.processPacket(test);
      }
    }

I am really puzzled why in this one case function is performing differently. Looking forward to any suggestions to that issue.

Thanks!

body: If the second isn't working, it may be best to use the other 2. Especially on the Arduino with limited RAM, you will not have enough if you pass a full struct to a function. Passing a pointer is less memory-intensive, and if it works, use it!


message:
Set up an Arduino Cellular Shield SM5100B

I'm trying to set up an Arduino Cellular Shield SM5100B to send SMS.

My setup is:

- Arduino UNO R2
- SM5100B
- "Movistar" SIM Card (Chile)

I've uploaded a code similar to the one described [here][1], but when communication is supposed to star it cannot find a network. I suspect the problem is I haven't setup correctly the GSM band. But when I issue the command (AT+SBAND=7, same as in the US), it doesn't respond. How can I check in what band I'm on? And change the band?

  [1]: http://www.instructables.com/id/Arduino-Cellular-Shield-Tutorial/?lang=en

body:
    /*
     Band Management

     This sketch, for the Arduino GSM shield, checks the band
     currently configured in the modem and allows you to change
     it.

     Please check http://www.worldtimezone.com/gsm.html
     Usual configurations:
     Europe, Africa, Middle East: E-GSM(900)+DCS(1800)
     USA, Canada, South America: GSM(850)+PCS(1900)
     Mexico: PCS(1900)
     Brazil: GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

     Circuit:
     * GSM shield

     created 12 June 2012
     by Javier Zorzano, Scott Fitzgerald

     This example is in the public domain.
     */
     // libraries
     #include <GSM.h>

     // initialize the library instance
     GSMBand band;

     void setup()
     {
       // initialize serial communications and wait for port to open:
       Serial.begin(9600);
       while (!Serial) {
         ; // wait for serial port to connect. Needed for Leonardo only
       }

       // Beginning the band manager restarts the modem
       Serial.println("Restarting modem...");
       band.begin();
       Serial.println("Modem restarted.");

     };

     void loop()
     {
       // Get current band
       String bandName = band.getBand(); // Get and print band name
       Serial.print("Current band:");
       Serial.println(bandName);
       Serial.println("Want to change the band you’re on?");
       String newBandName;
       newBandName = askUser();
       // Tell the user what we are about to do…
       Serial.print("\nConfiguring band ");
       Serial.println(newBandName);
       // Change the band
       boolean operationSuccess;
       operationSuccess = band.setBand(newBandName);
       // Tell the user if the operation was OK
       if(operationSuccess)
       {
         Serial.println("Success");
       }
       else
       {
         Serial.println("Error while changing band");
       }

       if(operationSuccess)
       {
         while(true);
       }
     }

     // This function offers the user different options
     // through the Serial interface
     // The user selects one
     String askUser()
     {
       String newBand;
       Serial.println("Select band:");
       // Print the different options
       Serial.println("1 : E-GSM(900)");
       Serial.println("2 : DCS(1800)");
       Serial.println("3 : PCS(1900)");
       Serial.println("4 : E-GSM(900)+DCS(1800) ex: Europe");
       Serial.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am.");
       Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)");

       // Empty the incoming buffer
       while(Serial.available())
       Serial.read();

       // Wait for an answer, just look at the first character
       while(!Serial.available());
       char c= Serial.read();
       if(c=='1')
         newBand=GSM_MODE_EGSM;
       else if(c=='2')
         newBand=GSM_MODE_DCS;
       else if(c=='3')
         newBand=GSM_MODE_PCS;
       else if(c=='4')
         newBand=GSM_MODE_EGSM_DCS;
       else if(c=='5')
         newBand=GSM_MODE_GSM850_PCS;
       else if(c=='6')
         newBand=GSM_MODE_GSM850_EGSM_DCS_PCS;
       else
         newBand="GSM_MODE_UNDEFINED";
       return newBand;
     }


message:
How do I use RFID-RC522 with an Arduino?

I am working on a project for my local Makerspace, we have limited budget so I was hoping to use the RFID-RC522 el'cheap'o RFID/NFC readers on eBay, I received a couple of SPI based boards, they work, however the code examples for them are limited.

I have found several different libraries and settled on this one: https://github.com/ljos/MFRC522

The trouble is that all the code available online seem to spawn from some Chinese guys Python code that people have translated, and hacked into an Arduino library.

The code works, but Mifare cards are meant to have 4, 7 or 10 byte UIDs and the example/library is returning a 5 byte serial number.

There is no documentation and the [NXP datasheet][1] is incomprehensible... Additionally it seems to work with most cards, but it doesn't work with Mastercard PayWave cards which conform to the ISO 14443 standard. The more expensive RDM880 reader which is based on the MFRC500 works fine and has a nice library but the cost makes the implementation impossible.

So, can someone help me to get this NXP MFRC522 based unit reading the UID from all ISO 14443 cards.

    #include <SPI.h>
    #include <MFRC522.h>

    #define RFID_SS  10
    #define RFID_RST 5

    MFRC522 rfid( RFID_SS, RFID_RST );

    void setup() {
      SPI.begin();
      Serial.begin(115200);
      rfid.begin();
    }

    void loop() {
      byte data[MAX_LEN];
      byte uid[5];

      if ( rfid.requestTag( MF1_REQIDL, data ) == MI_OK ) {
        if ( rfid.antiCollision( data ) == MI_OK ) {
          memcpy( uid, data, 5 );
          for ( int i = 0; i < 5; i++ ) {
            Serial.print( uid[i], HEX );
            Serial.print( ' ' );
          }
          Serial.println();
        }
      }
    }

  [1]: http://www.nxp.com/documents/data_sheet/MFRC500.pdf

body:
Sorry, but I must disagree with your *'NXP datasheet is incomprehensible'*. From the FIRST PAGE of the MFRC522 datasheet:

***'Remark: The MFRC522 supports all variants of the MIFARE Mini, MIFARE 1K,
MIFARE 4K, MIFARE Ultralight, MIFARE DESFire EV1 and MIFARE Plus RF
identification protocols'***

[**Here**](http://en.wikipedia.org/wiki/Radio-frequency_identification) it says the MFRC522 covers just a part of ISO/IEC 14443. The following are missing fron the NXP RC522:

***MIFARE DESFire EV1** (includes AES encryption)

**MIFARE DESFire EV2** (includes MIsmartApp, Transaction MAC, Unlimited Applications
MIFARE Plus drop-in replacement for MIFARE Classic with certified security level (AES 128 based))

***MIFARE SAM AV2*** (secure access module that provides the secure storage of cryptographic keys and cryptographic functions)*

These are probably the ones used in bank cards. Again, from the FIRST PAGE of the MFRC500 datasheet:

***'All protocol layers of the ISO/IEC 14443 A are supported.'***

You'll have to plow through all the different MIFARE / ISO/IEC 14443 specs to find out how many ID bytes there are for the different types (I suspect diferent types return a different quantity of bytes).

So, basically, you're screwed. Spring for the expensive MFRC500-based reader. I assume that with the higher cost you also get a high-class API, documentation and examples or even (gasp!) tech support.

Cheers


body:
The MFRC522::requestTag() returns the card type in the first two bytes of the 2nd parameter (_data_ in your example above).  You will need to look at this value to determine which sort of card it is.  Use this information to print out the required _N_ bytes of ID.

At a pinch, you could dump out the full 16 bytes (MAX_LEN), and test them with your various card types to see which bytes are changing in a deterministic manner, thus allowing you to determine the correct length of the ID.

And in case it saves you some time, if you call that library's self-test functions - getFirmwareVersion() and digitalSelfTestPass(); it's necessary to call MFRC522::begin() again, otherwise it's not possible to read RFID IDs (at the time of writing of course.)


body:
Try using the most popular one.

https://github.com/miguelbalboa/rfid

This is working for me. It returns the uID as what you desire. Just remove the other functions just the getting of the uid from its example.


message:
Default value of global variables is not set

I am tracking a bug in the [Marlin][1] source code.

**Background**

Just for those who is not familiar with Reprap 3D printer and G-code: Marlin is firmware that controls a [RepRap][2] 3D printer. It receives G-code from a host computer (or read from SD card). Here the important thing is that if you send the "M114" command, it would report information about axis positions. Here, I extended this command to make it print some internal variable as well.

**The Problem**

In Marlin.ino file there is a line that says:

    volatile int extrudemultiply=100; //100->1 200->2

However my RepRap keeps extruding (and worse, ejecting back) a huge amount of filament. So I added some debug output for `M114` command to output this value. It turns out this value is not the default value, 100, but something like 12374.

I thought somewhere inside the `setup()` function this value might be changed. So I defined another variable,

    volatile int orig_extrudemultiply = 100;

And then at the first line of `setup()` function, I added the following line.

    orig_extrudemultiply = extrudemultiply;

Finally, I output this value for the `M114` command. Still, it is not 100. So it looks like the default value is not effective.

**The Question**

Although I have experience in C programming, I am new to Arduino development. How is a global variable being initialized in Arduino? In my case, what is the proper way to initialize this value?

**Versioning**

I originally posted the official [Marlin][3] link for the reference. However,
the version I actually use is [this fork][4] from the RepRap Pro team. I was just following the [Melzi][5] entry of the RepRap wiki, because my board is Melzi. I am not sure whether the latest version of Marlin works for my board.

**Further details**

As the commenter said, the first thing I thought of was memory corruption. So I wanted to narrow the problem down. Since that value is configurable through `M302 SXXX` command, I tested this command, and it works without difficulty. This means there is nothing in the `loop` function or the [ISRs][6] can affect this value when it is running stably. So I consider the problem must be in the `setup` function or earlier.

Further tests shows that setting this value at the end of `setup` or even at the beginning of `setup` still works fine. This means the `setup` function may not be the problematic one. The test in "The Problem" session was the last step, which, in my opinion, means the course of the problem must being run before entering `setup`.

**UPDATE**

Further examination shows that although it looks like it works when I set the default value in the first line of `setup()`, but that it is just luckily being 100. So once I add more padding variables it stops working until I move the default setting after the following line in `setup()`:

    EEPROM_RetrieveSettings(); // Loads data from EEPROM if available

However, since I `grep`ed for `extrudemultiply` before any test, and I didn't figure out this function, this function should not change this value. I guess there is some data overflow inside this function, so the value was changed expectationally.

I got to figure out what is wrong in this function.

  [1]: https://github.com/reprappro/Marlin
  [2]: https://en.wikipedia.org/wiki/RepRap_Project
  [3]: https://github.com/ErikZalm/Marlin
  [4]: https://github.com/reprappro/Marlin
  [5]: http://reprap.org/wiki/Melzi#Melzi_Arduino_Pin_Numbers
  [6]: https://en.wikipedia.org/wiki/Interrupt_handler

body:
This variable is declared `volatile` which is generally meaning that it can be modified by an **Interrupt Service Routine** (**ISR**).

So it is perfectly possible that this ISR gets called before your `setup()` function gets called and then it may modify this variable.

In C and C++, variables defined as `type variable = xxx;` are guaranteed to be initialized before any of your code starts to run.

So this means you must look for the root of the problem somewhere else.

Don't forget that it is perfectly possible that some code gets run before `setup()` is called.

You may try to search for the code that runs before `setup()`; unfortunately it can be hard to find out this code:

Indeed, in C++, there are a lot of possibilities for code to execute even before the `main()` function gets called; for instance, declaring an instance of a class as a global variable, will call the class **constructor** before `main()`.

So you would have to **find out all class instances declared as global variables** in all source files, and then check the class constructor that gets called for each instance.

Another way could be to check the assembly produced for your program and find all calls occurring be fore `main()`, but it can be harder if you can't read assembly.


body:
The problem of this version of Marlin can be shown in the following piece of code (which is inside `EEPROM_RetrieveSettings` function):

      for (short i=0;i<4;i++)
      {
        axis_steps_per_unit[i]=tmp1[i];
        max_feedrate[i]=tmp2[i];
        max_acceleration_units_per_sq_second[i]=tmp3[i];
        max_length[i]=tmp4[i];
      }

Here `max_length` is an array of 3 elements, not 4 (the X,Y and Z axes have a max length to avoid hitting the edge, but the extrude axis does not have such a limit - you should be able to extrude as many filament as you can supply), so the last statement in the loop overrides other variable(s).

The solution is

      for (short i=0;i<4;i++)
      {
        axis_steps_per_unit[i]=tmp1[i];
        max_feedrate[i]=tmp2[i];
        max_acceleration_units_per_sq_second[i]=tmp3[i];
        if(i<3)
            max_length[i]=tmp4[i];
      }

Or

      for (short i=0;i<4;i++)
      {
        axis_steps_per_unit[i]=tmp1[i];
        max_feedrate[i]=tmp2[i];
        max_acceleration_units_per_sq_second[i]=tmp3[i];
        if(i < sizeof(tmp4)/sizeof(tmp4[0]))
            max_length[i]=tmp4[i];
      }

Greate thanks to the answer writer and commenter. Without your help I couldn't follow the right track.


message:
Which motor (type) to use for an arduino controlled magnetic stirrer?

I am in the process of building my own [sous vide machine][1] and like to replace the pump typically found in most commercial machines with a [magnetic stirrer unit][2]. I figured the easiest way would be to use a motor to spin a permanent magnet (instead of creating a strong rotating magnetic field electrically). I first started experimenting with some 12V DC fans leftover from an old computer. By either lowering the input voltage or via PWM I was able to obtain appropriate rotational speed (don't ask me about exact speeds, I guess around 300rpm or so). With the project maturing I am not sure which motor (type and/or exact model) to use. I hoped some of you might point me in the right direction for the type of motor or even better, could suggest a specific model. I considered stepper motors or continuous  servo motors. My criteria for the motor are:

 -  easy to control rotational speed between 0 and around 500 or so rpm (for ramp up and variation of speed to increase turbulent flow)
 - ability to rotate both clockwise and counter clockwise
 - enough torque at all speeds to spin a disk with magnets attached (weight and inertia probably negligible, the to be used alnico magnets create a field strong enough to lift 0,4kg each)
 - small axial dimensions
 - reasonably priced and long lasting
 - quiet

The following picture shows a commercial magnetic stirrer found in your average laboratory. The blurry white object in the glass beaker is the the so called stir bar or "fish", a PTFE coated permanent magnet. It spins due to the rotating magnetic field created by the actual device underneath the beaker.
![Photo of a commercial magnetic stirrer used in laboratories][3]

  [1]: http://en.wikipedia.org/wiki/Sous-vide
  [2]: http://en.wikipedia.org/wiki/Magnetic_stirrer
  [3]: https://i.stack.imgur.com/ysulU.jpg

body:
I'd personally recommend a continuous rotation servo or a brushed DC motor. Personally, for this kind of load, I think it would be easier and cheaper to go with the brushed DC motor. You have to remember a continuous rotation servo is a DC motor with some circuitry so you can send pulses to it to control the speed (although it's not directly proportional to the signal you send).

A servo is the only other option besides a brushless motor; both require a little more circuitry than the brushed motor/continuous servo. The additionally cost more. [This blog post covers the differences between brushed and brushless motors](http://quantumdevices.wordpress.com/2010/08/27/brushless-motors-vs-brush-motors-whats-the-difference/).

For driving a continuous, you hook it up to power [depends on your servo voltage], ground, and another Arduino pin and use the [servo library](http://arduino.cc/en/reference/servo) to send a signal as a degree (90 = no speed, 180 = full speed forward, 0 = full speed backward).

A brushed you would need a h-bridge that allows you to either send voltage, send no voltage, or send reverse voltage (for backward). [This chip (~$5)](http://www.pololu.com/product/2130) does that for two motors and allows PWM for different speeds. It also includes a brake function, although that doesn't seem necessary for you. It can handle up to a "2.4 A continuous (4 A peak)." I talk about this in [this answer of mine](https://arduino.stackexchange.com/questions/1314/how-can-i-connect-the-tamiya-double-gearbox-to-ardunio-uno/1315#1315).

Quick note, if you want to control the *exact* RPM of the device and not just manually adjust it to a good rate, you'll need some sort of a rotary encoder or similar. A reed switch (sends current depending on magnetic fields) would work perfectly for this purpose, just mount it below the magnets and figure out the degrees rotated by the motor for each "pulse."


body:
If you need to rotate huge loads, a permanent magnet coupled to the axis of a brushless DC motor, driven by an electronic speed controller (used for model aircrafts, multicopters, etc.) could be an option. This is the mechanical principle used in standard magnetic stirrers used in the lab, particularly when the stirrer has an additional heating.

Small (and flat) magnetic stirrers without heating, similar to the one in your image, however often have no (rotating) mechanical parts at all, but use a set of coils periodically powered in sequence. Here, the only mechanically rotating part is the stirring bar itself. A commerically available model would be [this one](http://www.ika.de/owa/ika/catalog.product_detail?iProduct=3907500&iCS=1&iProductgroup=188&iSubgroup=1).


message:
Larger NFC antenna?

Goal: I would like to be able to transfer some information to an Arduino Uno board via an NFC shield/antenna. The situation requires that the NFC tag may potentially hit anywhere within a circular area about a 12 inches in diameter.

Is it possible to increase the size of an NFC antenna? Possibly creating a loop antenna whereby the tag could be read from anywhere inside the loop.

I was thinking maybe if that isn't possible, it might be better to create an antenna array spanning the size of the area needed. Though I may have problems with overlap or double reads this way.

Has anyone attempted this before?

Note: I am not worried about increasing the z distance from the plane, just the x/y range. In fact, I still want the z distance to be very short as to not interfere with other antennas nearby.

body:
In general the size and geometry of the antenna is directly related to the carrier frequency. The antenna is tuned to the output signal of the transmitter/receiver. If you change an optimized antenna, it is no longer optimized and its performance will drop. So you can't keep extending an antenna, trying to improve its range.

The important question to be asked is if the existing antenna is already optimally sized for the transmitter/receiver. With these small things transmitter/receiver and antenna are usually closely matched. Even if the antenna is smaller than expected by math, the transmitter/receiver connected to it may be compensated for that.

With a receiver or a **low*** power transmitter, there is no harm in testing another antenna, but you'll probably won't improve performance much.

---

*) Notice that a high power transmitter can blow its output stage when connected to an unmatched load/antenna, but that is unlikely with NFC.


message:
Understanding the relationship of Pulse and Stepper RPM

This may be a better question for [the Physics StackExchange][1] so tell me if I should move the question.

I have a pretty simple script that I'm using to control the RPM of my stepper motor:

    void loop(){
      digitalWrite(PIN, HIGH);
      delayMicroseconds(wait);
      digitalWrite(PIN, LOW);
    }

as you can see it's just producing a pretty standard pulse, I have my Arduino connected to a driver that manages the motor. The `wait` variable comes from a second order equation I derived from measuring the RPM with a Tachometer and tweaking the value.

    // From data RPM = 31729/x + 17.327 thus x = 31729/(RPM-17.527)
    wait = M/(RPM-C);

It works pretty well, I get readings consistently within only 1 - 2 rotations off. But the slope and intercept seem completely arbitrary to me. Is there a chance it has to do with the clock speed of the Arduino? I'm using an Uno and from playing around with the numbers I can't seem to find a relationship. From what I can tell, the driver looks hardwired so I don't think it has much to do with the equation.

Any idea what these values, the slope/intercept mean?

Equation: `RPM=31729/wait + 17.327` M:`31729` and C:`17.327`

  [1]: https://physics.stackexchange.com/

body:
The real answer to this question requires understanding exactly what hardware you have. The formula, assuming one step per pulse, is that the delay should be:

wait = (MicroSecondsPerMinute)*(1/RPM)*(1/PulsesPerRevolution) - overhead

where overhead is the extra time it takes to run digitalWrite twice and loop. It is small, but if it were zero your code would not work because the amount of time your signal is LOW would be zero as well.

Your numbers suggest Pulses Per Revolution is around 1891. This will be the product of how many steps per revolution the motor is wired for and how many bits of microstepping the driver is doing. A 225 step motor with 3 bit microstepping (8 fractional steps per "true" step) would have PPR of 1800 for example. Your number does not precisely match any common setups, but is exactly in the range expected, with 1600 and 2000 being normal for small steppers.

Because of the "overhead" term, RPM as a function of wait should not be linear. Your constant value should be a function of RPM; in fact, when RPM gets much larger than the number of Microseconds per minute it should converge to being equal to RPM. In this case your RPM is so low that approximating it to 17 is probably valid and all error too small to notice. It could be causing some of the oddness of your PPR value though.


body:
one pulse equals one step of stepper and rpm is how many rotation stepper makes in one minute.
Try to understand the stepper.h library and Accelstepper library


message:
Is it possible to transmit Longitude and Latitude via RF433MHz?

I want to make a drone project, and to that I will use arduino as the platform. My plane is to use a Play Station controller to control the Drone in the air. In addition to that I want to connect a GPS-module. My question goes, is it possible to transmit the longitude and latitude from the GPS via the RF 433MHz to the receiver? When received the longitude and latitude how can I transmit them further to the Smartphone and display the data on google maps? I suggest it could be possible through the Xbee, but I am not sure.

I would like if someone can confirm my idea, if not bring me a better way to do that.

In the image below, you can see the diagram of my design.

![Image][1]

  [1]: https://i.stack.imgur.com/qorvn.png

body: If you are using Xbee modules in your project, why add 433MHz RF, just for the sole purpose of transmitting the location?  With the 433Mhz, you will have to implement error-correction yourself.


body:
Your design suffers several redundancies that should be fixed. First of all, you have an Xbee (only one, not a pair) *and* a a 433 MHz transmitter/receiver combo. **Why not just add another Xbee to the drone and remove the RF combo?** That would save a little battery life for the receiver end, and a lot of your time. You'll also get two way communication with error checking. Although an Xbee would increase your project size a *little*, if you manually wired the Xbee instead of a shield (3.3V), it would save a lot of space.

As some people point out, Bluetooth is a viable option that's fairly small and low cost. However, it would suffer shorter ranges and it would need a special configuration on the host side for a BT stack.


message:
Multiple definition of '__vector_36' (intterupts)

I'm having some conflicts between the core `HardwareSerial.cpp` and an external DMX library.

For DMX I'm using the [Four Universes DMX 512 Library](http://www.deskontrol.net/blog/arduino-four-universes-dmx-512-library/). Using the library standalone, it all works perfectly. But when combining it with other libraries, I'm getting the error:

    core.a(HardwareSerial.cpp.o): In function '__vector_36':
    C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino/HardwareSerial.cpp:147: multiple definition of '__vector_36'
    Dmx\lib_dmx.cpp.o:C:\Program Files (x86)\Arduino\libraries\Dmx/lib_dmx.cpp:206: first defined here

The DMX library uses the UART hardware to generate the DMX signals. It supports four universes on the Arduino Mega since that has four UART hardware parts. Now, I'd like to only use the second hardware part, so the UART1. In the DMX library this is easily adjusted in the .h-file, by commenting out the non-used serial ports.

The line from `lib_dmx.cpp` that is conflicting is this line:

    #if defined(USE_UART1)
    ISR (SIG_USART1_RECV)
    {
      ArduinoDmx1.Process_ISR_RX(1);
    }
    #endif

The line from `hardwareSerial.cpp` that is conflicting is in the ISR here:

    #if defined(USART1_RX_vect)
      void serialEvent1() __attribute__((weak));
      void serialEvent1() {}
      #define serialEvent1_implemented
      ISR(USART1_RX_vect)
      {
        if (bit_is_clear(UCSR1A, UPE1)) {
          unsigned char c = UDR1;
          store_char(c, &rx_buffer1);
        } else {
          unsigned char c = UDR1;
        };
      }
    #endif

I have been having issues with this for a very long time and don't have a solution at hand yet. It's also a but unclear to me how the interrupts on Arduinos are arranged. I've also included the .ino I'm using currently. I'm also using another Ethernet Library than the default, one that includes multicast UDP (found [here][1]).

**lib_dmx.h**

    > /***************************************************************************
    > *
    > * Title          : Arduino DMX512 library. 4 input/output universes.
    > * Version        : v 0.3 beta
    > * Last updated   : 07.07.2012
    > * Target         : Arduino mega 2560, Arduino mega 1280, Arduino nano (1 universe)
    > * Author         : Toni Merino - merino.toni at gmail.com
    > * Web            : www.deskontrol.net/blog
    > *
    > * Based on ATmega8515 Dmx library written by Hendrik Hoelscher, www.hoelscher-hi.de
    >
    > ;***************************************************************************/
    > #ifndef __INC_DMX_H
    > #define __INC_DMX_H
    >
    > #include <avr/io.h>
    > #include <stdint.h>
    > #include <avr/interrupt.h>
    > #include <util/delay.h>
    > #if ARDUINO >= 100   #include "Arduino.h"
    > #else    #include "WProgram.h"
    > #endif
    >
    > //#define        USE_INTERBYTE_DELAY     // rare cases of equipment
    > non full DMX-512 compliant, need this
    >
    > // *** comment UARTs not used *** //#define        USE_UART0
    > #define        USE_UART1 //#define        USE_UART2 //#define        USE_UART3
    >
    > // New DMX modes *** EXPERIMENTAL ***
    > #define        DMX512            (0)    // DMX-512 (250 kbaud - 512 channels) Standard USITT DMX-512
    > #define        DMX1024           (1)    // DMX-1024 (500 kbaud - 1024 channels) Completely non standard - TESTED ok
    > #define        DMX2048           (2)    // DMX-2048 (1000 kbaud - 2048 channels) called by manufacturers DMX1000K, DMX 4x or DMX 1M ???
    >
    > // DMX-512  (250 kbaud - 512 channels) Standard USITT DMX-512
    > #define        IBG_512           (10)                      // interbyte gap [us]
    > #define        DMX_512           ((F_CPU/(250000*8))-1)    // 250 kbaud
    > #define        BREAK_512         ( F_CPU/(100000*8))       // 90.9 kbaud
    >
    > // DMX-1024 (500 kbaud - 1024 channels) Completely non standard
    > #define        IBG_1024          (5)                       // interbyte gap [us]
    > #define        DMX_1024          ((F_CPU/(500000*8))-1)    // 500 kbaud
    > #define        BREAK_1024        ( F_CPU/(200000*8))       // 181.8 kbaud
    >
    > // DMX-2048 (1000 kbaud - 2048 channels) Non standard, but used by
    > manufacturers as DMX1000K or DMX-4x or DMX 1M ???
    > #define        IBG_2048          (2)                       // interbyte gap [us] + nop's to reach 2.5 uS
    > #define        DMX_2048          ((F_CPU/(1000000*8))-1)   // 1000 kbaud
    > #define        BREAK_2048        ( F_CPU/(400000*8))       // 363.6 kbaud
    >
    > // Inline assembly: do nothing for one clock cycle.
    > #define        nop()             __asm__ __volatile__("nop")
    >
    > #ifdef __cplusplus extern "C" {
    > #endif   #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    >     #if defined(USE_UART0)
    >       void SIG_USART0_RECV  (void) __attribute__((__always_inline__));
    >       void SIG_USART0_TRANS (void) __attribute__((__always_inline__));
    >     #endif
    >     #if defined(USE_UART1)
    >       void SIG_USART1_RECV  (void) __attribute__((__always_inline__));
    >       void SIG_USART1_TRANS (void) __attribute__((__always_inline__));
    >     #endif
    >     #if defined(USE_UART2)
    >       void SIG_USART2_RECV  (void) __attribute__((__always_inline__));
    >       void SIG_USART2_TRANS (void) __attribute__((__always_inline__));
    >     #endif
    >     #if defined(USE_UART3)
    >       void SIG_USART3_RECV  (void) __attribute__((__always_inline__));
    >       void SIG_USART3_TRANS (void) __attribute__((__always_inline__));
    >     #endif   #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    >     #if defined(USE_UART0)
    >       void USART_RX_vect    (void) __attribute__((__always_inline__));
    >       void USART_TX_vect    (void) __attribute__((__always_inline__));
    >     #endif   #endif
    > #ifdef __cplusplus };
    > #endif
    >
    > class CArduinoDmx  {    #if defined(__AVR_ATmega1280__) ||
    > defined(__AVR_ATmega2560__)
    >     #if defined(USE_UART0)
    >       friend void SIG_USART0_RECV  (void);
    >       friend void SIG_USART0_TRANS (void);
    >     #endif
    >     #if defined(USE_UART1)
    >       friend void SIG_USART1_RECV  (void);
    >       friend void SIG_USART1_TRANS (void);
    >     #endif
    >     #if defined(USE_UART2)
    >       friend void SIG_USART2_RECV  (void);
    >       friend void SIG_USART2_TRANS (void);
    >     #endif
    >     #if defined(USE_UART3)
    >       friend void SIG_USART3_RECV  (void);
    >       friend void SIG_USART3_TRANS (void);
    >     #endif   #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    >     #if defined(USE_UART0)
    >       friend void USART_RX_vect    (void);
    >       friend void USART_TX_vect    (void);
    >     #endif   #endif    public:    enum {IDLE, BREAK, STARTB, STARTADR};     // RX DMX states    enum {TXBREAK, TXSTARTB, TXDATA};
    > // TX DMX states
    >       volatile uint8_t    *RxBuffer;            // array of RX DMX values    volatile uint8_t    *TxBuffer;            // array of TX DMX
    > values
    >
    > private:    uint8_t     gRxState;    uint8_t    *gRxPnt;    uint8_t
    > IndicatorCount;    uint8_t     USARTstate;      uint8_t     RxByte;
    > uint8_t     RxState;    uint8_t     mUART;    uint8_t     gTxState;
    > uint16_t    RxCount;    uint16_t    gCurTxCh;      uint16_t
    > rx_channels;                  // rx channels number    uint16_t
    > tx_channels;                  // tx channels number    uint16_t
    > rx_address;                   // rx start address    uint16_t
    > tx_address;                   // tx start address    int8_t
    > rx_led;                       // rx indicator led pin    int8_t
    > tx_led;                       // tx indicator led pin    int8_t
    > control_pin;                  // max485 input/output selection pin
    > uint8_t     dmx_mode;                     // Standard USITT DMX512 =
    > 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K) = 2
    > uint8_t     speed_dmx;    uint8_t     speed_break;    uint16_t
    > CurTxCh;    uint8_t     TxState;    uint8_t    *RxPnt;
    >
    > #if defined(USE_INTERBYTE_DELAY)       void        delay_gap          ();
    > #endif
    >
    > public:    void        stop_dmx           ();    void        set_speed
    > (uint8_t mode);    void        set_control_pin    (int8_t  pin)
    > { control_pin     = pin;      }    void        init_rx
    > (uint8_t mode);  // Standard USITT DMX512 = 0, non standard DMX1024 =
    > 1, non standard DMX2048 (DMX1000K) = 2    void        set_rx_address
    > (uint16_t address)   { rx_address      = address;  }    void
    > set_rx_channels    (uint16_t channels)  { rx_channels     = channels;
    > }    void        init_tx            (uint8_t mode);  // Standard USITT
    > DMX512 = 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K)
    > = 2    void        set_tx_address     (uint16_t address)   { tx_address      = address;  }    void        set_tx_channels
    > (uint16_t channels)  { tx_channels     = channels; }
    >
    >    void        attachTXInterrupt  (void (*isr)(uint8_t uart))      {
    > TXisrCallback   = isr; }   // register the user TX callback    void
    > attachRXInterrupt  (void (*isr)(uint8_t uart))      { RXisrCallback
    > = isr; }   // register the user RX callback
    >        //void   Process_ISR_RX(uint8_t rx_isr_number);
    >
    >    void        (*TXisrCallback)   (uint8_t uart);    void
    > (*RXisrCallback)   (uint8_t uart);
    >
    >    inline void Process_ISR_RX     (uint8_t  rx_isr_number);    inline
    > void Process_ISR_TX     (uint8_t  tx_isr_number);    public:
    > CArduinoDmx                    (uint8_t uart)       { rx_address
    > = 1;
    >                                                          rx_channels     = 8;
    >                                                          tx_address      = 1;
    >                                                          tx_channels     = 8;
    >                                                          mUART           = uart; }   };
    >
    > #if defined(USE_UART0)   extern CArduinoDmx ArduinoDmx0;
    > #endif
    > #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)   #if defined(USE_UART1)
    >     extern CArduinoDmx ArduinoDmx1;   #endif   #if defined(USE_UART2)
    >     extern CArduinoDmx ArduinoDmx2;   #endif   #if defined(USE_UART3)
    >     extern CArduinoDmx ArduinoDmx3;   #endif
    > #endif
    >
    > #endif

**lib_dmx.cpp**

    /***************************************************************************
    *
    * Title          : Arduino DMX512 library. 4 input/output universes.
    * Version        : v 0.3 beta
    * Last updated   : 07.07.2012
    * Target         : Arduino mega 2560, Arduino mega 1280, Arduino nano (1 universe)
    * Author         : Toni Merino - merino.toni at gmail.com
    * Web            : www.deskontrol.net/blog
    *
    * Based on ATmega8515 Dmx library written by Hendrik Hoelscher, www.hoelscher-hi.de

    ;***************************************************************************/
    #include "lib_dmx.h"
    #include <SPI.h>

    #if defined(USE_UART0)
      CArduinoDmx ArduinoDmx0(0);
    #endif
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      #if defined(USE_UART1)
        CArduinoDmx ArduinoDmx1(1);
      #endif
      #if defined(USE_UART2)
        CArduinoDmx ArduinoDmx2(2);
      #endif
      #if defined(USE_UART3)
        CArduinoDmx ArduinoDmx3(3);
      #endif
    #endif

    // *************** DMX Transmision Initialisation ****************
    void CArduinoDmx::init_tx(uint8_t mode)
    {
      cli();          //disable interrupts
      stop_dmx();                         //stop uart
      dmx_mode = mode;
      set_speed(dmx_mode);

      if(control_pin != -1)
      {
        pinMode(control_pin,OUTPUT);        // max485 I/O control
        digitalWrite(control_pin, HIGH);    // set 485 as output
      }

      if(mUART == 0)
      {
        pinMode(1, OUTPUT);
        UBRR0H   = 0;
        UBRR0L   = speed_dmx;
        UCSR0A  |= (1<<U2X0);
        UCSR0C  |= (3<<UCSZ00)|(1<<USBS0);
        UCSR0B  |= (1<<TXEN0) |(1<<TXCIE0);
        UDR0     = 0;                 //start USART 0
      }
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      else if(mUART == 1)
      {
        pinMode(18, OUTPUT);
        UBRR1H   = 0;
        UBRR1L   = speed_dmx;
        UCSR1A  |= (1<<U2X1);
        UCSR1C  |= (3<<UCSZ10)|(1<<USBS1);
        UCSR1B  |= (1<<TXEN1) |(1<<TXCIE1);
        UDR1     = 0;                 //start USART 1
      }
      else if(mUART == 2)
      {
        pinMode(16, OUTPUT);
        UBRR2H   = 0;
        UBRR2L   = speed_dmx;
        UCSR2A  |= (1<<U2X2);
        UCSR2C  |= (3<<UCSZ20)|(1<<USBS2);
        UCSR2B  |= (1<<TXEN2) |(1<<TXCIE2);
        UDR2     = 0;                 //start USART 2
      }
      else if(mUART == 3)
      {
        pinMode(14, OUTPUT);
        UBRR3H   = 0;
        UBRR3L   = speed_dmx;
        UCSR3A  |= (1<<U2X3);
        UCSR3C  |= (3<<UCSZ30)|(1<<USBS3);
        UCSR3B  |= (1<<TXEN3) |(1<<TXCIE3);
        UDR3     = 0;                 //start USART 3
      }
    #endif

      gTxState = BREAK;                         // start with break
      TxBuffer = (uint8_t*)malloc(tx_channels);     // allocate mem for buffer
      memset((uint8_t*)TxBuffer, 0, tx_channels);   // fill buffer with 0's
      sei();          //enable interrupts
    }

    // ************************ DMX Stop ***************************
    void CArduinoDmx::stop_dmx()
    {
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      if(mUART == 0)
      {
        UCSR0B &= ~((1<<RXCIE0) | (1<<TXCIE0) | (1<<RXEN0) | (1<<TXEN0));
      }
      else if(mUART == 1)
      {
        UCSR1B &= ~((1<<RXCIE1) | (1<<TXCIE1) | (1<<RXEN1) | (1<<TXEN1));
      }
      else if(mUART == 2)
      {
        UCSR2B &= ~((1<<RXCIE2) | (1<<TXCIE2) | (1<<RXEN2) | (1<<TXEN2));
      }
      else if(mUART == 3)
      {
        UCSR3B &= ~((1<<RXCIE3) | (1<<TXCIE3) | (1<<RXEN3) | (1<<TXEN3));
      }
    #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
      if(mUART == 0)
      {
        UCSR0B &= ~((1<<RXCIE0) | (1<<TXCIE0) | (1<<RXEN0) | (1<<TXEN0));
      }
    #endif
    }

    // *************** DMX Reception Initialisation ****************
    void CArduinoDmx::init_rx(uint8_t mode)
    {
      cli();          //disable interrupts
      stop_dmx();
      dmx_mode = mode;
      set_speed(dmx_mode);

      if(control_pin != -1)
      {
        pinMode(control_pin,OUTPUT);        //max485 I/O control
        digitalWrite(control_pin, LOW);     //set 485 as input
      }

      if(mUART == 0)
      {
        pinMode(0, INPUT);
        UBRR0H   = 0;
        UBRR0L   = speed_dmx;
        UCSR0A  |= (1<<U2X0);
        UCSR0C  |= (3<<UCSZ00)|(1<<USBS0);
        UCSR0B  |= (1<<RXEN0) |(1<<RXCIE0);
      }
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      else if(mUART == 1)
      {
        pinMode(19, INPUT);
        UBRR1H   = 0;
        UBRR1L   = speed_dmx;
        UCSR1A  |= (1<<U2X1);
        UCSR1C  |= (3<<UCSZ10)|(1<<USBS1);
        UCSR1B  |= (1<<RXEN1) |(1<<RXCIE1);
      }
      else if(mUART == 2)
      {
        pinMode(17, INPUT);
        UBRR2H   = 0;
        UBRR2L   = speed_dmx;
        UCSR2A  |= (1<<U2X2);
        UCSR2C  |= (3<<UCSZ20)|(1<<USBS2);
        UCSR2B  |= (1<<RXEN2) |(1<<RXCIE2);
      }
      else if(mUART == 3)
      {
        pinMode(15, INPUT);
        UBRR3H   = 0;
        UBRR3L   = speed_dmx;
        UCSR3A  |= (1<<U2X3);
        UCSR3C  |= (3<<UCSZ30)|(1<<USBS3);
        UCSR3B  |= (1<<RXEN3) |(1<<RXCIE3);
      }
    #endif

      gRxState = IDLE;
      RxBuffer = (uint8_t*)malloc(rx_channels);   // allocate mem for buffer
      memset((uint8_t*)RxBuffer, 0, rx_channels); // fill buffer with 0's
      sei();          //enable interrupts
    }

    // *************** DMX Reception ISR ****************
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      #if defined(USE_UART0)
        ISR (SIG_USART0_RECV)
        {
          ArduinoDmx0.Process_ISR_RX(0);
        }
      #endif
      #if defined(USE_UART1)
        ISR (SIG_USART1_RECV)
        {
          ArduinoDmx1.Process_ISR_RX(1);
        }
      #endif
      #if defined(USE_UART2)
        ISR (SIG_USART2_RECV)
        {
          ArduinoDmx2.Process_ISR_RX(2);
        }
      #endif
      #if defined(USE_UART3)
        ISR (SIG_USART3_RECV)
        {
          ArduinoDmx3.Process_ISR_RX(3);
        }
      #endif
    #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
      #if defined(USE_UART0)
        ISR (USART_RX_vect)
        {
      ArduinoDmx0.Process_ISR_RX(0);
     }
      #endif
    #endif

    void CArduinoDmx::Process_ISR_RX(uint8_t rx_isr_number)
    {
      if(rx_isr_number == 0)
      {
        USARTstate = UCSR0A;            //get state
        RxByte     = UDR0;                //get data
        RxState    = gRxState;       //just get once from SRAM!!!
        if (USARTstate &(1<<FE0))         //check for break
        {
          UCSR0A  &= ~(1<<FE0);        //reset flag
          RxCount  = rx_address;      //reset frame counter
          gRxState = BREAK;
        }
      }
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)

      else if(rx_isr_number == 1)
      {
        USARTstate = UCSR1A;            //get state
        RxByte     = UDR1;                //get data
        RxState    = gRxState;       //just get once from SRAM!!!
        if (USARTstate &(1<<FE1))         //check for break
        {
          UCSR1A  &= ~(1<<FE1);        //reset flag
          RxCount  = rx_address;      //reset frame counter
          gRxState = BREAK;
        }
      }
      else if(rx_isr_number == 2)
      {
        USARTstate = UCSR2A;            //get state
        RxByte     = UDR2;                //get data
        RxState    = gRxState;       //just get once from SRAM!!!
        if (USARTstate &(1<<FE2))         //check for break
        {
          UCSR2A  &= ~(1<<FE2);        //reset flag
          RxCount  = rx_address;      //reset frame counter
          gRxState = BREAK;
        }
      }
      else if(rx_isr_number == 3)
      {
        USARTstate = UCSR3A;            //get state
        RxByte     = UDR3;                //get data
        RxState    = gRxState;       //just get once from SRAM!!!
        if (USARTstate &(1<<FE3))         //check for break
        {
          UCSR3A  &= ~(1<<FE3);        //reset flag
          RxCount  = rx_address;      //reset frame counter
          gRxState = BREAK;
        }
      }
    #endif

      if (RxState == BREAK)
      {
        if (RxByte == 0)
        {
          gRxState = STARTB;        //normal start code detected
          gRxPnt   = ((uint8_t*)RxBuffer + 1);
        }
        else
          gRxState = IDLE;
      }
      else if (RxState == STARTB)
      {
        if (--RxCount == 0)          //start address reached?
        {
          gRxState   = STARTADR;
          RxBuffer[0]= RxByte;
        }
      }
      else if (RxState == STARTADR)
      {
        RxPnt  = gRxPnt;
        *RxPnt = RxByte;
        if (++RxPnt >= (RxBuffer + rx_channels))  //all ch received?
        {
          gRxState= IDLE;
          if (*RXisrCallback) RXisrCallback(mUART);   // fire callback for read data
        }
        else
        {
          gRxPnt = RxPnt;
        }
      }
    }

    // *************** DMX Transmision ISR ****************
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      #if defined(USE_UART0)
        ISR(SIG_USART0_TRANS)
        {
          ArduinoDmx0.Process_ISR_TX(0);
        }
      #endif
      #if defined(USE_UART1)
        ISR(SIG_USART1_TRANS)
        {
          ArduinoDmx1.Process_ISR_TX(1);
        }
      #endif
      #if defined(USE_UART2)
        ISR(SIG_USART2_TRANS)
        {
          ArduinoDmx2.Process_ISR_TX(2);
        }
      #endif
      #if defined(USE_UART3)
        ISR(SIG_USART3_TRANS)
        {
          ArduinoDmx3.Process_ISR_TX(3);
        }
      #endif
    #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
      #if defined(USE_UART0)
        ISR(USART_TX_vect)
        {
          ArduinoDmx0.Process_ISR_TX(0);
        }
      #endif
    #endif

    void CArduinoDmx::Process_ISR_TX(uint8_t tx_isr_number)
    {
      TxState = gTxState;

      if(tx_isr_number == 0)
      {
        if (TxState == TXBREAK) //BREAK + MAB
        {
          UBRR0H   = 0;
          UBRR0L   = speed_break;
          UDR0     = 0;            //send break
          gTxState = TXSTARTB;
        }
        else if (TxState == TXSTARTB)
        {
          UBRR0H   = 0;
          UBRR0L   = speed_dmx;
          UDR0     = 0;            //send start byte
          gTxState = TXDATA;
          gCurTxCh = 0;
        }
        else
        {
          #if defined(USE_INTERBYTE_DELAY)
            delay_gap();
          #endif
          CurTxCh = gCurTxCh;
          UDR0 = TxBuffer[CurTxCh++];    //send data
          if (CurTxCh == tx_channels)
          {
            if (*TXisrCallback) TXisrCallback(0); // fire callback for update data
            gTxState = TXBREAK;   // new break if all ch sent
          }
          else
          {
            gCurTxCh = CurTxCh;
          }
        }
      }
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)

      else if(tx_isr_number == 1)
      {
        if (TxState == TXBREAK)
        {
          UBRR1H   = 0;
          UBRR1L   = speed_break;
          UDR1     = 0;            //send break
          gTxState = TXSTARTB;
        }
        else if (TxState == TXSTARTB)
        {
          UBRR1H   = 0;
          UBRR1L   = speed_dmx;
          UDR1     = 0;            //send start byte
          gTxState = TXDATA;
          gCurTxCh = 0;
        }
        else
        {
          #if defined(USE_INTERBYTE_DELAY)
            delay_gap();
          #endif
          CurTxCh = gCurTxCh;
          UDR1 = TxBuffer[CurTxCh++];    //send data
          if (CurTxCh == tx_channels)
          {
            if (*TXisrCallback) TXisrCallback(1); // fire callback for update data
            gTxState = TXBREAK;   // new break if all ch sent
          }
          else
          {
            gCurTxCh = CurTxCh;
          }
        }
      }
      else if(tx_isr_number == 2)
      {
        if (TxState == TXBREAK)
        {
          UBRR2H   = 0;
          UBRR2L   = speed_break;
          UDR2     = 0;            //send break
          gTxState = TXSTARTB;
        }
        else if (TxState == TXSTARTB)
        {
          UBRR2H   = 0;
          UBRR2L   = speed_dmx;
          UDR2     = 0;            //send start byte
          gTxState = TXDATA;
          gCurTxCh = 0;
        }
        else
        {
          #if defined(USE_INTERBYTE_DELAY)
            delay_gap();
          #endif
          CurTxCh = gCurTxCh;
          UDR2 = TxBuffer[CurTxCh++];    //send data
          if (CurTxCh == tx_channels)
          {
            if (*TXisrCallback) TXisrCallback(2); // fire callback for update data
            gTxState = TXBREAK;   // new break if all ch sent
          }
          else
          {
            gCurTxCh = CurTxCh;
          }
        }
      }
      else if(tx_isr_number == 3)
      {
        if (TxState == TXBREAK)
        {
          UBRR3H   = 0;
          UBRR3L   = speed_break;
          UDR3     = 0;            //send break
          gTxState = TXSTARTB;
        }
        else if (TxState == TXSTARTB)
        {
          UBRR3H   = 0;
          UBRR3L   = speed_dmx;
          UDR3     = 0;            //send start byte
          gTxState = TXDATA;
          gCurTxCh = 0;
        }
        else
        {
          #if defined(USE_INTERBYTE_DELAY)
            delay_gap();
          #endif
          CurTxCh = gCurTxCh;
          UDR3 = TxBuffer[CurTxCh++];    //send data
          if (CurTxCh == tx_channels)
          {
            if (*TXisrCallback) TXisrCallback(3); // fire callback for update data
            gTxState = TXBREAK;   // new break if all ch sent
          }
          else
          {
            gCurTxCh = CurTxCh;
          }
        }
      }
    #endif
    }

    void CArduinoDmx::set_speed(uint8_t mode)
    {
      if(mode == 0)
      {
        speed_dmx   = DMX_512;    // DMX-512  (250 kbaud - 512 channels) Standard USITT DMX-512
        speed_break = BREAK_512;
      }
      else if(mode == 1)
      {
        speed_dmx   = DMX_1024;   // DMX-1024 (500 kbaud - 1024 channels) Completely non standard, but usefull ;)
        speed_break = BREAK_1024;
      }
      else if(mode == 2)
      {
        speed_dmx   = DMX_2048;   // DMX-2048 (1000 kbaud - 2048 channels) Used by manufacturers as DMX1000K, DMX-4x or DMX-1M ???
        speed_break = BREAK_2048;
      }
    }

    #if defined(USE_INTERBYTE_DELAY)

    void CArduinoDmx::delay_gap() // rare cases of equipment non full DMX-512 compliant, need this
    {
      if(dmx_mode == 0)
      {
        _delay_us(IBG_512);
      }
      else if(dmx_mode == 1)
      {
        _delay_us(IBG_1024);
      }
      else if(dmx_mode == 2)
      {
        _delay_us(IBG_2048);
      }
    }
    #endif

**myFile.ino**

    /*-----------------------------------------------------------------------------
      include files
    ------------------------------------------------------------------------------*/
    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>
    #include <lib_dmx.h>

    #define DMX512  (0)

    byte mac[] = { 0xDD, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(10,0,0,2); // TODO: assign ip address from DHCP
    unsigned int multicastPort = 8888;
    IPAddress multicastIp(239,0,0,57);

    char packetBuffer[UDP_TX_PACKET_MAX_SIZE];

    EthernetUDP Udp;

    int sensorValue = 0;
    int ledState = 0;
    int DMXPin = 0;

    void setup() {

      // DMX
      ArduinoDmx1.set_control_pin(DMXPin);
      ArduinoDmx1.set_rx_channels(1);
      ArduinoDmx1.set_tx_channels(5);
      ArduinoDmx1.init_tx(DMX512);

      Ethernet.begin(mac,ip);
      Udp.beginMulti( multicastIp, multicastPort );
      Serial.begin(9600);

    }

    void loop() {
      int packetSize = Udp.parsePacket();
      if(packetSize){
        Serial.print("Received packet of size ");
        Serial.println(packetSize);
        Serial.print("From ");
        IPAddress remote = Udp.remoteIP();
        for (int i =0; i < 4; i++){
          Serial.print(remote[i], DEC);
          if (i < 3){
            Serial.print(".");
          }
        }
        Serial.print(", port ");
        Serial.println(Udp.remotePort());

        Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
        Serial.println("Contents:");
        Serial.println(packetBuffer[0]);

        ArduinoDmx1.TxBuffer[0] = (int)packetBuffer;
      }
    }

  [1]: https://github.com/aallan/Arduino

body:
It seems that, from the discussion on the page you link to, the author of the DMX Library himself is not sure how to get this to run.

The easiest solution, it seems to me, is to modify HardwareSerial.cpp in your Arduino core to no longer use that interrupt vector.


body:
You use the Serial.begin(9600) and other Serial functions in your sketch. Therefore the HardwareSerial library is included. Just avoid the Serial stuff in your sketch, it won't work anyway, because the DMX uses the same serial port.

Have a look to
"Don't use the Arduino Serial implementation"
in
http://www.mathertel.de/Arduino/DMXSerial.aspx
The Four Universes DMX 512 Library works the same way as the DMXSerial library.


message:
How can the Arduino Uno support up to 12 servos if it only has 6 digital PWM pins?

According to [this][1]:

> The Servo library supports up to 12 motors on most Arduino boards and
> 48 on the Arduino Mega. On boards other than the Mega, use of the
> library disables analogWrite() (PWM) functionality on pins 9 and 10,
> whether or not there is a Servo on those pins. On the Mega, up to 12
> servos can be used without interfering with PWM functionality; use of
> 12 to 23 motors will disable PWM on pins 11 and 12.

However, according to [this][2]:

> Digital I/O Pins 14 (of which 6 provide PWM output)

So how can the Uno control more than 6 servos if it only has 6 digital I/O pins that can provide PWM output?

  [1]: http://arduino.cc/en/reference/servo
  [2]: http://arduino.cc/en/Main/ArduinoBoardUno

body:
Although I haven't looked at the source myself, in these types of situations they usually use [interrupt timer 1](http://playground.arduino.cc/Code/Timer1), which in PWM mode would have been associated with pins 9 and 10. This would explain why you can't use pulse width modulation on those pins. In fact, you can use any of the three timers for PWM [on any digital pin, although it's not as good as the built in PWM options](http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM).

>[![][1]][1]
<sub>(source: [bansky.net](http://bansky.net/blog_stuff/images/servo_pulse_width.png))</sub>

*([Source](http://forum.arduino.cc/index.php/topic,14146.0.html))*

The above image accurately describes how the signals are sent to the servo motor. Such a waveform is similar to a standard PWM. The servo library can translate a degree to a waveform that the servo's IC will be able to use to adjust the motor's position with it's motor and potentiometer.

 [1]: https://i.stack.imgur.com/u3eoJ.png


message:
Arduino Uno + Ardumoto + BT robot works from USB but not from baterries

My Arduino UNO board is part of a [small robot][1] that works when connected to the laptop by USB but it does not when plugged to the batteries. The baterries plug seems okay, it outputs 7.8 V. My UNO is connected to an ArduMoto board that manages the robot motors as well as a bluetooth chip. I have little experience with Arduino or electronics in general so I am stuck on the best course of action.

1) Can I find out what is wrong with the power supply without completely isolating UNO from the robot?

2) If I separate UNO, how can I find out with certainty if my UNO power supply is damaged or not? Is there something in particular that I could measure with my multimeter?

UPDATE

After fully charging my batteries I observed that the LEDs attached to the motor outputs are blinking fast. They blink for about one minute then nothing happens anymore. On USB everything works as expected. Those LEDs show that signal is going towards the motors, but why is it so different to USB? On USB power, the LEDs blink only when I command the robot to move through the BT board while under baterries they blink furiously for a minute and that is all that happens.

I also don't know what happened to the batteries, they seem to be fully drained in just one minute, but I don't know how to test that, they appear to still have high voltage.

I use two LC 18650 4800 mAh 3.7 V UltraFire baterries. The motor shield is Ardumoto Keyes_L298P, very similar to [Sparkfun's Ardumoto shield][2].

I do not have the actual code that is on my Arduino. It must be similar to the code on [this page][3], since I am using their Android app for BT communication with my robot, and it works on USB power supply.

  [1]: http://www.hobbyking.com/hobbyking/store/__37893__Arduino_Tracked_Cellphone_Bluetooth_Robot_Kit.html
  [2]: https://www.sparkfun.com/products/9815
  [3]: http://www.mobot.es/MobotBTCar.html

body: Are you powering the motors with a separate supply, and not direct from the Arduino? Motors should be powered separately and the power only switched by the Arduino. Otherwise, their current draw could be pulling down your battery voltage. And even with USB power, they could be drawing more current than spec'd for either the USB power source or the Arduino's regulator or output pins. The chip itself is spec'd for a maximum current of 40mA per pin and 200mA total.


message:
Arduino Yún console clear

I'm having a problem. I want to clear the screen on the connected console. And after the clear, I want to rerun my code. But I can't seem to figure out how to do it. Below is some part of the code:

    #include <motorStyring.h>
    #include <Bridge.h>
    #include <YunServer.h>
    #include <YunClient.h>
    #define PORT 6666
    motorStyring mt;
    int cm;

      YunServer server(PORT);
      const int pingPin = 9;
      int led = 13;
        void setup() {

        Serial.begin(115200);
        Bridge.begin();
        server.noListenOnLocalhost();
        server.begin();
     }
        void loop() {
        long duration, inches, cm;
        pinMode(pingPin,OUTPUT);
        digitalWrite(pingPin,LOW);
        delayMicroseconds(2);
        digitalWrite(pingPin, HIGH);
        delayMicroseconds(5);
        digitalWrite(pingPin,LOW);
        pinMode(pingPin, INPUT);
        duration = pulseIn(pingPin,HIGH);
        cm = microsecondsToCentimeters(duration);
        h();
       }
        void h()
       {
        YunClient client = server.accept();
         if (client.connected()) {
          String question = "What would you like to drink?\nyou have 4    choises:\n1)Juice\n2)Vodca\n3)Soda\n4)Mix\n";
    client.write((uint8_t*)&question[0], question.length());
    String response;
    while (client.connected()) {
      if (client.available()) {
        char cmd = client.read();
        if (cmd == '\n') {
          break;
        } else {
          response += String(cmd);
        }
      }
    }
    if (response == "juice") {
      juice();

    } else if (response == "vodka") {
      vodka();

    } else if (response == "soda") {
      soda();

    } else if (response == "mix") {
      mix();

    } else {

      String error = "you didn't select anything that corrospond to an option. \n try agin";
      client.write((uint8_t*)&error[0], error.length());
     }
       String awnser = "Here is your " + response;
       client.write((uint8_t*)&awnser[0], awnser.length());
     }
     delay(1000);
    }

**...**

Is there a way to clear the screen on the console, so that all of the text from the previous code is not disturbing the user?

body:
Perhaps you could count the number of lines in the console and the print out enough carriage returns (`"\n"`) to fill it with empty whitespace.

For example, with a console with 100 lines:

    for(int iter = 0; iter < 100; iter++) {
       client.write('\n');
    }


message:
Communication with two XBee's and Arduinos over serial

I have two XBee's connected to two Arduino Uno boards (one for each XBee). I connected each XBee to the X-CTU software, and have set the following:

_XBee 1_

`Pan ID = 4270
DL = 10
MY = 20`

_XBee 2_

`Pan ID = 4270
DL = 20
MY = 10`

_Both_

`DD = 10000
IC = FF
IR = 32`

Therefore, they should be on the same network and see each other as the 'other person' each is talking to. I'm using the TX and RX pins of the arduino and the XBee to communicate over the serial port.

When testing if each can hear the other, I loaded one arduino with this code:

    #include <SPI.h>

    void setup() {
    // put your setup code here, to run once:
      Serial.begin(9600);
    }
    void loop() {
    // put your main code here, to run repeatedly:
      Serial.print('x');
      delay(1000);
    }

Then another with this:

    #include <SPI.h>

    void setup() {
    // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(7,OUTPUT);
      digitalWrite(7,LOW);
    }
    void loop() {
    // put your main code here, to run repeatedly:
      if(Serial.available())
      {
        char getData = Serial.read();
        if(getData == 'x')
        {
          digitalWrite(7,HIGH);
          delay(500);
          digitalWrite(7,LOW);
          delay(500);
        }
      Serial.print(getData);
      getData = ' ';
      }
    }

This works perfectly. One LED will light up on the correct arduino in half second intervals. However, when I try to make them both communicate at the same time to each other, nothing happens. Neither LED will light up. The code for both arduino's is:

    #include <SPI.h>

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(7,OUTPUT);
      digitalWrite(7,LOW);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.print('x');
      delay(1000);
      if(Serial.available())
      {
          char getData = Serial.read();
          if(getData == 'y')
          {
            digitalWrite(7,HIGH);
            delay(500);
            digitalWrite(7,LOW);
            delay(500);
          }
          Serial.print(getData);
          getData = ' ';
        }
    }

But for one arduino I change the code to `Serial.print('y')` and `if(getData == 'x')` to listen for the other one. I also have tried delaying one arduino in the setup by one second to offset the sending and recieving, but that also doesn't help.

I need them to be able to listen and talk to each other, maybe even at the same time like this example. I'm trying to create a proximity sensor in, lets say the 'back', area communicate with the 'front' area, and an accelerometer and two switches from the 'front' communicate with the 'back'.

Is there any settings I can change in X-CTU, such as the baud rate or the amount of packets re-sent, to overcome this problem? Or is this merely a code issue?

I do have the power connected to the 3.3V pin of the arduino, and I'm using 470/220 Ohm resistors as voltage dividers for the output pins from the arduino to the XBee, so I don't think voltage is an issue here.

Also, I have disconnected the arduino from the computer. I'm powering it via the USB-A to USB-B cord -> 13000 mAh 5V DC rechargeable battery, so there should be no interference with the serial data lines. Pin 2 (RX) of the XBee is connected to pin D0 (RX) of the arduino, and pin 3 (TX) of the XBee is connected to pin D1 (TX) of the arduino.

Thanks for your help.

body:
Did you set one of your modules into coordinator mode?
Every xBee network needs a coordinator. Therefore, you need to put one of your Xbee modules into coordinator mode using the "Function Set" dropdown box in X-CTU. The coordinator has the fixed address 0, so you need to set DL and HL address parts of the other module to 0. On your coordinator, you can set DL to FFFF and HL to 0, which is the broadcast address.

Softserial won't help you. It's just a way to use some of the pins as an additional serial port. Don't use that if you can use a hardware serial port.


message:
Arduino Serial Communication

I'm trying to communicate with the Arduino through the serial port to fade the LED.
There's the code running on my Arduino:

    #include <aJSON.h>
    aJsonStream serial_stream(&Serial);

    const int localID = 1;
    int intensity = 100;        // fadeTo value(0% - 100%)
    int currentIntensity = 0;   // how bright the LED actually is (0-100%)
    int time = 0;               // milliseconds
    int color[] = {0, 255, 0};

    int pinRed = 11;
    int pinGreen = 10;
    int pinBlue = 9;
    int pinPower = 8;

    void fadeTo() {
      if(intensity != currentIntensity) {
        if(intensity > currentIntensity)
          currentIntensity+=1;
        else
          currentIntensity-=1;

        analogWrite(pinRed,255-currentIntensity);
        analogWrite(pinGreen,255-currentIntensity);
        analogWrite(pinBlue,255-currentIntensity);
      }
    }

    aJsonObject *createMsg()
    {
        aJsonObject *orbData, *colorData;

        orbData = aJson.createObject();
        aJson.addNumberToObject(orbData, "id", (int)localID);

        aJson.addNumberToObject(orbData, "currentIntensity", (int)currentIntensity);

        //aJson.addNumberToObject(orbData, "time", (int)time);

        colorData = aJson.createIntArray(color, 3);
        aJson.addItemToObject(orbData, "color", colorData);

        return orbData;
    }

    // echo {\"id\":1, \"intensity\":150, \"time\":10} >> /dev/ttyACM0 in terminal
    // {"id":1, "intensity":150, "time":10} in Serial Monitor
    void processMsg(aJsonObject *msg)
    {
        //Serial.println("Data succefully received.");
        Serial.println("received message: ");
        aJson.print(msg, &serial_stream);

        aJsonObject *idData = aJson.getObjectItem(msg, "id");
        if(idData != NULL)
        {
            Serial.println("ID data succefully received.");
            if(localID == (idData->valueint)) {

                aJsonObject *intensityData = aJson.getObjectItem(msg, "intensity");
                if(intensityData != NULL) {
                    if(intensityData->type != aJson_Int) {
                        Serial.println("Invalid data type for Intensity");
                        return;
                    }

                    if(intensityData->valueint == currentIntensity) {
                        Serial.println("The received intensity value is already the current LED intensity");
                        return;
                    }

                    else {
                        Serial.println("Intensity data succefully received");
                        intensity = intensityData->valueint;
                    }
                }
                else {
                    Serial.println("No intensity value received.");
                    return;
                }

                aJsonObject *timeData = aJson.getObjectItem(msg, "time");
                if(timeData != NULL) {
                    if(timeData->type != aJson_Int) {
                        Serial.println("Invalid data type for time");
                        return;
                    }
                    else {
                        Serial.println("Time data succefully received");
                        time = (timeData->valueint);
                    }
                }
            }

            else {
              Serial.println("The received ID is not mine.");
              return;
            }
        }

        else {
          Serial.println("No ID data received.");
          return;
        }

        Serial.println("received message: ");
        aJson.print(msg, &serial_stream);
    }

    void setup()
    {
        Serial.begin(9600);

        pinMode(pinRed,OUTPUT);
        pinMode(pinGreen,OUTPUT);
        pinMode(pinBlue,OUTPUT);
        pinMode(pinPower,OUTPUT);

        digitalWrite(pinPower,HIGH);
        digitalWrite(pinRed,HIGH);
        digitalWrite(pinGreen,HIGH);
        digitalWrite(pinBlue,HIGH);
    }

    void loop()
    {
        aJsonObject *orbData = createMsg();

        Serial.println("current status: ");
        aJson.print(orbData, &serial_stream);

        Serial.println();

        aJson.deleteItem(orbData);
        delay(100);

        fadeTo();

    }

    void serialEvent()
    {
        if(serial_stream.available())
        {
            // first, skip any accidental whitespace like newlines
            serial_stream.skip();
        }

        if(serial_stream.available())
        {
            aJsonObject *msg = aJson.parse(&serial_stream);

            processMsg(msg);

            aJson.deleteItem(msg);
        }
    }

The problem is, I can open my Serial Monitor in the Arduino IDE and send json data to the Arduino and I see live the changes through the output and the LED on the board. I can also send data through terminal to /dev/ttyACM0 while running Serial Monitor in the IDE and it works fine too. But as soon as I close the Serial Monitor and send data to the device through terminal, it breaks down. I can then open Serial Monitor and every time I get the ERROR from json parser --> ("No ID data received.").

Has anyone any idea why this is happening?

body:
I had a similar problem trying to use the commands such as :

> echo 1 > /dev/ttyACM0

and found that I needed privileges to perform serial communication in this way like:

> sudo echo 1 > /dev/ttyACM0

You could also try setting the baud rate you are communicating at :

> sudo echo 1 > /dev/ttyACM0 9600

GOOD LUCK!


message:
Can Arduino Mega2560 Use this 24VDC Relay?

Can a Arduino MEGA 2560 R3 provide enough current out of its pin to activate the [Songle srd-24vdc-sl-c relay][1]? Will powering the Arduino with an external power supply help?

![enter image description here][2]

  [1]: http://www.hebertech.com/view/3778-songle-srd-24vdc.pdf
  [2]: https://i.stack.imgur.com/8zapx.png

body:
This relay cannot be **directly** commanded by any Arduino because its coil require **24V voltage** to be able to switch the contact; Arduino Mega pins output voltage is **5V**.

Regarding **current**, the **relay coil needs 15mA** ("high sensitivity" model) **or 18.7mA** (standard model), that would be OK for an Arduino Mega pin (**max current = 40mA**).

Anyway, you would have to add some circuit to adapt voltage between the Arduino pin and the relay. For this, first of all **you will need to get a second power supply** (in addition to the Arduino 5V supply used for Arduino) that can supply 24V.

Then you could use a [MOSFET][1] transistor between the Arduino pin and the relay. A MOSFET is often used in so-called **Solid State Relay** ([SSR][2]) because it can almost do the same as a coil relay but is 100% electronic-based (no moving parts); however, contrarily to a coil relay, it does not provide galvanic isolation between the input and the output circuits.

You can check out [this question][3] to find out further information on MOSFET.

Personnally, I would rather replace that relay with a 5V relay model, as that would make the circuit simpler, and would remove the need for a second power supply.

  [1]: http://en.wikipedia.org/wiki/MOSFET
  [2]: http://en.wikipedia.org/wiki/Solid-state_relay
  [3]: https://arduino.stackexchange.com/questions/403/how-can-higher-current-devices-motors-solenoids-lights-etc-be-controlled-b