# Question
Title: Running light, without delay, and a potentiometer
I am just getting hands on to my Arduino Uno.

I am have finished the blinking light tutorial, managed to read a potentiometer, build a running light with delays and as well a binary counter.

Now I build a small project with 5 LEDs and a potentiometer to configure a running light and change the speed of the running light with the potentiometer.

The LEDs are connected to the pins 13 to 9 and the potentiometer is connected A0 and 5V.

I also managed to program it without a delay function, but I think it is rather ugly.

Is there a better way of doing this like I did it?

```
int led1 = 13;
int led2 = 12;
int led3 = 11;
int led4 = 10;
int led5 = 9;
//the delay
int pause = 1500;
//count to decide which LEDs are HIGH and which are LOW
int count = 0;
// will store last time LED was updated
unsigned long previousMillis = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {

  unsigned long currentMillis = millis();

  // read the input on analog pin 0:
  pause = analogRead(A0);
  float voltage = pause * (5.0 / 1023.0);

  // print out the value and teh corresponding voltage you read:
  //Serial.println("Value: %d and Voltage: %f", pause, voltage);
  Serial.print("Value: ");
  Serial.println(pause);
  Serial.print("Volts: ");
  Serial.println(voltage);

  if (currentMillis - previousMillis >= pause) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    if (count == 0) {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
    }
    else if (count == 1){
      digitalWrite(led2, HIGH);
    }
    else if (count == 2) {
      digitalWrite(led1, LOW);
      digitalWrite(led3, HIGH);
    }
    else if (count == 3) {
      digitalWrite(led2, LOW);
      digitalWrite(led4, HIGH);
    }
    else if (count == 4) {
      digitalWrite(led3, LOW);
      digitalWrite(led5, HIGH);
    }
    else if (count == 5) {
      digitalWrite(led4, LOW);
    }
    else if (count == 6) {
      digitalWrite(led4, HIGH);
    }
    else if (count == 7) {
      digitalWrite(led5, LOW);
      digitalWrite(led3, HIGH);
    }
    else if (count == 8) {
      digitalWrite(led4, LOW);
      digitalWrite(led2, HIGH);
    }
    else if (count == 9) {
      digitalWrite(led3, LOW);
      digitalWrite(led1, HIGH);
    }
    else if (count == 10) {
      digitalWrite(led2, LOW);
      digitalWrite(led1, HIGH);
      count = -1;
    }
    count++;
  }
}

```

# Answer
You can put the LED pin numbers into an array. After each delay period, turn off the current LED, increment the count, and turn on that LED. For example:

```
// Sketch re: http://arduino.stackexchange.com/questions/19605/running-light-without-delay-and-a-potentiometer

// Set constants for pins with LEDs
enum { led1 = 13, led2 = 12, led3 = 11, led4 = 10, led5 = 9};

// Make an array with the LED pin numbers
byte ledPins[] = { led1, led2, led3, led4, led5 };

// # of entries in ledPins:
enum { numLeds = sizeof(ledPins) / sizeof ledPins[0]};

//count to track which LEDs are HIGH and which are LOW
int count = numLeds-1;      // Will roll over to 0

// To store last time LED was updated
unsigned long previousMillis = 0;

void setup() {
  // initialize digital pin outputs
  for (byte i=0; i<numLeds; ++i)
    pinMode(ledPins[i], OUTPUT);

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// loop() runs over and over again forever:
void loop() {
  unsigned long currentMillis = millis();
  // read input on analog pin 0:
  int deli = analogRead(A0);
  float voltage = deli * (5.0 / 1023.0);

  // Print out the value and corresponding voltage you read:
  // Serial.println("Value: %d and Voltage: %f", pause, voltage);
  Serial.print("Value: ");
  Serial.println(deli);
  Serial.print("Volts: ");
  Serial.println(voltage);

  if (currentMillis - previousMillis >= deli) {
    // Save the last time we blinked the LED
    previousMillis = currentMillis;

    // Turn off current LED, turn on next one
    digitalWrite(ledPins[count], LOW);
    count = (count+1) % numLeds;
    digitalWrite(ledPins[count], HIGH);
  }
}

```
> 1 votes

# Answer
Your Serial.print()s will print on every iteration of loop() even if that iteration doesn't operate on the LEDs. You'll be swamped with output on the terminal.

One improvement I'd make would be to get rid of the counter and the if/else if/.../else if segment. Rotate a bit through a byte variable for as many bit-positions as you have LEDs. Then call a function with that byte, that will set each LED on or off according to the state of its respective bit.

One more improvement can be had if you rotate the bits through bit positions 1 to 5 (in this case) of your byte variable, because you made the fortunate or perhaps intentional assignment of LED's to digital I/Os that are adjacent bits in PORT-B! One single `PORTB = [your byte];` statement could set all 5 LEDS simultaneously.

Update: PORTB is a register in the UNO's Atmega328p MCU, one of three (PORTB, PORTC, and PORTD) that connect to all of the I/Os on the UNO (or any other '328 based MCU board). By setting the (up to) 8 bits in one port, a single assembly-language instruction can set that many I/Os simultaneously. It is incredibly efficient. The downside of doing that instead of calling digitalWrite() is that the sketch is then tailored to that particular processor. digitalWrite() uses more program memory and execution time (by a lot, especially when setting multiple I/Os), but keeps your sketch processor independent; digitalWrite() knows which processor it was compiled for and how to translate a Digital I/O number to a physical external pin on that processor, so you don't have to.

For those interested in the low level details of the hardware, they are in the processor's datasheet.
> 1 votes

# Answer
Completed now.

@all: Thank you very much.

@JRobert: Thanks a lot for the very good explanation @jwpat7: Thanks for the code, it helped me a lot.

```
// Sketch re: http://arduino.stackexchange.com/questions/19605/running-light-without-delay-and-a-potentiometer

// Set constants for pins with LEDs
enum {
  led1 = 13, led2 = 12, led3 = 11, led4 = 10, led5 = 9};

// Make an array with the LED pin numbers
byte ledPins[] = {
  led1, led2, led3, led4, led5 };

// # of entries in ledPins:
enum {
  numLeds = sizeof(ledPins) / sizeof ledPins[0]};

//count to track which LEDs are HIGH and which are LOW
int count = numLeds-1;      // Will roll over to 0

// To store last time LED was updated
unsigned long previousMillis = 0;

//direction forward
boolean forward = true;

void setup() {
  // initialize digital pin outputs
  for (byte i=0; i<numLeds; ++i)
    pinMode(ledPins[i], OUTPUT);

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// loop() runs over and over again forever:
void loop() {
  unsigned long currentMillis = millis();
  // read input on analog pin 0:
  int deli = analogRead(A0);
  float voltage = deli * (5.0 / 1023.0);

  // Print out the value and corresponding voltage you read:
  // Serial.println("Value: %d and Voltage: %f", pause, voltage);
  // Serial.print("Value: ");
  // Serial.println(deli);
  // Serial.print("Volts: ");
  // Serial.println(voltage);

  if (currentMillis - previousMillis >= deli) {
    // Save the last time we blinked the LED
    previousMillis = currentMillis;

    if(forward){
      // Turn off current LED, turn on next one
      digitalWrite(ledPins[count], LOW);
      count = (count+1) % numLeds;
      digitalWrite(ledPins[count], HIGH);

      if(count == numLeds-1 ){
        forward = false;
        count = 0;
      }
    }
    else {
      digitalWrite(ledPins[count + numLeds-1], LOW);
      count = (count - 1) % numLeds;
      digitalWrite(ledPins[count + numLeds-1], HIGH);

      if(count + numLeds-1 == 0){
        forward = true;
        count = 0;
      }
    }
  }
}

```
> 0 votes

---
Tags: c++, led, potentiometer
---


title: Visual Micro without .ino files

text:
# Question
Title: Visual Micro without .ino files
I am using the visual micro extension for Visual Studio 2015. I would like to not use any .ino files since I'm trying to setup cppcheck which doesn't recogonize .cpp files, and its just what I'm used to. However when I change my project.ino file to project.cpp the compile option is no longer available (I assume its looking for a .ino file). Is there a project setting I can change to fix this?

# Answer
> 2 votes
Make a new tab in the IDE (top RH corner) with a xxx.cpp file name. Put your code in that. Leave the .ino file blank. Then it will compile. You need to add:

```
#include <Arduino.h>

```

... to the start of the .cpp file.

More information: How to avoid the quirks of the IDE sketch file pre-preprocessing

---

To clarify the question about libraries ...

You do need to put into the .ino file an include for any libraries used in the project. For example:

```
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>

```

This effectively triggers the Arduino build process to link those libraries into the final executable file.

Related, my reply in this thread: Classes and objects: how many and which file types do I actually need to use them?

# Answer
> 1 votes
As you have found, Visual Micro will not consider the project to be an Arduino project if you do not have a "project\_name.ino" included in the project

A cheat is to create a "project\_name.cpp" and include it in the project. This will cause the .ino to be ignored during compilation.

EDIT: The project\_name.cpp takes priority during compile, therefore the .ino just becomes a dummy. However the .ino will still be used for intellisense. The cpp should be #included in the .ino along with any libraries you want discovered by intellisense.

The Visual Micro release yesterday includes automatic "library in library" discovery which means you would no longer need to put all lib #include's in the project\_name.ino. (tip: you can switch the "deep search" feature off for each project via the Visual Micro menu. It slows the compile down with large libraries)

---
Tags: build, visualstudio, ino
---


title: Due : DMAC BTSIZE trimmed modulo 8192?

text:
# Question
Title: Due : DMAC BTSIZE trimmed modulo 8192?
On Arduino Due, I set-up DMA transfers using direct control of memory mapped hardware registers.

There is a 16-bit BTSIZE field in CTRLA which indicates the number of (width sized) transfers. If I specify larger than 8191, the value of btcount is trimmed to 13 bits after the DMA channel is enabled. I set chunk size src/dest to 1.

The ATMEL data sheet for the sam3x (linked from the due page) does not mention this 'limitation' (section 22.7.16), or possibly I'm using it wrong.

What reference is canonical and correct for the DMAC (dma controller)?

---

As noted in the links in the comments, multi-buffer transfer can work around this, but since I don't know why it works or fails, it's hard to decide if that solution will work in all cases.

# Answer
> 2 votes
I'll quote the answer given in this link to help make this question more useful for future people who search this problem.

> The dmac.h file in asf library has a macro named DMA\_MAX\_LENGTH set to 0xFFF = 4095. We tried changing it to higher values but still Buffer Transfer size (BTSIZE) register was showing only values till 4095. This seemed to us to a hardware limitation of the DMAC in Atmel SAM3x8E (which we did'nt see mentioned in the datasheet). So this closed the option of single buffer transfer for us and we moved to multi-buffer transfer
>
> It was a simple way out (even though I took some time to figure it out :P ) - *Use multi-buffer transfer with contiguous source address!* (see table 22.4 Row 3)

---
Tags: arduino-due, hardware
---


title: Resetting 16U2 Processor on Uno (R3)

text:
# Question
Title: Resetting 16U2 Processor on Uno (R3)
This question got me thinking, the OP was wondering about how to "bring back" Leonardo boards connected to a Raspberry Pi via USB. The Leonardos would occasionally drop off line and could not be brought back by resetting the board.

So I got curious and hooked a Uno up to a Pi via USB and started poking around. I had the idea that perhaps resetting the 16U2 would do the trick. It does not. After resetting the 16U2 (by grounding the reset pin in the ICSP connector). This is what I see in the kernel log on the Pi:

```
[ 6277.570058] usb 1-1.3: USB disconnect, device number 11
[ 6278.576503] usb 1-1.3: new full-speed USB device number 12 using dwc_otg
[ 6278.684793] usb 1-1.3: New USB device found, idVendor=03eb, idProduct=2fef
[ 6278.684823] usb 1-1.3: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

```

As opposed to this:

```
[ 6325.960510] usb 1-1.3: USB disconnect, device number 12
[ 6329.267003] usb 1-1.3: new full-speed USB device number 13 using dwc_otg
[ 6329.382675] usb 1-1.3: New USB device found, idVendor=2a03, idProduct=0043
[ 6329.382703] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 6329.382720] usb 1-1.3: Product: Arduino Uno
[ 6329.382736] usb 1-1.3: Manufacturer: Arduino Srl
[ 6329.382753] usb 1-1.3: SerialNumber: 75431343334351F061E2
[ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

```

Which is what I see if I unplug and replug the USB cable.

I'd like to know what happens differently during a 16U2 reset vs. an unplug/replug cycle.

I'd also like to know if there is a way to simulate unplugging and replugging the USB cable. The 16U2 reset comes close (the Pi notices that something happened), but it would be nice if there were a way that either code on the Uno or on the Pi could "wake up" a down USB link.

# Answer
> 2 votes
What I think is happening here is that the HWBE fuse is set (hardware boot enable).

From the datasheet:

> The Hardware Boot Enable Fuse (HWBE) can be programmed so that upon special hardware conditions under reset, the bootloader execution is forced after reset.

What this means is that under normal booting (power-on reset) the bootloader is not entered, and the device immediately identifies as a TTY device (ttyACM0) as you saw:

```
[ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

```

However if you manually reset it, it enters DFU mode with its bootloader, so you can reprogram the main code. Thus it identifies differently:

```
[ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

```

Thus, a forced reset via the Reset pin acts differently to a power-on rest. By design.

---

If you search for `uno enter dfu mode` you will get quite a few hits. People use that technique to reprogram their ATmega16U2 (eg. to act as a MIDI interface).

---
Tags: arduino-uno, usb, atmega16u2
---


# Question
Title: Trying to understand compilation error message
```
C:\Users\Field\Documents\Arduino\Adafruit_TCS34725-master\examples\tcs34725autorange\tcs34725autorange.ino:2:31: fatal error: Adafruit_TCS34725.h: No such file or directory

 #include "Adafruit_TCS34725.h"

                               ^

compilation terminated.

```

exit status 1 Error compiling.

# Answer
You are trying to use a library, but it is either not installed, or is installed in the wrong location. A library, in this context, is code that supports a sensor or some other hardware or that accomplishes a task. We call them libraries because we can share and reuse them – like borrowing a book from a library.

It looks like you're trying to get the Adafruit TCS34725 color sensor going. The official source of the library is in the Adafruit's GitHub repository for the TCS34725 and there is a link at the bottom of the README for how to install a library. I'll bet that will get you back on track.
> 1 votes

---
Tags: compile, adafruit
---


title: Unable to read the IC Card UID

text:
# Question
Title: Unable to read the IC Card UID
I have a RFID module using NXP RC522 chipset.

I have no idea that is it correct the module using 27.120 mHz

And I have 4 IC card,

```
A) 0005302176, (Blue color tag, come with the RFID module)
B) 0008846830 134,65006 (White card, come with the RFID module)
C) 0004189112 063,60344 (White card)
D) White card, no number print on the card. Only this card UID can be read.

```

Here is the pinout Which I connected to Arduino UNO R3

```
     RFID         UNO R3
(Pin Name, Pin)    (Pin)
SDA        1        10
SCK        2        13
MOSI       3        11
MISO       4        12
IRQ        5        -No Connect-
GND        6        Ground
RST        7        9
3.3V       8        3.3V

```

PS: I am using this library, and this example.

PS: The serial return this information `MFRC522 Software Version: 0x91 = v1.0`

# Answer
Check your power source, if you are powering the module from arduino/USB=\>part or something like that, there can be not much power for the module. Also you can try powering it 5v (not 3,3 as they should be powered by reference).

In my case I have had problems reading some types of cards, and I have solved that problems by giving better power supply, also higher power supply than in reference for some of the cards.

"By magic" the cards that were not working started working as a charm.

Also you should check if the cards you are using are all ISO14443 A

Only that kind of cards is compatible with that reader. So if you got type B, or other type of ISO cards, that will not be working. Some of them may use different frequency, there is a bunch of standards around.

Also as said before the cards can be damaged, or could be corrupted if you tried reading UID while writing to the card, the problem is known , and in that case you can damage the UID.

I hope it helps you. cheers
> 1 votes

# Answer
The MFRC522 reader is for 13.56 Mhz tags; these tags normally dont have the UID printed on them, in my experience. 125khz cards, however, usually have their SNs printed on them; as you can see all the cards that didnt work, have a 10 digit SN that seems to follow the same pattern. These card SNs can't be read by the MFRC522, as they follow a different protocol. When you buy a tag/card, make sure that its a 13.56 Mhz tag (look for Mifare tags), if you want the MFRC522 to be able to read it.
> 0 votes

---
Tags: arduino-uno, rfid
---


title: Powering 3.3v sensors from a coin cell

text:
# Question
Title: Powering 3.3v sensors from a coin cell
I want to build some small wireless temperature measurement boards, to sprinkle around the house. I'd like to power these from a single coin cell battery (CR2032).

For these I'd like to use the DS18B20 sensor. These sensor require a minimal voltage of 3v. A coin cell will however only provide 3v when it's full, and will drop to around 2.6v when 90% discharged.

From what I've read the DS18B20 will give some strange results when the supply voltage is below 3v. Also the precision can be off, when the supply voltage isn't regulated.

(The ATMega328p and NRF24L01, I plan to use, will work just fine at voltages down to 2v, so only the DS18B20 requires 3.3v.)

So I've come up with the following solutions:

1. Use two coin cells, and a (low quiescent current) voltage regulator. (Disadvantage: takes more space, more batteries, slightly more expensive.)
2. Use a boost regulator. (Disadvantage: even more expensive, and a lot more complex (for me at least).)
3. Implement a voltage doubler to power the DS18B20 when needed (every 15 minutes). To regulate the voltage I'd add a 3.3v zener diode to the output. (dirt cheap to implement)

I tend to lean toward option 3, but my question is, could it even work?

Is there something to look out for?

Or is there an even better solution?

**edit** I was planning to use the Dickson doubler circuit.

# Answer
You're missing out option 4, which is the option I would personally go for:

* Use a different temperature sensor.

A quick parametric search on Microchip (my favourite, I'm a Microchip fanboy after all...) I find quite a nice one - the MCP9844.

> Microchip Technology Inc.’s MCP9844 digital temperature sensor converts temperature from -40°C and +125°C to a digital word. This sensor meets JEDEC Specification JC42.4-TSE2004B1 mobile Platform Memory Module Thermal Sensor Component. It provides an accuracy of ±0.2°C/±1°C (typical/maximum) from +75°C to +95°C.
>
> Operating Voltage Range (V): +1.7 to +3.6

**However** it is only available as a TDFN which makes prototyping difficult, although it is one of my two preferred footprints for real building - the other being variants of QFN.

I am sure you can search other makers for similarly specified chips that will do the job without the need for fancy boosters or doublers or the expense of multiple batteries etc.

One of the first steps of any design is the component identification. Often the chip or component that many people automatically reach for because it's the first one they used, or it's the one people most often talk about, may not be the right tool for the job. It pays to shop around a bit and look to see if there is something better that will fit the bill and save cost and time in the long run by ending up with a simpler system.
> 2 votes

---
Tags: ds18b20
---


title: Details on OV7670

text:
# Question
Title: Details on OV7670
I am thinking of working on a project based on a camera module OV7670. I am making a security system using an arduino where detected motion (I am also using a PIR sensor) will trigger the camera module. I wanted to get all kinds of information needed to work with the camera module in this kind of project.
I am not expecting a very long answer rearding everything about the module. The most important points and maybe a few references would be enough. It would also be helpful if programming reference for the camera module is also provided.

# Answer
This post is a link to a blog that describes the pinout and connections, along with some general information. They also have a link to an "ArduCAM" library with an example utilizing your camera model.
> 1 votes

---
Tags: arduino-uno, programming, sensors, sketch, robotics
---


# Question
Title: Arduino drawing a bitmap on nokia 5110 lcd
Hello I finally got my nokia 5110 lcd working, I have tested it by displaying bitmap images other people have made. I made my own image and then used lcd assistant to turn it into an array. First look at my code.

```
#include "U8glib.h"

```

U8GLIB\_PCD8544 u8g(8, 4, 7, 5, 6); // CLK=8, DIN=4, CE=7, DC=5, RST=6

int x = 5; int y = 5;

int level = 5;

const uint8\_t rook\_bitmap\[\] U8G\_PROGMEM = { 0x7E, 0x82, 0x04, 0x8E, 0x7A, 0x42, 0xB4, 0x24, 0x08, 0xD8, 0x48, 0x08, 0x08, 0x0C, 0x02, 0x22, 0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1E, 0x11, 0x21, 0x22, 0x14, 0x3B, 0xD4, 0x25, 0x29, 0x68, 0xA8, 0xA8, 0x74, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };

void draw(void) { // graphic commands to redraw the complete screen should be placed here
u8g.drawBitmapP( 5, 5, 3,18, rook\_bitmap);

}

void setup(void) {

}

void loop(void) { // picture loop u8g.firstPage();
do { draw(); } while( u8g.nextPage() );

// y++; // rebuild the picture after some delay delay(1000); }

The part that goes wrong is at u8g.drawBitmapP(5,5,21,18, rook\_bitmap); I know it is to do with the 21 and 18 being wrong because I don't know where to get those numbers. Is it the width and height of the image when it is in paint.net or what is it?

# Answer
The 21 and 18 are the dimensions of the image. It's not just pixels though.

The first number (21) is the number of *bytes* in a row of the image - that is one eighth of the width in pixels. The width *must* be a multiple of 8.

The second number is the number of rows in the image - basically the height in pixels.

The two numbers, when multiplied together, must equal the number of bytes in your array.

From the documentation:

> **Description**
>
> Draw a bitmap at the specified x/y position (upper left corner of the bitmap). Parts of the bitmap may be outside the display boundaries. The bitmap is specified by the array bitmap. A cleared bit means: Do not draw a pixel. A set bit inside the array means: Write pixel with the current color index. For a monochrome display, the color index 0 will usually clear a pixel and the color index 1 will set a pixel.
>
> **Arguments:**
>
> * u8g : Pointer to the u8g structure (C interface only).
> * x: X-position (left position of the bitmap).
> * y: Y-position (upper position of the bitmap).
> * cnt: Number of bytes of the bitmap in horizontal direction. The width of the bitmap is cnt\*8.
> * h: Height of the bitmap.

---

It would appear your image data is complete gibberish. This is what I decode it to be:

```
 ######  #     #  #
 ###   # # ####  #    #
  # ## #  #  #     #
   ## ##   #  #    #
   #      ##     #
 #   #  #  ## #####

        #        ####
#   #   #    #   #   #
  # #   ## ###    # # ##
# #  #  #  # #     # ##
   # # #   # # #  # ###
  ##    ##

```
> 0 votes

---
Tags: arduino-uno
---


title: Arduino U8glib: how to display text?

text:
# Question
Title: Arduino U8glib: how to display text?
I have a Nokia 5110 screen using u8gliv. I have it displaying an image and I can get it to display text:

```
   u8g.setFont(u8g_font_osb18);
   u8g.drawStr(0, 20, "PRESS START");

```

The problem is that this font size is way too big. How can I make it smaller? Do I have to use different fonts? If so how do I do that?

# Answer
Just choose a smaller font. You know, I showed you the documentation earlier. You really should read it, because it contains all the information you need.

For instance, here is the section on the available fonts: https://code.google.com/p/u8glib/wiki/fontgroup \- each section contains a link to download the font group which of course you will need to do before you can use it.

You might find something like:

```
u8g.setFont(u8g_font_fixed_v0);

```

more to your liking. And don't forget to download it via the link above first.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Is it possible to specify a pin upon which the data sent over i2c can act?
A master will send fan speed values to the slave. The slave will then read the fan speed values and change the speed value for the relevant pwm pin. However I am not sure how I can tell the slave which pin the data is for. Should I send two packets of data in quick sucsession and then have a loop system wherby the first peice of data out of two is always for specifying the pin? Any help in tackling this would be greatly appreciated.

# Answer
You can use a struct to send multiple things, like this:

```
#include <Wire.h>

const byte SLAVE_ADDRESS = 42;

struct t_message
{
  byte pin;
  byte speed;
} message;

void setup ()
{
  Wire.begin ();   // initialize master
}  // end of setup

void loop ()
{
  // set desired parameters
  message.pin = 10;
  message.speed = 50;

  // send the message
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write ((byte *) &message, sizeof message);
  Wire.endTransmission ();
}  // end of loop

```

---

More information about I2C - Two-Wire Peripheral Interface - for Arduino

---

On that page is mentioned how to Send and receive any data type. This includes structs. Using the code there you could send a struct, and receive a struct.
> 2 votes

# Answer
In a way, yes. You are making the assumption that many beginners do, that I2C is only able to send one byte. That's not the case. You can send many bytes as one single packet with I2C.

Send a single packet consisting of two bytes - the first is the pin number and the second the speed.
> 0 votes

---
Tags: c++, i2c
---


# Question
Title: Long Distance Communication with Arduino
I am reading the value of six potentiometers with a TX Arduino and receiving that data and applying those numbers to a motor using serial. It is working fine through TTL but I am going to need to do this over a 60 ft tether.

I have done a little research and see that I could use RS 232 but that the maximum you should go with that is 50 ft, which will not work if I'm not mistaken. I have also seen RS 485 which will give us 4000 ft, which is overkill but will work. However, that only offers one-way communication, if I'm not mistaken. What I'm wondering is which protocol should I convert it to, and how I would have to adjust my RX and TX code.

TX code:

```
/*
  Transmitting Code
  Reads potentiometers and sends them through serial
*/

int data [10];     // to send bytes
int start [2];
int pot0Pin = A0;  // analog pin used to connect the potentiometer
int pot0;          // variable to read the pot0ue from the analog pin
int pot1Pin = A1;
int pot1;
int pot2Pin = A2;
int pot2;
unsigned char checksum0;
unsigned char checksum1;
unsigned char checksum2;

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(19, INPUT);
  pinMode(18, OUTPUT);
}

void loop() {

// READ THE POTENTIOMETERS:

  pot0 = analogRead(pot0Pin);   // reads the value of the potentiometer (pot0ue between 0 and 1023)
  data[0] = pot0 & 0xFF; //least significant 8 bit byte
  data[1] = (pot0 >> 8); //most significant 2 bits

  pot1 = analogRead(pot1Pin);
  data[2] = pot1 & 0xFF;
  data[3] = (pot1 >> 8);

  pot2 = analogRead(pot2Pin);
  data[4] = pot2 & 0xFF;
  data[5] = (pot2 >> 8);

// CREATE CHECKSUMS:

  checksum0 = ~(data[0]+data[1]) + 1;

  checksum1 = ~(data[2]+data[3]) + 1;

  checksum2 = ~(data[2]+data[3]) + 1;

// WRITE VALUES AND CHECKSUMS TO SERIAL:

  Serial1.write(data[0]);
  Serial1.write(data[1]);

  Serial1.write(data[2]);
  Serial1.write(data[3]); //bytes sent

  Serial1.write(data[4]);
  Serial1.write(data[5]);

  Serial1.write(checksum0);

  Serial1.write(checksum1);

  Serial1.write(checksum2); // send the checksum

 delay(10);        // delay in between reads for stability

}

```

RX code:

```
/*
  Receving Code
  Reads bytes from Transmitting Code and put thems back together
  Applies the read bytes to our motor control board
*/
unsigned char val[10];    // variable to read the value from the analog pin
int motorVal;
int coolVal;      // 0-1024 received from serial
int coolVal1;
int coolVal2;
unsigned char checksum1;
unsigned char checksum2;
unsigned char checksum3;
unsigned char checkit1;
unsigned char checkit2;
unsigned char checkit3;
int directionPin = 8;
int PWM_out_pin = 9; // works on pins 2 - 13 and 44 - 46

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
//  Serial1.begin(9600);
  pinMode(10, INPUT);
  pinMode(18, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
}

void loop() {

  if (Serial1.available()>5) {

    val[0]=Serial1.read();         // least significant 8 bits
    val[1]=Serial1.read();         // most significant 2 bits

    val[2]=Serial1.read();
    val[3]=Serial1.read();

    val[4]=Serial1.read();
    val[5]=Serial1.read();

    checksum1=Serial1.read();
    checksum2=Serial1.read();
    checksum3=Serial1.read();// get the checksum last

    checkit1 = val[0]+val[1]+checksum1;
    checkit2 = val[2]+val[3]+checksum2;
    checkit3 = val[4]+val[5]+checksum3;

  if (checkit1==0);  {
    coolVal = val[1]<<8 | val[0]; }

  if (checkit2==0);  {
    coolVal1 = val[3]<<8 | val[2];}

  if (checkit3==0);  {
    coolVal2 = val[5]<<8 | val[4];
    }

    Serial.print(coolVal);
    Serial.print(" ");
    Serial.print(coolVal1);
    Serial.print(" ");
    Serial.println(coolVal2);
    delay(10);

  }

// FOR MOTOR 1 (more will be added once we achieve successful serial):
  if (coolVal > 550) {
    digitalWrite (directionPin, HIGH);
    motorVal = map(coolVal, 550, 1023, 0, 1023);
    analogWrite (PWM_out_pin, motorVal / 4); }

  if ((coolVal < 550) && (coolVal > 500)) {
    digitalWrite (directionPin, HIGH);
    analogWrite (PWM_out_pin, 0); }

  if (coolVal < 500) {
    digitalWrite (directionPin, LOW);
    motorVal = map(coolVal, 0, 500, 1023, 0);
    analogWrite (PWM_out_pin, motorVal / 4); }

}

```

# Answer
> 2 votes
You're right that 60' exceeds the spec for RS-232. That said, distance specs are often quite conservative (as they should be, the spec is a promise that it will work and needs to account for marginal components and an unfavorable environment). I think the 50' limit for RS-232 was more observed in the breach than in practice. So for starters I'd be inclined to see if you could get 60' using RS-232 – I'd be kind of surprised if it didn't work.

Since reliability is important you're doing the right thing by checksumming and checking the data. If the checksum you use is good, it will go a long ways towards letting you detect corrupted data. Then, even if you are using a less than perfect underlying medium (e.g., RS-232 over a long distance), you can improve reliability by ignoring any corrupted values you receive. What that won't protect you from is a major data loss – for example a cut in your cable or a very noisy environment where most of your messages are getting lost. To defend against that you need a mechanism that also acknowledges your transmissions.

So, at this point you've got a choice – you could keep thinking of what might go wrong and designing solutions, or you could see if you could build on existing work. One thing you might want to look at is using something like the SLIP (**S**erial **L**ine **IP**) protocol which was developed to run TCP/IP over a dialup modem back in the dark ages of the Internet. I found, but haven't tried out, a couple of implementations for the Arduino:

RS-485 is (can be) bi-directional, you just need a transmitter and receiver at each end. Another approach would be to use a 4-20 mA current loop.

You might also want to look into making the controller wireless. That would get you some added convenience (at the expense of a tether to help you find where you put the box) as well as a reliable two-way communication protocol.

# Answer
> 0 votes
You can do two-way communication with RS485. I have a page about RS485 with schematics and code, including calculating checksums.

You don't have to use twisted cable, that would just add to the reliability. You would need 4 cores (power, ground, A and /B) however if the other end was self-powered (ie. a battery) then you could skip that. There has been a bit of debate about whether the ground wire is needed (assuming you don't send power) but it is probably sensible to include it.

The page I linked above also describes a rolling master system, where each node has a chance to "talk" to other nodes. This demonstrates that you can send and receive on the same pair of wires.

In my test of the rolling master (using UTP cable) I had it working over 40 meters (ignore the figure on the schematic). So your 50 feet range should be easily achievable.

---
Tags: serial, arduino-mega, c++, rs485, rs232
---


# Question
Title: How to diagnose unresponsive Leonardo serial port?
I was using an Arduino Leonardo (in the form of an RPI hat) to control a single DC motor via a motor controller. I have it wired to set Phase and Enable to control motor speed and direction, and I read sensors on the motor's encoder to directly measure motor speed.

I triple checked all my wiring, and a test program I wrote to spin the motor at half-speed seemed to work just fine. Then it suddenly stopped working. Now, when I plug the Leonardo into my machine, the ttyACM0 device does not appear, and I seem to have no way to communicate with it anymore.

I've noticed that when I press the reset button, the Leonardo's status light flashes for a few seconds and ttyACM0 does momentarily appear. But as soon as the flashing stops, ttyACM0 disappears again. I tried upload a new sketch when the device reappears, but I get a "broken pipe" error.

What's going on here? Did I somehow fry my Leonardo, or is it possible I just screwed up the serial port? How do I fix it?

Edit: For the host, I've tried Ubuntu 14 running on a Raspberry Pi 2 and a generic 64bit laptop.

Edit: My `setup()` is simply:

```
void count_pan_changes(){
    /*
    CW  => 11,00,11,00,...
    CCW => 10,01,10,01,...
    */
    int a = digitalRead(MOTOR_ENCODER_A_PIN);
    int b = digitalRead(MOTOR_ENCODER_B_PIN);
    int direction = (a == b) ? +1 : -1;
    motor_controller.record_direction(direction);
}

void setup(){
    attachInterrupt(digitalPinToInterrupt(MOTOR_ENCODER_A_PIN), count_pan_changes, CHANGE);
}

```

Edit: I'm not sure why, but when I disconnected the Leonardo from it's 5V UBEC power supply and powered it directly from my laptop via USB, then ttyACM0 suddenly came back. However, when I reconnect it to its own power supply, I again have problems connecting to it. The first upload and serial terminal seem to work, but as soon as I disconnect, further uploads/serial connections seem to fail with a "broken pipe" error. I'm powering it via a UBEC by connecting the 5V and Gnd lines to one of the Leonardo's GVS headers (i.e. it's not going in through any onboard regulator on the Arduino or RPi). Should this work? The motor is behind a separate UBEC.

Edit: Now power cycling isn't even fixing it. I tried erasing the contents using:

```
avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -e

```

as explained here. This keeps /dev/ttyACM0 from disappearing, but if I try and upload a sketch using `ano upload`, I still get the error:

```
IOError: [Errno 32] Broken pipe

```

# Answer
I think this might be a bug in Arturo. This is how I was able to fix my Leonardo:

1. Fix disappearing `/dev/ttyACM0` by pressing reset to temporarily bring it back, then erase all content with:

avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -e

Now /dev/ttyACM0 stays there, but trying to upload my sketch throws a broken pipe error.
2. Upload a blank sketch using the Arduino IDE.

Then I could upload my sketches normally.
> 0 votes

# Answer
Since your code does not open the serial port, it is entirely expected that the serial port will appear briefly on reset, and then disappear. Initially it appears as the bootloader looks for a new sketch, and disappears because your code does not open Serial.

If you time it correctly you should be able to upload a new sketch after pressing Reset. You need to press Reset fairly precisely after the IDE announces that is uploading. You only have a window of a second or so.
> 1 votes

---
Tags: usb, arduino-leonardo
---


# Question
Title: Saving byte array in PROGMEM instead of SRAM
For an ethernet project I do, I need to store the Ethernet Shield's MAC address. I store it like that:

```
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0x85 };

```

That works OK, but in my project I need all the SRAM available, so every byte of memory is important. I've used the F() macro and PROGMEM everywhere, but I couldn't manage to store the MAC byte array in the PROGMEM.

How can I store it in PROGMEM? Is it even possible?

# Answer
> 2 votes
See Putting constant data into program memory (PROGMEM) for tips about putting stuff into PROGMEM. However personally I wouldn't get too excited about saving 6 bytes.

---

Example code:

*Declare data globally:*

```
const byte mac [6] PROGMEM = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0x85 };

```

*Get a copy for use into a temporary variable:*

```
  char foo [6];
  memcpy_P (foo, mac, sizeof foo);

```

---
Tags: arduino-uno, ethernet, progmem, sram
---


title: Adafruit libary and CC3000 shield

text:
# Question
Title: Adafruit libary and CC3000 shield
I have a Arduino Uno and a CC3000 shield. When I run the example code for Webclient from Adafruits libary it works perfect.

When I switch out address for reading a corresponding text file from my own server the code completes sporadically. The output in the serial window stops at differens places every time.

Does anyone have any idea how I can fix this?

The Adafruit points to this URL: http://www.adafruit.com/testwifi/index.html While mine points to this URL: http://a.sjsd.li/test/test.html

# Answer
> 1 votes
I have arrived at a solution that works for me. Instead of using Adafruit library I have adopted Sparkfuns library.

Some adjustments in the setup for the pins:

```
#define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       5   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno
#define SD_CS           4   // Chip select for SD card

```

Then some adjustemnt in the block for the HTTP request:

```
client.print("GET /index.html HTTP/1.1\r\n");
client.print("Host: ");
client.print(server);
client.print("\r\n\r\n");
client.println();
Serial.println();

```

This is not a solution for the Adafruit libary. But it helped me to continue my project.

# Answer
> 0 votes
Perhaps the CC3000 isn't waiting long enough for the whole response to come in. Try increasing the variable `IDLE_TIMEOUT` in the Web\_Client sketch, near the top. Change its value to 10000 and see if you get the whole response this time.

---
Tags: arduino-uno, wifi, adafruit
---


title: Arduino String problem

text:
# Question
Title: Arduino String problem
Hello I am using the u8glib library to draw text on the string but it keeps giving me an error with the string

```
 String name1 = "";
 ...
 void draw(){
  u8g.setFont(u8g_font_micro);
  u8g.drawStr(22, 37, name1);
 }

```

why dosnt this work?

Here is the error:

> C:\Program Files (x86)\Arduino\libraries\U8glib/U8glib.h:200:16: note: no known conversion for argument 3 from 'int' to 'const \__FlashStringHelper\*' no matching function for call to 'U8GLIB\_PCD8544::drawStr(int, int, String&)'

# Answer
> 2 votes
String is evil and should be avoided at all costs (http://hacking.majenko.co.uk/the-evils-of-arduino-strings)

The author of u8glib knows that and has refused (quite rightly) to implement them.

You should not use String either. If you really *must* for some obscure reason then you will have to pass the internal "C string" reference to the `drawStr` function instead of the whole String object:

```
u8g.drawStr(22, 37, name1.c_str());

```

The *only* reason people use String is because they are too lazy to learn the proper way of handling textual data in C.

# Answer
> 0 votes
Like the documentation says, that method doesn't take a `String` object. Call the `c_str()` method of the `String` object and pass that instead.

---
Tags: arduino-uno
---


title: Arduino Google speech api

text:
# Question
Title: Arduino Google speech api
I'm currently experimenting with my arduino Uno. I control it via an mobile (android) but wanted to just use a microphone on the board so I don't need to carry my mobile around. It is possible to record flac files from a mic and send it to Google speech api and get a return? And then maybe output it via the synthesis.

So it is possible to do this on an arduino uno and with C. If doesnt is there any other way I can go? I could buy a raspberry pi but I don't an whole operating system like linux installed. So any thoughts?

# Answer
> 1 votes
You can use a special voice recognition shield (for example: EasyVR Shield 3.0 - Voice Recognition Shield) to integrate a simple and basic voice recognition. I think it's a very fast and easy prototyping way...

For the use of the more complex Google Speech Recognition I would use a more powerful microcontroller (such as Raspberry PI or something like that)...

---
Tags: arduino-uno, programming, c++
---


# Question
Title: İs there any way different way than GND's Arduino
İ'm making a project on my arduino uno when i figured out i had no more GND left to finish the circuit. İs there any other way to optimize, use pins as input maybe. İ tried whit other websites, however, they weren't much of a use. Can you show an example also.
Thank you sooo much in advance,
Dario

# Answer
Dario,

There are only 3 ground pins on the Arduino Uno, but don't be afraid to "breakout" these pins with wire. It doesn't matter if you connect multiple component grounds together, as long as they are connected to ground with no resistance between them, the circuit will close.

Strip board and pin headers will help you here, try this: http://www.instructables.com/id/Home-Made-Arduino-Prototype-Shield/
> 1 votes

---
Tags: input, arduino-uno, electronics
---


title: Gboard 800 (SIM900 + ATmega 328)

text:
# Question
Title: Gboard 800 (SIM900 + ATmega 328)
Greetings dear reader!

I have some trouble storing my IMEI code inside a variable. It always returns an error: "void value not ignored as it ought to be".

Since then I tried to write it to the serial line by just running the `gsm.SimpleWriteln("AT+GSN");` AT command, but I am stuck at storing this displayed value inside a variable. Does anyone here know a way to store a serial value into a variable? I just want to send the IMEI code as an identifier to the cloud application...

Thanks in advance, your response is really appreciated.

The code:

```
#include "SIM900.h"
#include <SoftwareSerial.h>
//#include "inetGSM.h"
//#include "sms.h"
//#include "call.h"

//To change pins for Software Serial, use the two lines in GSM.cpp.

//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.

//Simple sketch to communicate with SIM900 through AT commands.

//InetGSM inet;
//CallGSM call;
//SMSGSM sms;

int numdata;
char inSerial[40];
int i=0;
boolean startUp = false;

void setup() {
  Serial.begin(9600);
  Serial.println("GSM Shield testing.");

  //Start configuration of shield with baudrate.
  //For http uses it is recommended to use 4800 or slower.
  if (gsm.begin(9600)) {
    Serial.println("\nstatus=READY");
    getIMEI();
  } else Serial.println("\nstatus=IDLE");
};

void loop() {
  //Read for new byte on serial hardware,
  //and write them on NewSoftSerial.
  serialhwread();
  //Read for new byte on NewSoftSerial.
  serialswread();
};

void serialhwread() {
  i=0;
  if (Serial.available() > 0) {
    while (Serial.available() > 0) {
      inSerial[i]=(Serial.read());
      delay(10);
      i++;
    }
    inSerial[i]='\0';
    if(!strcmp(inSerial,"/END")) {
      Serial.println("_");
      inSerial[0]=0x1a;
      inSerial[1]='\0';
      gsm.SimpleWriteln(inSerial);
    }
    //Send a saved AT command using serial port.
    if(!strcmp(inSerial,"TEST")) {
      Serial.println("SIGNAL QUALITY");
      gsm.SimpleWriteln("AT+CSQ");
    } else {
      Serial.println(inSerial);
      gsm.SimpleWriteln(inSerial);
    }
    inSerial[0]='\0';
  }
}

void serialswread() {
  gsm.SimpleRead();
}

void getIMEI() {
  long IMEI = gsm.SimpleWriteln("AT+GSN"); // IMEI code
  Serial.println(IMEI);
  return IMEI
}

```

# Answer
> 1 votes
The `SimpleWriteln()` function just sends an instruction. It doesn't return anything. Once you have sent the instruction to retrieve the IMEI you then have to actually *read* the IMEI.

However, fortunately, there is a function that does it for you:

```
char imei[20];
gsm.getIMEI(imei);

```

The IMEI should now be in the C string `imei`. What you do with it then is up to you.

---
Tags: serial, arduino-ide
---


title: Connecting Arduino To mains

text:
# Question
Title: Connecting Arduino To mains
How would iconnect my Arduino Mega to house Mains, without buying a transformer, and having to make a whole setup for that. Can i just use a regular phone adapter? Or is 1 Amp too large (or 2 Amps).

# Answer
Amps tell you how much current you can draw from the power supply, or "how much it can do".

You can hook up 3Amps power supply to a device that draws 1Amp and it will work ok, still having 2 amps of reserve.

You must pay attention to power supply **voltage** and keep it in specified range.

Arduino Mega has recommended input voltage of 7-12V, so you must deliver at least 7V. There are plenty of cheap wall power supplies with voltage regulation from 1.5V to 12V.

How much current it will draw depends on your application, but I doubt that you can suck more than 0,5-1A in a typical application.
> 3 votes

---
Tags: power
---


# Question
Title: Optocouplers for Arduino DCC decoder - Explain?
I am trying to make an Arduino circuit as outlined here.

This is for connecting an Arduino input to a DCC system. DCC is a command control system for model railways that uses the same two wires for power and data (there's a wikipedia article that explains it better than I can)

I'm wondering what the optocoupler has more than 4 pins for? I'm new to this and I understand the purpose of the optocoupler but I am confused as to how this particular one works. It is a 6N136 optocoupler. I don't understand why it has the extra pins compared to 4 pin optocouplers, and I don't understand how it would read the polarity of the signal. DCC sends commands using polarity as I understand it, so I know I need to read the polarity, but how does the optocoupler do it here?

I have a very limited knowledge of electronics right now so pardon anything stupid I said :P

# Answer
That specific chip (the 6N137) uses a more efficient IC detector rather than a simple transistor junction. It also has an "enable" pin that allows it to be turned on or off. Consequently it needs a power supply to run it. That all means extra pins.

This design allows for higher speed communication (it's a 10Mbaud chip) with less leakage when compared to a traditional design.

The pin VE (pin 7) needs to be pulled up to make the chip work (the job of R2) and the output is pulled high (it's open drain) by R3.

The optocoupler will be on with one polarity and off with the other. It's as simple as that. The diode D1 protects the LED in the optocoupler from the reverse voltages.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: Use Adafruit Colorsensor to distinguish between green and red
I am using the Adafruit TCS34725 to sense color. I have used the Colorview code example to set it up to sense all colors, works great. The thing I want is for it to tell me if it is seeing either green or red, I don't care about the other colors.

Can anyone suggest what I can do?

# Answer
Based on what I could find, you will have to calibrate the sensor to recognize these colours. First, run the Colourview code. Take down the raw RGB and CLEAR values obtained for an object you consider green and another you consider red. Find out if these values are consistent, each time you power down the sensor and turn it on again. If they aren't, record how much dead zone there is i.e. the maximum difference in readings (between resets) that you get for the same colour. Then using the values you get, try this code:

```
#include <Wire.h>
#include "Adafruit_TCS34725.h"

#define MAX_OFFSET 50  // the maximum diff you found between readings

typedef struct {  // struct to hold raw color data
   uint16_t red;
   uint16_t green;
   uint16_t blue;
   uint16_t clear;
} Color;

Color my_red = {3344, 3333, 23444, 3333}; //here you enter your minimum recorded values for red in the order of the struct members above
Color my_green = {22222, 4444, 5555, 3333}; //the same for green

void setup() {
  Serial.begin(9600);
  Serial.println("Color View Test!");

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1); // halt!
  }
}

void loop() {
  uint16_t clear, red, green, blue;

  tcs.setInterrupt(false);      // turn on LED

  delay(60);  // takes 50ms to read

  tcs.getRawData(&red, &green, &blue, &clear);

  tcs.setInterrupt(true);  // turn off LED
  if (compare_colour(&my_red, red, green, blue, clear)){
      Serial.println("I see red.");
  }
  else if (compare_colour(&my_green, red, green, blue, clear)){
      Serial.println("I see green.");
  }
}

boolean compare_color(Color * std, uint16_t r, uint16_t g, uint16_t b, uint16_c){
if ((r - std.red <= MAX_OFFSET) && (r - std.red >= 0) &&
      (g - std.green <= MAX_OFFSET) && (g - std.green >= 0) &&
      (b - std.blue <= MAX_OFFSET) && (b - std.blue >= 0) &&
      (c - std.clear <= MAX_OFFSET) && (c - std.clear >= 0))
  {
      return true;
  }
  return false;
}

```

You can use this code directly after you have gotten the sensor readings for red and green objects.
> 1 votes

---
Tags: adafruit
---


title: Multiple I2C Devices connected parallel

text:
# Question
Title: Multiple I2C Devices connected parallel
I have two Lidar Lites, connected to one APM. I have no issue with getting data from one of them, i use the code below

```
#include <I2C.h>
#define    LIDARLite_ADDRESS   0x62          // Default I2C Address of LIDAR-Lite.
#define    RegisterMeasure     0x00          // Register to write to initiate ranging.
#define    MeasureValue        0x04          // Value to initiate ranging.
#define    RegisterHighLowB    0x8f          // Register to get both High and Low bytes in 1 call.

void setup(){
  Serial.begin(9600); //Opens serial connection at 9600bps.
  I2c.begin(); // Opens & joins the irc bus as master
  delay(100); // Waits to make sure everything is powered up before    sending or receiving data
  I2c.timeOut(50); // Sets a timeout to ensure no locking up of sketch if I2C communication fails
}

void loop(){
 // Write 0x04 to register 0x00
  uint8_t nackack = 100; // Setup variable to hold ACK/NACK resopnses
  while (nackack != 0){ // While NACK keep going (i.e. continue     polling until sucess message (ACK) is received )
    nackack = I2c.write(LIDARLite_ADDRESS,RegisterMeasure, MeasureValue); // Write 0x04 to 0x00
    delay(1); // Wait 1 ms to prevent overpolling
  }

  byte distanceArray[2]; // array to store distance bytes from read function

  // Read 2byte distance from register 0x8f
  nackack = 100; // Setup variable to hold ACK/NACK resopnses
  while (nackack != 0){ // While NACK keep going (i.e. continue polling until sucess message (ACK) is received )
    nackack = I2c.read(LIDARLite_ADDRESS,RegisterHighLowB, 2, distanceArray); // Read 2 Bytes from LIDAR-Lite Address and store in    array
   delay(1); // Wait 1 ms to prevent overpolling
  }
  int distance = (distanceArray[0] << 8) + distanceArray[1];  // Shift high byte [0] 8 to the left and add low byte [1] to create 16-bit int

  // Print Distance
  Serial.println(distance);
}

```

i can get the distance fine, now have two connected, as follows

So my noob question is how to i get data from the 2, my guess is the wiring is ok.

I am using the code from https://github.com/PulsedLight3D/LIDARLite\_v2\_Arduino\_Library

any help would be appreciated. thanks.

# Answer
Connect one at a time and run the change address sketch mentioned by Yeti.

Naturally change each one (one at a time) to different addresses (ex. 0x62, 0x64, 0x66).

> i still don't know whats the address of the 2nd one

The address is what you change it to.

Then connect them all back up again and run the I2C scanner. You should see all 3 addresses.

---

> documents state that address changes will be gone when i power it off

If that is true, save the address for each module in EEPROM. Then use that code to change the module address in `setup`.

---

See the address in the code you posted?

```
#define    LIDARLite_ADDRESS   0x62          // Default I2C Address of LIDAR-Lite.

```

If you don't want to save the address in EEPROM just upload three versions of the sketch with a different address in each one. Note that the address must be even (eg. 0x62, 0x64, 0x66).

But it would be very simple just to read from EEPROM in `setup` and keep the address in a variable rather than a #define.
> 1 votes

---
Tags: i2c
---


# Question
Title: Do I have to use an RTC to build a clock?
While I was researching ideas for an Arduino clock, I found several clocks that incorporated an RTC (Real Time Clock) module.

I don't know why it is used in some clocks.

So, here are my questions:

* How does an RTC module work?
* Do I have to use it "like a rule" (is an RTC necessary or unnecessary) in my clock?

# Answer
> 2 votes
> How does a RTC module works?

It counts. As simple as that. Once a second it ticks and counts up. It also remembers - most have a battery backup and will continue ticking when you turn the main power off.

> I have to use it "like a rule" (if it is necessary or unnecesary) in my clock?

If you want accuracy and continuation, yes. An RTC is designed to tick at (as close as reasonably possible) once per second. Trying to do that with just an Arduino is incredibly difficult. The ceramic resonator on an Arduino is not as accurate as the quartz crystals used with an RTC. After a week you may find you are an hour out.

# Answer
> 1 votes
RTC modules are used because they make it easier to keep accurate time. They do this by maintaining time when the system is shut down or rebooted (by way of a battery or some other mechanism for keeping running independently of the host system) and by providing a time base that is, usually, more accurate than that of the host.

Another way to keep very accurate time (potentially better than you can get with all but the best RTC modules) is to get your time from a GPS or from the Internet using NTP. If you're going to use a GPS anyway or need an Internet connection then either of those approaches are very good ways to go. If you don't, then they are considerably more expensive than an RTC module.

# Answer
> 1 votes
I built a clock designed a while ago by Geoff Graham, who synchronized to a GPS around every 24 hours, and used the internal clock in-between. The GPS corrected for drift in the internal clock (and, of course, gave you the time accurately in the process).

This is more expensive than a RTC, but more accurate. If you also had an RTC it would drift less during the day. Or, you could read from the GPS all the time and not have an RTC.

I made a GPS clock myself which does that - just shows the GPS time.

Higher-contrast image:

Internals:

---

This is another project that uses an RTC clock chip (indicated on photo):

However if you go for just an RTC chip you can expect it to drift over time. They are more accurate than counting processor ticks (and survive a power outage because of the backup battery) but are not as accurate as the GPS.

Those clock chips are pretty cheap. I got 30 of them for $10 from eBay.

# Answer
> 0 votes
> How does a RTC module works?

It is a specialized counter. It counts seconds, minutes, hours, days, months and years, properly handling such annoying problems as leap year, different days in months, etc.

Additionally it allows powering with a battery, so that clock ticks even when the device is not powered on, until battery discharges.

Usually RTC is clocked at 32768Hz using standarized quartz crystal.

> I have to use it "like a rule" (if it is necessary or unnecesary) in my clock?

Unless your microcontroller has RTC built-in, you should use an external one. There are many RTCs with I2C interface.

Built-in timer available in Arduino is not accurate enough and cannot tick when you remove power. Inaccurate counter will cause your clock to drift considerably and no backup power forces your clock to be connected all the time.

You can check out this example to see how to hook up: https://iobtoolkit.com/docs/tutorials/i2c\_terminal\_mcp7940n.html

Disclaimer: i'm the author of IOB, but you don't need to use it. It's just a nice analysis of a rather popular RTC.

# Answer
> 0 votes
For this "rule", and for many "rules" like this, the answer is "it's more of a guideline" (usually "it's not required, but may be easier that way").

Keeping time requires 3 things: an accurate "tick", a way of knowing the time initially, and counting the time since then.

The (16mHz) clock on the Arduino will give you a reasonably accurate "tick" - on the order of 50 parts per million. That means, over a million seconds, your clock will drift about 50 seconds. This works about (ballpark) 1 minute per fortnight. Is this accurate enough? This depends on what you are using it for.

The next thing on the list is knowing the time initially. If you buy a RTC, it may be set to the right time, or it may not. Even if it is "set", it may not be set to your timezone. Setting these is pretty easy. It will need to be set every time the clock (be it a RTC or your homebrew clock) loses power. For this reason, RTCs usually have a battery back up. How will your clock get it's time when it starts up? Note that, if your project is network connected, you may be able to get the clock from the internet - this will also mean the drift of your clock will not be an issue - you can retrieve it once per day, so it will never drift more than 4 seconds before it gets corrected.

The final thing that it needs (and the easiest) is a way of counting the time. This is probably the easiest - use the millis() function. Note that this overflows (resets to 0) after 4294967296 milliseconds - about once every 50 days. Millis() will tell you the number of milliseconds since the Arduino last rebooted. If you want your clock to run more than 50 days, you need to be prepared to that. This will happen part way through a second.

Note that this will give you milliseconds, and, fairly easily, seconds, minutes, hours. If you want the day (of the month), then you need to keep track of which month and year, since the length of each month will vary, as will leap days.

---
Tags: arduino-uno, rtc, oscillator-clock
---


# Question
Title: Signal a LOW level interrupt with an RTC
I'm trying to figure out how to use an RTC to send interrupts to my arduino. I'm using a DS3232. I can get an 'edge' interrupt, with the following toy code (I know the code is silly, it's just a short example to test if I have actually set the RTC to send the interrupt, and that the Arduino receives it):

```
/*----------------------------------------------------------------------*
 * Minimal example of setting a recurring alarm with the DS3232 RTC     *
 * Attach an LED to pin 7, which will flash when the alarm fires.       *
 *                                                                      *
 * Attach the RTC SQ/INT pin to Uno pin 2, with a 10K pull-up to VCC.   *
 * Ard pin A4 -> RTC SDA, Ard A5 -> RTC SCL, 5v -> vcc, GND -> GND      *
 *----------------------------------------------------------------------*/

#include <DS3232RTC.h>        //http://github.com/JChristensen/DS3232RTC
#include <Time.h>             //http://playground.arduino.cc/Code/Time
#include <Wire.h>             //http://arduino.cc/en/Reference/Wire

#define WAKE_PIN 2
#define LED_PIN 7

void setup(void)
{
    pinMode(LED_PIN, OUTPUT);

    // RTC config:
    RTC.squareWave(SQWAVE_NONE);
    pinMode(WAKE_PIN, INPUT_PULLUP);
    attachInterrupt(INT0, wakeUp, FALLING);
    RTC.setAlarm(ALM2_EVERY_MINUTE, 0, 0, 0, 1);
    RTC.alarm(ALARM_2);
    RTC.alarmInterrupt(ALARM_2, true);
}

void loop(void)
{
  if(RTC.alarm(ALARM_2)){
    digitalWrite(LED_PIN, HIGH);
    delay(5000);
    digitalWrite(LED_PIN, LOW);
  }

}

void wakeUp (){
// no-op, just checking if the interrupt fired
}

```

Why doesn't this work if I set the interupt to "LOW", ie., `attachInterrupt(INT0, wakeUp, LOW);`?

The reason I ask is I'm trying to use an RTC to wake from low power mode, and I think this doesn't work with a 'falling' interrupt.

# Answer
That page is incorrect, although it reflects what the datasheet says.

The processor **can** be woken from RISING/FALLING/CHANGE/LOW. I queried this with Atmel and got this response:

> Commented by Manoraj Gnanadhas (Atmel)
>
> 2015-01-20 06:23:36 GMT
>
> \[Recipients: Nick Gammon\]
>
> Hello Nick,
>
> Our design team has confirmed that “Note-3 mentioned under Table 10-1” is a datasheet bug. So you can use any type of interrupt (Rising edge/ Falling edge / Low level / Any logical change) to wake up from sleep mode. Sorry for the inconvenience caused.
>
> Best Regards,
>
> Manoraj Gnanadhas

This is mentioned on my page about interrupts.

---

Why does LOW hang the processor? The LOW interrupt is not an **edge** interrupt but a **continuous** one. Thus, while the signal is LOW the interrupt is being continually called, with only one processor instruction being executed after each call to the ISR (which itself takes around 5.125 µs). So, the ISR is not being interrupted, but effectively only one instruction of your code is being executed every 5.125 µs (probably about 1/40th of the usual speed).

---

> and see how much of my problem is due to using an old and buggy IDE

It's nothing to do with the IDE. Change to a FALLING interrupt and your problems should go away. You may also want to clear the interrupt flag (as documented on my page) in case the interrupt event has already happened before you go to sleep. Specifically:

```
EIFR = bit (INTF0);  // clear flag for interrupt 0

```
> 3 votes

---
Tags: c++, interrupt, rtc
---


title: Design Dilema -- What hardware?

text:
# Question
Title: Design Dilema -- What hardware?
I'm trying to build a smart thermostat for a particular application. I have the following design criteria and goals for the system:

* Must be able to set up and monitor the device from either a mobile phone or local network device.
* No go on Ethernet or other hardwired connection, except for initial setup. This must be a wireless solution. I'm presuming WiFi is best.
* Needs a clock, an on time and an off time setting.
* The system does a system time verification check once daily.
* Needs a temperature input.
* Needs to run an existing heater system (24v) thru a relay.
* 120v AC power (battery backup not required.)
* Needs to be "hidden" in existing wall as much as possible. (i.e. small & compact) My intent is to hide the unit behind a double wide electrical duplex dead panel. (i.e. 4" x 4" nominal access thru drywall)

Here's a visual of my design intent package:

As I review a number of different hardware controller devices, I can see some issues. I am very familiar with the Intel Edison, and I know exactly how to do this project there, including using the controller as a stand alone web host. (The Edison uses Yocto Linux to create a node.js server using http module.) I was hoping to save a few $$ on hardware using an alternative controller but not sure that will work. I've been wading thru the code for both the Photon and generic Arduino devices, and I'm getting the impression that I may need a custom server / api tool for a web page interface. Its not clear that those hardware choices will support an interactive web page, particularly for easy user data update via browser Submit button. That's not a big problem, I'm a freelance software developer, handy in C/C++/Java, PHP and JavaScript. And as for the Raspberry Pi, I have no experience but the pricing on some of their boards is below $15.

Here are my questions:

* Has anybody used an Arduino board to host an interactive web page, including user input via Submit / Form ? (Can I declare a local network static IP address for an Arduino?)
* Has anybody used an Particle Photon board to host an interactive web page, including user input via Submit / Form? (It looks like declaring a local network static IP address on a Photon is anything but easy...)
* Has anybody written an API Restful server for their Arduino, with both `get` and `put` functionality? (I'm thinking PHP, or node.js makes the most sense for me.) I know if I have to use Dynamic IP addressing to the controller, that I can always make an API system work for the system.
* Other comments?

# Answer
> 2 votes
> Has anybody used an Arduino board to host an interactive web page, including user input via Submit / Form ?

I have a Tiny Web Server for the Arduino. It is designed to be light-weight on RAM. It supports GET/POST/Cookies for interacting with web forms.

Example code and more information on the linked page above.

---

> (Can I declare a local network static IP address for an Arduino?)

Yes.

---

> Other comments?

You could use NRF24L01 modules for short-range communication of wireless information. I have example code and schematics. My tests seemed to indicate 20m range was achievable.

# Answer
> 2 votes
Have you looked at the Adafruit Huzzah boards? It's small, inexpensive ($10), comes with wireless capability and a 10-bit ADC for a temperature sensor. If you'll have access to the Internet, then you could use NTP to get time.

---
Tags: programming, web-server, edison, raspberrypi
---


# Question
Title: bluetooth module with stk500_recv() error
I am trying to dow what is demonstrated in this tutorial. I have altered the original setup a little by adding a level converter to not fry the Bluetooth module and resistors for the LEDs, as well as using only 2 instead of four LEDs (which I adjusted for in code later). other than that I am using the exact same setup, code,and procedure. Yet when I try to run my code on the Arduino. I get the error below. I believe it is due to using Tx/Rx and serial at the same time but I really don't know anything about this. Should I add more libraries? Should I change the wiring shown in the tutorial link? It seems like I need to use Tx/Rx

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xce
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xce
avrdude: stk500_recv(): programmer is not responding

```

Here is the code I used from tutorial:

```
//Coded By: Angelo Casimiro (4/27/14)
//Voice Activated Arduino (Bluetooth + Android)
//Feel free to modify it but remember to give credit

String voice;
int
led1 = 2, //Connect LED 1 To Pin #2
led2 = 3, //Connect LED 2 To Pin #3
led3 = 4, //Connect LED 3 To Pin #4
led4 = 5, //Connect LED 4 To Pin #5
led5 = 6; //Connect LED 5 To Pin #6
//--------------------------Call A Function-------------------------------//
void allon(){
     digitalWrite(led1, HIGH);
     digitalWrite(led2, HIGH);
     digitalWrite(led3, HIGH);
     digitalWrite(led4, HIGH);
     digitalWrite(led5, HIGH);
}
void alloff(){
     digitalWrite(led1, LOW);
     digitalWrite(led2, LOW);
     digitalWrite(led3, LOW);
     digitalWrite(led4, LOW);
     digitalWrite(led5, LOW);
}
//-----------------------------------------------------------------------//
void setup() {
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
}
//-----------------------------------------------------------------------//
void loop() {
  while (Serial.available()){  //Check if there is an available byte to read
  delay(10); //Delay added to make thing stable
  char c = Serial.read(); //Conduct a serial read
  if (c == '#') {break;} //Exit the loop when the # is detected after the word
  voice += c; //Shorthand for voice = voice + c
  }
  if (voice.length() > 0) {
    Serial.println(voice);
//-----------------------------------------------------------------------//
  //----------Control Multiple Pins/ LEDs----------//
       if(voice == "*all on") {allon();}  //Turn Off All Pins (Call Function)
  else if(voice == "*all off"){alloff();} //Turn On  All Pins (Call Function)

  //----------Turn On One-By-One----------//
  else if(voice == "*TV on") {digitalWrite(led1, HIGH);}
  else if(voice == "*fan on") {digitalWrite(led2, HIGH);}
  else if(voice == "*computer on") {digitalWrite(led3, HIGH);}
  else if(voice == "*bedroom lights on") {digitalWrite(led4, HIGH);}
  else if(voice == "*bathroom lights on") {digitalWrite(led5, HIGH);}
  //----------Turn Off One-By-One----------//
  else if(voice == "*TV off") {digitalWrite(led1, LOW);}
  else if(voice == "*fan off") {digitalWrite(led2, LOW);}
  else if(voice == "*computer off") {digitalWrite(led3, LOW);}
  else if(voice == "*bedroom lights off") {digitalWrite(led4, LOW);}
  else if(voice == "*bathroom lights off") {digitalWrite(led5, LOW);}
//-----------------------------------------------------------------------//
voice="";}} //Reset the variable after initiating

```

# Answer
How did you upload the sketch? With the Bluetooth module still connected? In that case please disconnect it and the upload. Connect again after the upload.
> 1 votes

---
Tags: serial, bluetooth, softwareserial
---


# Question
Title: 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. 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).

**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;
  }
}

```

# Answer
> 1 votes
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.

# Answer
> 3 votes
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.

---
Tags: arduino-mega, interrupt
---