# Question
Title: Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board?
Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board ? Is it possible without another component in between ?

# Answer
> 1 votes
Actually, this is dependent on the datasheet. Assuming it's 7 segment + dot, it will require 8 independent pins to control each of the segment. All of segments are connected to a common anode/cathode which can be connected to a pullup/pulldown.

If we have 4 digit, that means we need 4\*8=32 pins, which is a lot for any microcontroller. However, if you map out the internal circuit, you'll find that the segments are multiplexed. (You can do this by touching the pins with a wire connected to a pullup resistor, and another wire connected to ground.

Generally, you'll find that all the segment pins are multiplexed together in such a way that if all anodes/cathodes are enabled, all of the digits show the same display.

So how then can we make use of this information? Here's an idea:

How about turning on each of the digits one at a time (by controlling the common anode/cathode), but doing it quickly?

An example sequence would be as follows: Set the segments for digit 1, enable the corresponding common anode/cathode for 5ms. Turn off. Set the segments for digit 2, enable the corresponding common anode/cathode for 5ms. Turn off. Do the same for digit 3 and then 4. Repeat.

Controlling in this manner means you only need 8+4 pins=12 which is available on an arduino uno. Refreshing at 4\*5=20ms will hardly be visible to our human perception, thanks to persistence of vision.

My answer is really just a starting point. If you spend some time, you can try to put in other smarts which are suited for your application, using even less pins. You should try this as an exercise. ;-)

Edit: As a precaution, it's important to limit the current running through each of the LED segments so that they can live a long and happy life.

Assuming a forward voltage of 2V, adding a 1k resistor at the common anode limits the current to 3mA. This means adding resistors for all 4 anodes.

The same could work for common cathode displays, as long as the reverse breakdown voltage is not exceeded.

As with all things you find on the net, don't take my word for it. You should do the maths to check.

# Answer
> 0 votes
You need 4\*4+7 = 23 pins in common cathode configuration or 4 +7\*4 = 32 in common anode and arduino uno only have 20 output/input pins so if you don't want to use any external component you are going to need an Arduino mega.

Anyway, the best idea is to use a max7219 matrix led driver. look for it in google.

---
Tags: led, display
---


title: Multiple sensor connection help

text:
# Question
Title: Multiple sensor connection help
How would you connect multiple HC-SRO4 ultrasonic sensors to one arduino uno? As of now, I have a bunch of jumper cables, 3 u.s sensors, and one arduino uno board. How would one hook up 3 sensors? A schematic would be excellent!

# Answer
> 1 votes
It depends on what you want to do overall.

Using the HC-SR04 works roughly like this:

1. you generate a strobe on a pin for a minimum amount of time, and this strobe is understood by the sensor as "emit the ultrasound signal"
2. then you somehow (more on this later) measure how much time passed between your strobe and a change of level on another pin from the sensor - this is how the sensor notifies you that there was an echo and it has returned.
3. finally, you convert the time measured into distance, using a conversion algo (typically multiplying by a certain factor) that is specific to the sensor.

Mostly the problem revolves around point #2: how to measure the time elapsed between command (strobe) and answer (change of level).

You have various options, each with pros and cons:

* busy looping: it's easy to implement, very straightforward and works right away. The problem is that your arduino will do just that.
* polling: it's a less aggressive version of polling, where you check the values every now and then. It lets you do more, but the drawback is that in the worst case the line changes level right after you have checked it, so it will be noticed only at the following iteration. The period used for checking is the maximum error you will get.
* GPIO interrupt driven: this is harder but lets your arduino do many other things, while not loosing precision (I'll detail it separately)
* HW backed: the AVR on UNO has the ability to capture events: basically there is a timer running that will stop when it gets triggered by a certain event (ex: the change of pin level cause by the echo). It is very precise, but you are limited by the number of HW blocks available on the AVR (3 iirc).

Now about the sub-cases of the GPIO interrupt-driven solution:

* EXT based: the ATMega328p present on the UNO has what are called external interrupt sources, which is a fancy way to say that if you configure correctly a pin, the processor will notice when the pin voltage level changes and do something about it (in your case, take a time measurement) - this is quite generic solution, but unfortunately it works only on 2 pins, so you are out of lack with your 3 sensors, unless you implement some scheme where you multiplex 2 or more sensors on only one pin.
* Pin-change-interrupt based: on AVR most of the PINS are grouped in ports. Each port contains maximum 8 pins and is labelled with a letter (A, B, C, ..). The way this interrupt works is roughly like the EXT type, but with a catch: you will get an interrupt whenever *any* of the pins that you have enabled on a certain port will change. In your case you could allocate only one sensor on a certain port, so that it would be obvious that if you get an interrupt for that port, it will be because of that sensor.

So now you can see why I said "it depends". If all you want to do is to get the information about proximity, you can go with busy-looping/polling.

But if you decide later on to do more on the same arduino, be aware that you might have to come back to the implementation of the ultrasonic sensor.

Finally, there is a library for this, but its implementation will fall into one of the cases i mentioned before, so be aware that the same catch applies: at some point you might want to do something that conflicts with the library.

Other points worth mentioning, that you should consider in your design (at least experiment with them):

* orientation of the sensors: will they interfere with each other?
* timing: do you need/want to activate them all simultaneously or do you prefer to have them activated in sequence?

---
Tags: arduino-uno
---


title: Printing SD card file contents on LCD

text:
# Question
Title: Printing SD card file contents on LCD
This is a part of my program which reads data from file stored in SD card and displays that on an LCD screen.

```
  File dataFile = SD.open("1165.txt");

  if (dataFile) {
    Serial.println("File Opened");
    lcd.clear();
       delay( 5 );  //LCD-specific M
       lcd.setCursor( 0,0 );

  while (dataFile.available()) {
      Serial.write(dataFile.read());
      lcd.write(dataFile.read());
      lcd.print(dataFile.read());
    }
  dataFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error");
  }

```

When I look at the serial monitor it prints the contents of that file but none of these commands print what is printed in the serial monitor,

```
lcd.write(dataFile.read());
lcd.print(dataFile.read());

```

Any ideas?

# Answer
When you call `dataFile.read()`, the file pointer is advanced, so you always read different bytes in each `read` call. Imagine the file like a book with many lines: Each time you read, you advance the current line, so with multiple calls, you never get the same data. The solution is to currently store the last read byte:

```
while (dataFile.available()) {
  char readByte = dataFile.read();
  Serial.write(readByte);
  lcd.write(readByte);
  lcd.print(readByte);
}

```

You have two calls for displaying data in the LCD, but be careful that the second call (`print`) might interpret your data as a number, so just remove the `lcd.print(readByte)` call altogether to be sure it's printing the raw character.
> 2 votes

# Answer
You could also implement a readLine routine, similar to:

```
void _readLine(File f, char *line)
{
    boolean cr_found = false;
    int p = 0;
    while (f.available()) {
        char b = f.read();
        if(b!='\r' && b!='\n')
            line[p++] = b;

        if(b == '\r') cr_found = true;
        if((b == '\n') && cr_found) break;
    }
    line[p] = '\0';
}

```

And read the SD file line by line, processing each one of them by its own.

```
char buffer[32];

while(dataFile.available()) {
    _readLine(dataFile, buffer);
    // do something with buffer
}

```
> 1 votes

---
Tags: arduino-mega, c++, lcd, sd-card
---


# Question
Title: Teensy 3.1 no overclock option for 168 MHz
I'm sorry if this isn't the right area. Teensy uses the arduino ide.

I've seen some people show off the 144 mhz and 168 mhz option in their ide. I read in the Teensyduino 1.19 release notes that the options were added but not enabled. I would like to know how to enable it or if I somehow downloaded an older version.

P.S I get the 96 mhz option.

Thanks ahead of time!

# Answer
> 3 votes
Using the latest Teensyduino distribution as of this writing, 1.25, you have to uncomment the higher overclocking options in the `boards.txt` file, located here in my install- `/hardware/teensy/avr/boards.txt`

The options look like this, just remove the # symbol-

```
#uncomment these if you want to try faster overclocking
#teensy31.menu.speed.168opt=168 MHz optimized (overclock)
#teensy31.menu.speed.144opt=144 MHz optimized (overclock)
#teensy31.menu.speed.120opt=120 MHz optimized (overclock)`

```

---
Tags: teensy
---


# Question
Title: Multiple shift registers, 16 bit numbers
Currently working on understanding shift registers and traing to display binary number from 65535 to 0 on a 16 LED's. Below you can see schematics I am using.

The code I am using is

```
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int numberToDisplay=65535;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {

    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

    digitalWrite(latchPin, HIGH);
    delay(500);
  }

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 16; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (15 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

```

Problem is when I change numberToDisplay from 0 to 225, everything works and LEDs are lighted correspondingly (if numberToDisplay=225 all red lights are on). But if numbers are bigger than 225 everything just stops working and nothing lights up.

Thank you in advance

# Answer
> 2 votes
Your problem is entirely that you declare val to be uint8\_t, instead of uint16\_t. You are truncating your data to 8 bits before displaying it. One other note, the 74HC595 has a maximum total drive current of 50mA. Your circuit will draw around 90mA for each of the 74HC595's if all of the LEDs are on. You may want to change the resistors to something bigger (510 Ohm, for example) to avoid this problem. Of course that will make the LEDs dimmer, so it's a tradeoff. Here's your project in 123D Circuits. You can simulate it in the browser and look at the code running in the Arduino there.

# Answer
> 1 votes
notice the `uint8_t val`. You are truncating the 16-bit number back to 8 bit.

One way of fixing this is to split the 16-bit number before calling shiftOut.

```
shiftOut(dataPin, clockPin, MSBFIRST, highByte(numberToDisplay));
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(numberToDisplay));

```

# Answer
> 1 votes
I agree with Gerben. But Byte datatype will not help you, since Byte type is an unsigned 8-bit type (the same as uint8\_t). Why don't you try this header:

```
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint16_t val)

```

Or follow Gerbens idea, just using out of the box shiftOut routine. It shifts 8-bit variables, so you shouldn't need to re-implement the routine.

Regards.

---
Tags: arduino-uno, shift-register
---


title: Trying to understand Arduino products

text:
# Question
Title: Trying to understand Arduino products
**Background:**

I am new to Arduino world, and I like to buy a board. I am a bit confused how Arduino products are being sold. Coming from Raspberry world, it seems that I don't know what actually Arduino is.

**Question**:

I am trying to understand what is it that this product offers:

.

1. Why it says "**For** Arduino UNO R3"? 2. Isn't it actually an "Arduino UNO R3"? So why it says "For"?
2. What are MEGA328P and CH340? Does "Arduino UNO R3" comes with other chipsets?

# Answer
> 4 votes
It sounds to me like an Arduino Uno **clone**.

> Why it says "For Arduino UNO R3"?

I would read that as "For Arduino UNO R3 **projects**" (ie. Uno-compatible).

> Isn't it actually an "Arduino UNO R3

No, it's a clone. Or not really a clone (see below) because they used different hardware. It is compatible with the Uno in most respects.

> What are MEGA328P?

That is the **main** chip on the board (actually an Atmega328P).

> and CH340?

They have saved money by using a CH340 USB-to-serial chip instead of the Atmega16U2 used on genuine Uno boards. You may need to install a different driver to make that work. I disagree with the other answer(s) that this is a separate board or chip. It is clear from the photo of the chip near the USB socket that it is a CH340 chip there. See, for example https://hackaday.com/tag/ch340/ from which I quote:

> The cheapest USB to serial chip on the market appears to be the CH340G, available for 20-40 cents apiece from the usual retailers. There is, however, almost no English documentation, and the datasheet for the CH340 family doesn’t include this chip

They used it because it is cheap.

> Does "Arduino UNO R3" comes with other chipsets?

Yes the **genuine** one comes with an Atmega328P (main processor) and Atmega16U2 (USB interface).

---

Having said all that, the Uno is a good all-rounder starting board to get going with Arduinos.

Note that they are using the SMD (surface mounted) main processor chip. If you fry it you need to replace the whole board, not just the chip. However the entire board is quite cheap. :)

# Answer
> 1 votes
The board in the picture is not an official Arduino board. It is a clone. You will note that in the picture the board does not say "Arduino" It may be 100% compatible or it may not, you have to decide if the low price is worth it.

If you want an official board you should check either http://arduino.cc or http://arduino.org to find official distributors. (see this question for information about why there is both arduino.cc and arduino.org).

---
Tags: arduino-uno
---


title: I2C_Anything String / Char Array issues

text:
# Question
Title: I2C_Anything String / Char Array issues
I've been working with the lovely I2C\_Anything.h (thanks to the great work and support from Nick over at http://www.gammon.com.au/forum/?id=10896&reply=9#reply9).. All working great, I was using Serial communication between Teensy 3.1 & mini pro but looking to replace with I2C - I was sending a file name across that was fine, but not managing to figure it out with the I2C\_Anything technique.. here's some snippets:

**MASTER**

```
const uint8_t MaxMP3Name = 13;
//====================================
// DATA STRUCTURE FOR MP3 SLAVE
//====================================
struct SEND_MP3_STRUCTURE{
  char Filename[MaxMP3Name];
  uint8_t VolLeft;
  uint8_t VolRight;
  uint8_t Command;
};
SEND_MP3_STRUCTURE txMP3;

#define MP3_SLAVE_ADDRESS 77

const uint8_t PlayFile = 1;
const uint8_t PauseFile = 2;
const uint8_t StopFile = 3;

... etc

//#################################//
//##  SEND MP3 COMMAND           ##//
//#################################//
void sendMP3Command(String MP3File, uint8_t Command) {
  char *TextArray[MaxMP3Name];
  MP3File.toCharArray(TextArray, MaxMP3Name);
  txMP3.Filename = TextArray;
  txMP3.VolLeft = VolLeft;
  txMP3.VolRight = VolRight;
  txMP3.Command = Command;
  Wire.beginTransmission(MP3_SLAVE_ADDRESS);
  I2C_writeAnything(txMP3);
  Wire.endTransmission(true);
}

...etc

```

... not entirely sure what i'm doing, I've tried most variations (using String in the struct vs char \*Filename\[\] and various other attempts).

**SLAVE**

```
const uint8_t MaxMP3Name = 13;
//====================================
// RECEIVE DATA FORMAT
//====================================
struct RECEIVE_DATA_STRUCTURE{
  char Filename[MaxMP3Name];
  uint8_t VolLeft;
  uint8_t VolRight;
  uint8_t Command;
};
volatile RECEIVE_DATA_STRUCTURE RXdata;
#define SLAVE_ADDRESS 77
volatile uint8_t newData; // flag to detect I2C activity

// MAKE GLOBAL VERSIONS
String RX_Filename;
uint8_t RX_VolLeft = 30;
uint8_t RX_VolRight = 30;
uint8_t RX_Command = 0;

... etc

//#################################//
//##  MASTER SENDING US DATA     ##//
//#################################//
void onReceiveEvent(int numbytes){
  if(numbytes == 16){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

... etc

void loop(){
  if (newData==2){// I2C received Data
    RX_Filename = RXdata.Filename;
    RX_VolLeft = RXdata.VolLeft;
    RX_VolRight = RXdata.VolRight;
    RX_Command = RXdata.Command;
    newData = 0; // Clear data sent marker
  }
}

... etc

```

Hopefully you'll be able to see pretty quickly what i'm trying to do and the method I should be using to do it..

Thanks for any insights

Cheers

Andy

---

Sorry, still getting used to this comment vs editing questions business, didn't realise it would add my comment when I hit enter so it cut me off... here's full comment:

---

Hiya Nick, thanks for your suggestion, How you've recommended it is actually how I tried it originally (I don't like using Strings either) - which just ends up giving me the error:

`"invalid conversion from 'volatile char*' to 'const char*' [-fpermissive]"`

(on the Slave) - obviously the RXdata is updated during the interrupt so can't leave it out (despite the fact it compiles - but doesnt work)..

I got it working soon after I posted by breaking down the filename in the struct to separate chars, then assembling back into char array in a function I made.

That seemed to work fine, but only if I added null char at as the last char (0x00) - I can get the char `Filename[MaxMP3Name];` working, but only if I lose the volatile declaration, and it skips the last char.

Thanks for any further help Nick, I really appreciate all you do for the community and I know you're the best guy to help me (not to take anything away from anyone else that wants to jump in ;)

## Current solution i'm using that avoids the volatile erros

Obviously could be a for loop etc but I wrote it out this way just to debug and see where the issue was. Not perfect, but breaking it down this way seems to be overcoming the issue of trying to do anything with the volatile variable. (and i've got so much to figure out for so many other parts of the project that I was thinking i'd come back to it later once i'm done with other bits).. Cheers

```
//#################################//
//##  SEND MP3 COMMAND        ##//
//#################################//
void sendMP3Command(String MP3File, uint8_t Command) {
  char FileName[8];
  MP3File.toCharArray(FileName, MaxMP3Name+1);
  txMP3.File1 = FileName[0];
  txMP3.File2 = FileName[1];
  txMP3.File3 = FileName[2];
  txMP3.File4 = FileName[3];
  txMP3.File5 = FileName[4];
  txMP3.File6 = FileName[5];
  txMP3.File7 = FileName[6];
  txMP3.File8 = FileName[7];
  txMP3.VolLeft = VolLeft;
  txMP3.VolRight = VolRight;
  txMP3.Command = Command;
  StartMicros = micros();
  Wire.beginTransmission(MP3_SLAVE_ADDRESS);
  I2C_writeAnything(txMP3);
  Wire.endTransmission(true);
  EndMicros = micros();
  //Serial.print("MP3 Packet Size: "); Serial.println(sizeof(txMP3));
  //Serial.print("Sending Command To MP3: "); Serial.print(MP3File);Serial.print("   Command; "); Serial.print(txMP3.Command);Serial.print("   Time; "); Serial.print(EndMicros-StartMicros);Serial.println("uS ");
}

```

... Oh, and on the slave end, I changed the numbytes to be sizeof, but as you say Nick, not even any need for that, i'm not using it on any of my other I2C slaves all running in the project (5 X MCU core system). the filename is then pulled from the I2C array in a siimilar (debugging) way as the master packs them in

```
//##############################//
// RECONSTRUCT FILENAME
//##############################//
String getFilename(){
  char FileName[] = {
    RXdata.File1,
    RXdata.File2,
    RXdata.File3,
    RXdata.File4,
    RXdata.File5,
    RXdata.File6,
    RXdata.File7,
    RXdata.File8,
    0x00
  };
  return FileName;

}

//#################################//
//##  MASTER REQUESTING DATA     ##//
//#################################//
void onRequestEvent(void){
    I2C_singleWriteAnything(TXdata);
    newData = 1;
}

//#################################//
//##  MASTER SENDING US DATA ##//
//#################################//
void onReceiveEvent(int numbytes){
  if(numbytes == sizeof RXdata){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

```

# Answer
This part looks weird:

```
void sendMP3Command(String MP3File, uint8_t Command) {
  char *TextArray[MaxMP3Name];
  MP3File.toCharArray(TextArray, MaxMP3Name);
  txMP3.Filename = TextArray;

```

You have made an array of 13 pointers to strings. This is not what you want. You want the file name to end up into `txMP3.Filename`.

This would be closer:

```
void sendMP3Command(String MP3File, uint8_t Command) {
 MP3File.toCharArray(txMP3.Filename, MaxMP3Name);

```

Personally I wouldn't be using the `String` class at all, but that should be better.

---

Now:

```
void onReceiveEvent(int numbytes){
  if(numbytes == 16){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

```

Are you **sure** it's 16 bytes? What if you change the struct? Let the compiler do the thinking for you:

```
void onReceiveEvent(int numbytes){
  if(numbytes == sizeof (RXdata)){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

```

---

> How you've recommended it is actually how I tried it originally (I don't like using Strings either) - which just ends up giving me the error "invalid conversion from 'volatile char\*' to 'const char\*' \[-fpermissive\]" (on the Slave)

This minimal example compiles OK:

```
#include <Wire.h>
#include <I2C_Anything.h>
const uint8_t MaxMP3Name = 13;
struct RECEIVE_DATA_STRUCTURE{
  char Filename[MaxMP3Name];
  uint8_t VolLeft;
  uint8_t VolRight;
  uint8_t Command;
};

volatile RECEIVE_DATA_STRUCTURE RXdata;
volatile uint8_t newData; // flag to detect I2C activity

void onReceiveEvent(int numbytes){
  if(numbytes == sizeof RXdata){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

void setup()
{
}

void loop()
{
}

```
> 1 votes

---
Tags: arduino-uno, c++, i2c, string, struct
---


title: Transient and reverse current

text:
# Question
Title: Transient and reverse current
Does anyone know (1) how much transient current can be output from a pin and (2) how much (and how long) reverse current an output pin can take? For instance, consider the following circuit (driven by a series of 10 ms pulses at 5V):

```
  o----------------
       |          |
       = 10µF    1k LOAD
       |          |
  o----------------

```

which would be a classical filtered (smoothed) PWM circuit. When the pin goes to +5V, the capacitor would act like a short and allow very high current (assuming about 20 ohm impedance, maybe 250 mA) for a millisecond or so. Similarly, when the voltage drops to 0V, the charged capacitor will discharge, leading to a reverse current until it bleeds through the load. Will either of these damage the diodes in the pin or even the IC? Thanks. (Worse comes to worse, does this mean that a resistor and diode are needed to protect the pin?)

**More info**

1) It's 10µF. 10 pF would be useless in a power supply, it would only store 0.05 µC of electricity at most, which would only be able to smooth the output for a few microseconds.

2) The load is resistance, 1 k ohms.

3) A diode would be handy if you wanted to prevent reverse current, since you could put a much larger diode outside than the protective diodes in the Arduino. They are classically used with motors (inductive load) as a clamp diode.

4) My general question is about high transient current or reverse currents. A capacitor is just an example of a situation that could cause this. Another example would be a pin that is putting out only occasional (for example) 1ms long 100 mA pulses, separated by many seconds. Such a circuit is really not delivering much power, but for very short periods it exceeds that recommended 40 mA. Would this burn out the pin or not?

5) A capacitor in parallel with the load is pretty much the classic filtered DC power supply. Open any wall wart you have and you'll see a transformer, a rectifier and several large (electrolytic) capacitors (along with a couple small ones) and a voltage regulator. Closer to this example, say you want to deliver current at 2 volts DC. You can do this by alternating 2 ms pulses (at 5V) with 3 ms at 0V. Then have a capacitor in series to smooth it to closer to DC, making it more like analog output. That is, in fact, exactly how adjustable power supplies often work.

# Answer
It sounds like you are trying to make a digital to analog converter driving some type of load. Look at this link: http://emesystems.com/BS2PWM.htm It will give you a start. Please note they use an opamp as a buffer.

This 'buffer' has a very high input impedance and a low output impedance. It can drive from a few mills to over an amp depending on the opamp chosen. Additional circuitry can get you into thousands of amps if desired. The schematic is a 2 pole filter originally designed for the Stamp microcontroller.

The filter soothes it out but adds a delay on the final output value (settling time). The greater the filter capactance the lower the ripple and the slower the response. You can add another pole to filter if you want.

As a bit of information from an old semiconductor guy absolute ratings are just that. If you exceed them even for a few nanoseconds you can be sure you damaged the device, you just do not know when it will fail.

I have seen a lot of microcontrollers damaged because of capacitors connected to the pins, power excluded, doesn't matter if the pin is input or output. When the power supply collapses it will inject current into the microprocessor substrate possibly damaging it.

Good Luck
> 1 votes

# Answer
I have had fairly lengthy discussions with Mike Cook from the Arduino forum about this sort of thing. I asked, for example, if it was OK to drive LEDs by PWM providing the duty cycle was short enough that "on average" the pins put out a current in specified range.

His answer always is: **no**!

The datasheet does not say you can exceed the *absolute maximum ratings* for a certain amount of time (like 1 µs). You are not supposed to exceed them at all.

It doesn't take a particularly large series resistor to limit current to the recommended 20 mA (250 Ω at 5 V).

Now you can probably "get away with" not using it, but you are basically moving into unsupported territory. If the chip fails after a year, don't blame the manufacturer.

---

> It's 10 microFarad = 10mmF. 10 picoFarad would be useless in a power supply

According to Wikipedia:

> A "micro-microfarad" (μμF, and confusingly often mmf or MMF), an obsolete unit sometimes found in older texts, is the equivalent of a picofarad.

Your use of mmF as a replacement for µF is confusing. I suggest either copying and pasting "my" µ from this post, or using a simple "u" instead.

> ... useless in a power supply

Surely you are not seriously suggesting that you are going to make a power supply, powered by an Arduino output pin?

I am presuming not, so perhaps if you describe your application?
> -1 votes

---
Tags: arduino-uno, pins
---


title: SSH and web interface broken on Yun

text:
# Question
Title: SSH and web interface broken on Yun
I have two Arduino Yuns that are not accessible *at all* on the network. I can't go to the arduinoname.local, ssh arduinoname.local, as I previously could. I know at least one it working because it sends emails as I programmed it, yet it seems there is no longer a way to ssh into it. Any ideas?

Yes, I have unplugged, plugged in the router, and the yuns.

# Answer
> 1 votes
It turns out the problem is a fairly common one - Actiontec wireless access points break this way when set to Both, not AES - see https://superuser.com/questions/522781/unable-to-ssh-from-any-wireless-ip-to-another-wireless-ip-on-home-network

Apparently on other routers this bug is marked as a feature, "Wireless Isolation" or something.

---
Tags: wifi, arduino-yun, ssh
---


# Question
Title: Reasons why it is not OK to connect a relay directly from an Arduino digital pin
After looking into various schematics on controlling a relay via an Arduino, I have noticed that, most of the time, transistors are used to switch the separate supply into the relay coil rather than directly supplying the relay with the 5-Volt output from the I/O pin of the Arduino. For example, I have a 5-volt DPDT relay and also a small dc motor. I want to drive both directly from my Arduino UNO (SMD clone) with an Atmel328 processor? Would it be advisable to proceed?

If not (most likely):

1. Can someone give a detailed explanation and might as well important cautions on current limits and stuff?
2. How can one control such components without risking the Arduino? What are some common means to accomplish this?
3. What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

I'm just a beginner who wants to be extremely cautious. Thanks.

# Answer
> 10 votes
Processor pins have strictly limited current drive capability.

* The rated values may vary depending on whether you want a high or low drive.
* Some processors will supply only a few mA and the most you will usually officially get is in the 20 to 30 mA range.
* There is usually a total current limit for the processor and only a few pins can provide peak current simultaneously.
* Processor pins have significant effective resistance and a high voltage will "drop" as increasing current is drawn and a low voltage will rise as load increases. Pins MAY be specific with a maximum short circuit current but at that point a high pin will be pulled low and a low pin will be pulled high so short circuit current has limited applicability.

Even if you have a say 25 mA per pin rated processor the power available is small. 25 mA · 4V say (1V drop on 5V Vcc) = 100 mW. Most motors will take more than that and only very small motors will run well when powered only by a pin.

Electric motors and inductors will generate significantly high voltages when current is interrupted - voltages of tens of volts can easily result and 100+ volts can happen. Connecting a motor of inductor to a processor pin directly is an invitation to destruction. Murphy will often oblige.

---

A transistor (bipolar or MOSFET) that will drive typical hobby motors costs 10's of cents (or free from scrapped equipment) and allows the port pin current drive to be buffered and "amplified". Use of a transistor or other buffer is an extremely good idea if you have one or a few processors and do not wish them to die semi-randomly.

**MOSFET motor driver** \- **from here** \- section 8.

Voltages and part numbers are for their example - select to suit.
A NPN biploar could be used with the addition of an input resistor to the transistor base.

Bidirectional driver - if you want the driver to be able to drive a load high and low this circuit will work. from here
The input gate is in this case the internal processor driver. The two MOSFET gates connect directly to the processor pin. Vdd should usually be no higher than processor Vmax\_drive\_out. Slightly higher can be made to work with suitable design. Much higher voltage loads can be driven with this circuit (or similar) plus one extra transistor.

---

A buffer such as a ULN2803 (and other family members) will drive 8 channels x 500 mA/channel and several can be paralleled.

---

A ULN2803 is essentially 8 x "Darlington" transistors with emitters connected to a common ground, 8 x "open collector" (unconnected) collectors, and 8 flyback diodes to deal with over voltage spikes (use optional). (There is a ULN280x family with slightly different input characteristics).

This device provides a reasonably priced means of providing 8 x 500 mA pull down drivers. A load connected from an output to V+ is turned on when the input pin is driven high. Once you've used one a few times you'll find them trivially easy to use and very useful. (There is also a ULN200x family with 7 channels per package).

YouTube "how to" video

---

Driving a stepper motor

Also here

---

Driving small DC motors \- and quite a lot else.

A zillion examples

Digikey - available in 1's if desired $0.72/1, $0.29 in 1000's.

**ULN2803 datasheet**

---

For sale at Sparkfun \- can be had rather cheaper but these are available

# Answer
> 8 votes
The recommended output (source or sink) from an I/O pin is 20 mA. The absolute maximum is 40 mA. Your relay coil is likely to consume more than that, particularly when it initially energizes. This will damage your output pin. Then it will eventually fail.

> Nothing seems to be amiss by far.

No, not yet. :)

> How can one control such components without risking the Arduino? What are some common means to accomplish this?

Use transistors or MOSFETs.

> What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

Anything that exceeds the maximum voltage or current limits as documented in the datasheet. Coils (eg. in relays and motors) in particular are likely to have a high reverse voltage when they are turned off, which is why you need a snubber diode.

> Would it be advisable to proceed?

It would be advisable to take heed of what I wrote above, and to read the many, many articles on the Web about how to drive motors and relays from an Arduino. You are not the first person to attempt this.

# Answer
> 5 votes
Have a look at the simple circuit on this PDF from the Arduino Playground. It shows a single transistor to drive a small relay.

As Russell says in his answer, a ULN2803 or similar is a chip which will allow you to drive several small relays, which is neater than using several transistors, if that's what you want.

(Also note the diode "D1" in the circuit I linked - you need this, it's to protect the transistor from eventually being damaged by inductive spikes generated when the relay turns off. Some of the ULN-style chips have this diode built in, which is why you don't always see it in schematics.)

# Answer
> 5 votes
To really protect your arduino it's worth putting a photo-coupler on the pin and driving your circuit that way. Then no stray inductive charge or short can affect the arduino.

They are also called OptoIsolators or Optocouplers.

http://forum.arduino.cc/index.php?topic=143954.0

# Answer
> 4 votes
Let us look as some basic's, these seem to be the basis of a lot of questions:

A capacitor when power is switched on draws a huge amount of current that tapers off as it gets charged. This curve is also called the RC time constant (this is close but not exact "http://www.electronics-tutorials.ws/rc/rc\_1.html" will give a better explanation).

When switching off a capacitor discharges at an exponential rate (RC time constant) depending on the value, charge voltage and the load. This makes them good for holding power for a short time when the power fails.

An Inductor draws nothing when first switched on but the current increases exponentially until its voltage reaches the supply voltage.

When switched off the inductive field in the inductor collapse causing the polarity to reverse. The voltage will rise unlimited until typically something externally limits it. The faster it is turned off the quicker the rise time and voltage. Energy will cease to flow when the inductive charge is dissipated. Guess where this current goes when the inductive load such as a relay is connected to a port pin?

For this reason you need to put a diode (commonly called a fly wheel diode) across the inductive load. Google for: "inductor/capacitor charge curve" you will find a lot of nice graphs explaining this. This diode is not necessary if you use an appropriately rated MOSFET (UIS). The UIS (Unclamped Inductive Spike) information is in the MOSFET data sheet. If you look at the circuit it has the cathode + connected to the most positive side of the power supply. In this configuration it will not conduct unless the voltage is reversed (when the inductive load is switched off).

Another common misconception is you can load a microprocessor I/O to the maximum. This is bad design. They give you a maximum per pin, per port and for the chip. At room temperature you will probably get away with it for a while.

Let us assume we have a port with a 40mA load. The output is 0.005 from the power rail. Using Ohm’s law we are dissipating 20 milliwatts of power on one pin. At this rate of loading it does not take long to over heat the device because of internal power dissipation.

When the output pin is changing state it draws more current because it has to charge or discharge its internal and the external capacitance, ‘more heat’, more speed ‘more heat’.

If you look some of the specs will give you a maximum temperature, it is for the junction on the die, not the case temperature. Plastic is a poor conductor so heat sinking the package does not do a lot. Now consider this along with the ambient temperature. The ratings are given typically with the device at 25C, guess what happens when it gets warmer.

Have fun,

Gil

---
Tags: arduino-uno, relay, safety
---


# Question
Title: How to Create a water screen with solenoid valve in arduino
I want to make a water screen. I will create character with solenoid valve. Sometimes sequential valve will pass to water, sometimes not pass.

And I will create some shape or character.

But I don't know how can I create this character with Arduino.

Do you have any good idea ? Can you help me ?

# Answer
You can refer to this page for the generic actuation (iow Arduino board + relays shield + power supply for the valves), but that leaves one problem open: timing.

To draw something on a wall of water, you need to make sure that the water flows with a known, constant speed (unless your wall is very tall, I would ignore the effect of gravity, if the initial speed is high enough).

Maybe it can be achieved without this extra step, but to play it safe, I'd also add a pump that feeds all the valves.

This will ensure that you will have a known pressure/speed of the water, thus being able to calculate the timing of the valves.

You can use one of the relays to control also the pump. Notice also that most likely an arduino UNO/Nano or equivalent will not be sufficient, as you will get relatively few lines.

An ArduinoMega2560 or DUE have far more GPIOs.
> 2 votes

---
Tags: arduino-mega
---


title: Arduino Uno + 12 relays

text:
# Question
Title: Arduino Uno + 12 relays
I'm using a basic relay and I want to use 12 like this. Each one needs 50 milliamps, but the Arduino can supply only 300 milliamps. What can I do?

# Answer
> 2 votes
You should never drive relays direct from an Arduino. You always need a driver circuit since each OP pin can only reliably provide up to 25mA.

Every relay needs (at least) an NPN transistor and a flyback diode. Follow the myriad of examples for controlling one relay on an Arduino and multiply it by 12.

You might like to make things smaller and more manageable by using a paur of ULN2303 chips with 6 darlington drivers in each instead of using 12 discrete transistors.

---
Tags: arduino-uno, relay
---


title: LM35 at higher temperatures

text:
# Question
Title: LM35 at higher temperatures
I have a question concerning the LM35 sensor: if I'm not too concerned about accuracy (I don't mind having 2 or more degrees off), is it possible to use the LM35 sensor at higher temperatures than the normal range? The project that I'm thinking of using this sensor, temperatures should reach 200 degrees, maximum.

Thanks!

# Answer
> 4 votes
No, you cannot. The LM35 is rated for an **absolute maximum** junction temperature of 150°C. Any higher than that and you will damage it.

For temperatures above that you are better using a thermocouple.

---
Tags: temperature-sensor
---


# Question
Title: less expensive alternative arduino board to CMUcam4
Is there any similar (less expensive alternative) arduino board to CMUcam4?

CMUcam4:The CMUcam4 is a fully programmable embedded computer vision sensor. The main processor is the Parallax P8X32A (Propeller Chip) connected to an OmniVision 9665 CMOS camera sensor module.

# Answer
> 1 votes
I have used OpenCV on Intel Galileo for doing recognition of sub images from a larger image (given the cover of a magazine, identify it in a pile of magazines partially covering it). The frame rate is far from stellar. I haven't tried with Edison but it should be much faster, as it's an Atom core vs the pentium-like Quark. OpenCV is optimized for x86.

I used a normal webcam to capture the image, so this solution gives more flexibility in the choice of the sensor.

You could have a look at ROS on Edison.

---
Tags: hardware
---


title: Arduino Uno and I2C

text:
# Question
Title: Arduino Uno and I2C
How does the arduino uno talk with i2c? i saw the circuit and it use analog input pins but as far as i know you cant use them as output. How does he send data over those pins?

# Answer
> 2 votes
Most pins on the Arduino are multi-function and can be switched into different modes. Analog is just one of those modes. I2C is one of the available modes for the pins that A4 and A5 are connected to.

---
Tags: arduino-uno, i2c
---


# Question
Title: Problem with structs and pointers(?) - Mega with QueueArray
I'm writing a sketch to run on a Mega that builds up an array of timestamps (using the QueueArray library and DS3231 library). I'm having a problem where a struct I'm defining and then queueing is always referring to the first in the list. The relevant bits of the code looks like this:

```
#include <QueueArray.h>
#include <DS3231.h>
struct payload_t
{
   unsigned long timestamp;
}

QueueArray <payload_t> dataQueue;
DS3231 clock;
RTCDateTime dt;

void setup() {
   clock.begin();
   clock.setDateTime(__DATE__, __TIME__);
}

void loop() {
    payload_t dataPayload;
    dataPayload.timestamp = getTimestamp();
    dataQueue.enqueue(dataPayload);

    payload_t tempItem = dataQueue.dequeue();

    /**
     * At this stage, the dataPayload.timestamp is correct,
     * but tempItem.timestamp will always show the value from
     * the first item in the queue
     */

    sleep(1000);
}

unsigned long getTimestamp()
{
    RTCDateTime dt = clock.getDateTime();
    return dt.unixtime;
}

```

As per the comment in the main() loop, the first time a packet is added to the queue, the timestamp matches. For subsequent items, the value retrieved from the queue always gives the timestamp from the first item in the queue.

I feel this is my C knowledge letting me down with something basic, but can anyone point me in the right direction?

# Answer
> 2 votes
It's not your C knowlede letting you down, it's just that you haven't gotten used yet to the weirdness of the arduino ide/compiler.

You do not need to create a main() function.

You need to create a loop() function.

main() is already defined and calls loop() in a loop.

Check any other sketch and you'll notice that it usually defines setup() and loop(), almost never main().

You must put in the setup function all the code that needs to be executed once (settings and initializations) and in the loop() function whatever needs to be executed iteratively.

Also, leave declarations out of loop() unless you want such variables to have scope (and life) limited to only one round of loop()

---
Tags: arduino-mega
---


# Question
Title: Best way to make an Arduino switch 8 12V LED's
I'm trying to switch multiple 12V LED's with my arduino, based on the input of a (serial-in parallel-out) shift-register.

The 12V comes from a separate battery, so I can use 8 mosfets to get my 12V, and I might even put a parallel-in serial-out shift register in between.

But I'm hoping that there is a cleaner way of doing this. Is there some kind of component that combines a shift register and a mosfet?

Any ideas on the best way to solve this?

# Answer
> 1 votes
I would recommend using something like the STP08DP05. ST Microelectronics makes 16 and 24 bit versions as well. You can also find TI and NXP parts that will do basically the same thing.

With these parts you can hardwire your max current value with a resistor to make sure you don't overdrive the LED. Just because you can drive the LED at 90mA, doesn't mean you should... it will probably be way to bright. The IC's can also be daisy-chained to your shift register and you can drive very large strings of LEDs... or use them for RGB LEDs.

Hope that helps!

**EDIT - Based on Comments**

There are a couple of options. Note the Vdd represents the voltage supply to the IC itself and the nominal operating voltage is 3.0V up to 5.5V (I'm honestly not sure why they even added 7V as a max value when they specify 5.5V on the next page).

So, Vdd is not necessarily the voltage that your LED's are driven at. You can drive the LEDs at 12V (if you need to) and add a series resistor to the OUT pins of the IC's to dissipate the extra heat.

You would probably be fine with 200 ohms per pin. If you set your current at 20mA, and assuming a 2.2V drop through the LED, that would give you approximately 5.8V at the OUT pins and the IC wouldn't have to dissipate much heat in terms of power.

However, if you don't need to drive them at 12V then I wouldn't bother. Usually the forward voltage of an LED is 1.8 to 3.3V and you don't need 12V. However, if you are driving a lot of them then it may be easier to use the 12V. There are always trade-offs.

---
Tags: power, shift-register, mosfet
---


# Question
Title: pySerial and serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
I'm having some trouble getting my arduino uno to communicate with a simple python script through pyserial.

Lets start with my arduino sketch:

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

byte i = 0;
void loop() {
  Serial.println(i);
  i = i + 1;
}

```

Really dead simple. It just spews the numbers from 0 to 255 over and over again. It works fine in the arduino serial monitor and gets me the expected result.

The python script comes from:

http://playground.arduino.cc/Interfacing/Python

```
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
while True:
    print ser.readline()

```

However running this script gets me:

```
$ python test.py
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print ser.readline()
  File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 460, in read
    raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)

```

I am using ubuntu 14.04 and python-serial\_2.6-1build1\_all.deb

# Answer
> 1 votes
This may be a kernel bug. See here: https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/1501240

The workaround it seems is to use kernel `3.13.0-63-generic`.

You can change the kernel for a one-time boot by holding shift while starting up. To make the change persistent, you need to edit `/etc/default/grub`: https://askubuntu.com/questions/262965/grub-timeout-set-to-0-cant-access-grub-menu-anymore?rq=1

---
Tags: arduino-uno, serial, python
---


title: Stuck on upload

text:
# Question
Title: Stuck on upload
**I just bought the SmartEverything FOX Board which is Arduino compatible** http://www.smarteverything.it/wp-content/uploads/2015/10/SmartEverything-User-Guide-Ver-1.01.pdf and simply tried to get started with it.

**My OS is Ubuntu 14.04, my laptop DELL XPS 13 bought in 2014**

**I cannot upload sketches on it, when I try, it gets stuck on uploading**, whether it is a basic script (blinkRBG) or even the default one with empty setup and loop methods, my laptop processor keeps running at 100% and nothing happens. **The board does not do anything, tx/rx leds do not flash.** **I can access to it with a Windows 7 laptop (UPDATE: and another UBUNTU laptop) from a frien**d, I could upload the basic blinkRGB sketch. If I try to upload from my Ubuntu laptop after, it does erase the contents and stop the blinking but nothing follows.

When I try to upload, I only get the compiling logs: Quote

```
Sketch uses 13,368 bytes (5%) of program storage space. Maximum is 262,144 bytes.

```

**I could still upload sketches to another board from my Ubuntu laptop: to an Arduino micro.**

**I am connecting directly from my board to my laptop through USB 3.0**, I don't have USB2.0 plugs on my laptop, and I currently don't have any programmer device.

I tried with different versions of arduino IDE (1.6.4 1.6.5 nightly), same issue every time. The IDE sees that my board is connected on /dev/ttyACM0

I tried to run in command line but it gets stuck as well Quote /home/jcharlet/.arduino15/packages/arduino/tools/bossac/1.6-arduino/bossac --port=ttyACM0

**I've been googling the world but could not find anything, could anyone help me to troubleshoot it please?**

# Answer
Moved to another board more suitable to our needs, but @sm4rteverything (Twitter) gave us the following solution (not tested):

> This is a known bug of the bootloader.
>
> to fix this U need to download the one i attach in this email with the ATMEL-ICE tool. http://www.atmel.com/tools/atatmel-ice.aspx
>
> Copy the attched file under: \Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme (Linux) C:\Users\\AppData\Roaming\Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme (Windows)
>
> last follow these three simple step Connect the ATMEL-ICE on the SWD J1 connector (pin 1 on top-rigth , the pin on eon cabel is the red one)

> select on Arduino IDE to connect to ASME via atmel-ice (board menu) tool-\>burn bootloader
> 0 votes

---
Tags: uploading
---


title: Arduino Wire.onReceive(handler)

text:
# Question
Title: Arduino Wire.onReceive(handler)
It says in the description of the function:

> Registers a function to be called when a slave device receives a transmission from a master.

So when does it exactly called? I guess it's not been called for each byte, but its the meaning of receiving transmission from the master. Does it called for each byte? When the master use transmissionBegin? transmissionEnd?

# Answer
> 1 votes
It is called at the end of the reception of the entire packet - i.e., when the slave receives the final `STOP` bit. It is passed the number of bytes received (which is the number of bytes you requested since I2C has no way of being able to work out if it is actually receiving real data - see here) as the only parameter so you know how many bytes you can then read from the internal buffer without overflowing it.

---
Tags: i2c
---


title: How to add more inputs on Arduino?

text:
# Question
Title: How to add more inputs on Arduino?
I'm building an instrument that has 72 buttons that can be pressed. Now I'm planning on using Arduino to send data to computer via USB cable about which buttons are pressed. So I figured I'd need 72 different input pins, one for each button(the button is connected to the Arduino via a wire). But, the Arduino doesn't have 72 input pins, so this seems kind of impossible. So what I'm looking for is a way to somehow extend the number of pins on the Arduino or another way to solve my problem. Maybe it would be better to use another micro-controller? Maybe using analog inputs for this is better?

If it makes any difference, the max number of buttons that can be pressed at once is 10.

# Answer
There is a whole concept you need to learn:

# Matrix

By using a matrix arrangement you can, using (8 + 9 = ) 17 IO pins you can create a grid of 8 × 9 buttons, which is 72 buttons.

This method is used all the time for keypads, and you can read more here: http://playground.arduino.cc/Main/KeypadTutorial

To further reduce the number of IO pins used you can replace the 8 IO pins for one dimension of the matrix with a 3-to-8 decoder, since only one pin is ever active at a time. That reduces it down to just 12 IO pins for the whole shebang.
> 2 votes

# Answer
There are quite a few GPIO expanders available that you could use to increase IO lines in your circuit, mostly running off I2C. Just search "I2C GPIO" on your favorite electronics site/google/ebay

Examples: https://www.sparkfun.com/products/8130 \[No affiliation\]

If every sensed key has to be on a GPIO, then this is the way to go.

Having said that, with IO expanders, you will find that sensing large number of keys still takes lots of code on your uC. With some extra software effort, you could eliminate expanders, and rather scan a key matrix as suggested by Majenko
> 2 votes

# Answer
You may try making something like a button grid, Like the ways Leds are connected in a Led cube, For example - In a 4\*4\*4 led cube, u don't need 64 pins, but a smart connection of all on x and y axis,

what i mean to say is, you need to make rows and columns of button, But i don't think this idea would work cause buttons are totally different from leds, But then also try searching for led cube circuit, let it spark a new idea in your mind.
> -1 votes

---
Tags: usb, input, pins
---


title: DC motor kickback diode?

text:
# Question
Title: DC motor kickback diode?
I have the following circuit:

And I know it works and that the diode protects the negative voltage from flowing back into the transistor. This is essentially the circuit:

Could someone illustrate what happens when the motor stops? The current normally flows from 5V to GND (and the electrons from GND to 5V, but this doesn't matter (I think?)), and then it reverses when you switch it off, so current comes out of the top of M1, and then what? I don't get it here.

# Answer
> 2 votes
While the motor is being powered the current flows from Vcc to GND as in this circuit:

When the power is disconnected (such as the transistor in the ground connection in your circuit is switched off) amongst other things (including the collapsing of magnetic fields) the spinning of the motor turns it into a generator. The power generated is the opposite of what was being provided to make it move. As the magnetic field of the coils collapses additional high voltages are also generated.

When disconnected the motor can be represented as a battery connected backwards. In that configuration the current flows from the + of this hypothetical battery through the diode into the - thus stopping any current from going elsewhere, as in this circuit:

---
Tags: arduino-uno, motor, transistor, h-bridge
---


# Question
Title: How to use Infra Red (IR) to reset arduino board
I am a big noob I know that

but can this code be used to reset arduino board (instead of pressing the usual reset button on the board)

I want to reset the board as If am pressing the reset button using IR

```
int receiverpin = 2; // pin 1 of IR receiver to Arduino digital pin 2
#include <IRremote.h>
IRrecv irrecv(receiverpin); // create instance of irrecv
decode_results results;
void setup()
{
irrecv.enableIRIn(); // start the receiver
}
void(* resetFunc) (void) = 0; //declare reset function @ address 0

void loop()
{
 if (irrecv.decode(&results)) // have we received an IR signal?
{
if(results.value == 0x2FD847B) //if the button press equals the hex
{
  resetFunc();
}
{
irrecv.resume(); // receive the next value
}
}
}

```

# Answer
> 1 votes
Kind of, yes. That doesn't actually reset the Arduino, it just sends the program to address 0.

There are two other ways of performing the reset that do a proper full reset:

1. Enable the watchdog timer and let it time out to reset the CPU.
2. Connect an IO pin to the RESET pin - keep it in INPUT most of the time but set it to OUTPUT and LOW when you want to reset.

By just jumping to address 0 you aren't resetting the internal peripherals and registers to their reset state, so things like timers and such will still be running when they shouldn't be, etc. It's better by far to do a real reset instead of just jumping to 0 like that.

---
Tags: ir
---


# Question
Title: GPRS shield - Hayes commands to identify a faulty SIM connection
I'm currently battling with a LinkSprite GPRS shield (it's based on the SIMCom SIM900 chip) and seem to have absolutely no luck trying to connect to the network. I've got two SIMs, both of which should be active, but I cannot get the connection light on.

I've got a serial connection going and it's responding to various AT commands, but I can't connect:

> AT+COPS=?

is working, and giving me a list of networks, so I think my antenna is good, but

> AT+COPS=-whatever-

immediately gives me +CREG: 3.

I'm now wondering whether there's a fault with my board, and that it's not seeing the SIM cards. A few commands that I thought would work aren't, for example:

> AT+CPIN?

just returns ERROR

Similarly, when trying to read SMS data:

> AT+CMGL="ALL"

returns ERROR.

Have I proved that the board isn't seeing the SIM, or is there something definitive I can try?

Thanks in advance!

# Answer
> 1 votes
Having exchanged the board for another one (that works!) I can now confirm that the calls above (e.g. AT+CMGL) *should* work if there is a working SIM connection.

---
Tags: arduino-uno, serial
---


title: My mega only works on 1.0.1 IDE

text:
# Question
Title: My mega only works on 1.0.1 IDE
My mega usb/serial adapter died some time ago, so I bought an external FTDI programer wich I got working on 1.0.1 IDE. I can load any program to the mega, even complex led matrix driver I wrote myself so the ATmega works fine and the external FTDI board does too. Strangely enough I if I want to update the IDE (tried once on 1.0.5 and yesterday downloaded 1.6.5) I get an

```
 avrdude: stk500v2_getsync(): timeout communicating with programmer

```

When this problem occurs, I see that the programmer board recieves something (it has Rx and Tx LED's) the Mega resets but never sends any data back, which does happen on 1.0.1 IDE. This happens on my pc, and on a laptop son no pc related problems. I'd keep using this version but now I got an OLED display I want to drive (SSD1306 from waveshare) but I can't compile u8glib on 1.0.1 but I can on 1.6.5, however I can't get a simple blink example to upload with this IDE.

I suspect the DTR pin (reset pin) is handled differently and that makes the mega stay resetting until it times out. What can be the problem here? How can I get more info from the console to solve this?

# Answer
> 0 votes
You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.

The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.

---
Tags: arduino-mega, arduino-ide, ftdi
---


# Question
Title: Verifying the timing between relay activations
I would like to verify timings of a relay controlled by an arduino (uno R3). There is a lot going on in the sketch and it does not use the delay function but one which is based on counting milliseconds. The arduino then transmits to another arduino using a radio module (nRF24L01). I'd like to confirm the intervals between the relay, so for instance if the relay is acivated 10 times and there are 5 seconds between each actvation.

So what I was wondering was whether anyone had any reccomendations on methods to verify timings using an external source.

Two ideas I came up with were: have another arduino with a very simple script that measures the timings or try and find/write a verilog script to upload to a mojo fpga and measures the timings.

An ideal situation would be where I have a seperate device that hooks up to the relay and then measures and displays the timings between the relay switches and is extremely precise.

I hope that makes sense, if not please let me know and I'll explain further. Thank you for reading and any help is greatly appriciated.

# Answer
You could use sigrok with one of the many supported devices. For example, you can find on ebay an 8 channell 24MHz probe for less than $10.

It's a nice tool to have laying around. For example you can use it as less-invasive-than-serial-print way to detect when internal states of a program change value: just toggle some unused GPIO.
> 1 votes

---
Tags: safety, timing
---


# Question
Title: Arduino communicate between 2 different router in different location
I am on my final year project in I.T. my project is that i want to create a helicopter or quadcopter with a camera attached to it. And i want to control the copter via wifi from an android phone in another location. e.g, the copter is at home and i am somewhere else (work, university etc..). so i wanted to know if i can connect both via 2 different routers and control it and get the live video the camera is actually recording (the idea is to monitor your house when you are away). if that is possible, which arduino hardware will enable me to do that. Thank you.

# Answer
It's not the Arduino that has anything to do with this but the routing, port forwarding and/or VPN that you set up between your routers.

I'd have thought, since you're in your final year of IT, you'd at least have some rudimentary knowledge of routing, port forwarding and VPNs...
> 1 votes

---
Tags: arduino-uno, wifi, ethernet
---


# Question
Title: Using 2 RGB lights over Bluetooth with a DigiSpark
I'm not that experienced with electronics but I am learning. And I've set a challenge for myself. I have a Digispark USB Development board (and many more but I want to use this one!), I have a Bluetooth module and I have two RGB LEDs which I want to control over the Bluetooth connection. Each LED has to be controlled separately and I want to be able to set each color separately and be able to mix about 256x256x256 colors. Which means, PWM connections. The Bluetooth connection would listen to instructions, receiving four bytes containing RGB values and a value between 0 and three to pick which light needs to be set. (0=None, 1=left, 2=right, 3=both)
Also important is that it needs to be small. It will end up in a container of of roughly 3x3x10 CM in size. (Slightly bigger than 1x1x3 inch.)

The challenge is that Digispark only has 6 pins available so that's not enough to handle this all. I could use three pins and use a 74HC165N Shift Register but that would just turn each color on or off, thus limiting me to 8 colors. That's not good enough! Besides, I also need to connect the four pins of the Bluetooth module.

So my question is simple: What would I need more to build this project? To send the proper six analog signals while having enough pins to handle the Bluetooth datastream?

# Answer
> Which means, analog connections.

Nope. It means PWM.

How would you control the brightness of a single LED?

By generating a PWM signal with:

* sufficiently high frequency to not be able to notice the flickering;
* duty cycle proportional to the brightness you want/need, where 100% is full brightness, and 0% is OFF

You only have to do that for each colour of the RGB LED you want to drive. Ideally you would use a HW block capable of generating the PWM signal, but it can be also bit-banged, should you run out of PWM blocks.

Just keep in mind that different colours have different currents (for the same level of brightness), so you have to pay attention at calculating the correct value of the resistor applied to each colour.

If you prefer to ensure that each channel is driven by a HW PWM generator, you can also use an external driver. Ex: I2C 6-channels PWM generator.
> 1 votes

---
Tags: pwm, multiplexer, rgb-led
---


# Question
Title: How do I know which is ground and power in Piezo?
I have a piezoelectric sensor. Both pins are the same length. I have one like this: Piezo picture. On the Piezo it's written *muRata* and *01P*. How do I know which do I send to the digital pins and which to the ground? I have an Arduino Uno.

# Answer
> 2 votes
On the one I have, the shorter pin is ground. I discovered that empirically - a scientific word for "I tried it the wrong way round the first time but the magic smoke stayed inside." Afterwards I inspected it more carefully, I found a '+' embossed in the top surface nearer one side. :-o

# Answer
> 1 votes
If you're using just one or sound quality doesn't matter: it doesn't matter.

Otherwise you need to figure it out with a scope like this:

* Connect both poles of the connector of the PZT to an oscilloscope (time base approx. 50ms/div, y-axis 200mV/div).
* Slightly tap the head of the PZT with your finger. As a result you should get a voltage pulse on the oscilloscope.
* Positive Amplitude -\> + pole of the piezo is connected to the inner conductor of the oscilloscope BNC connector.
* Negative Amplitude -\> + pole of the piezo is connected to the outer conductor of the oscilloscope BNC connector.

---
Tags: arduino-uno, sensors, pins, piezo
---


# Question
Title: Open the Uart0 Serial Port on Intel Edison
I'll preface this buy saying I am very new to working with Arduino boards or hardware in general. I am attempting to follow a tutorial on instructables

http://www.instructables.com/id/PCBot/step4/Printer-test/

I have my board and printer wired up properly and I have git cloned the python thermal printer. My issue begins at this paragraph:

> Open the UART0 serial port by default the GPIO's of the edison are disables.
>
> You can enable them by programming the edison via the Arduino IDE or by using the MRAA library available for several programming languages.
>
> To open enable the UART0 port, TX RX on the edison breakout board, open a Python shell in the thermal and write:
>
> import mraa
>
> x=mraa.Uart(0)

I opened a python shell and entered the `import mraa` lines and tried to run the `printertest.py`

I receive an error that says no module named serial. I am not sure where the issue is. I thought the Edison already had python serial installed. I did try to install it with `opkg install python-serial` but it didn't work. If my issue is with enabling the Uart0 port I am not sure how to go about doing it. I have the Arduino IDE installed but I have no idea how to go about enabling it via the Arduino IDE. The instructions are a bit vague in that paragraph.

\*Update I have successfully installed pip and got pyserial installed. Now when I try to run the printertest.py I get an error `OSError: [Errno 2] No such file or directory: '/dev/ttyAMA0'` which I think is potentially caused by me not succesfully opening Uart0 port but I am not sure how to. I tried adding the import in a shell as well as adding it directly to the code via nano

# Answer
> 0 votes
I have solved the issues and successfully connected this printer with the Compute Module. I solved the issue by changing the target of `/dev/ttyAMA0` to `/dev/ttyMFD1` as shown by http://iotdk.intel.com/docs/master/mraa/edison.html . This was the final step after I had installed pyserial.

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


# Question
Title: Capacitive sensor MPR121 on Arduino Uno—how many will work?
I need to attach several capacitive sensors MPR121 with each of them using all of its 12 electrodes to an Arduino Uno.

Could you please tell me, how many will work with the voltage and current Arduino Uno supplies?

# Answer
The answer is 4 regardless of the current consumption.

You can have 4 MPR121 devices on an I2C bus (by connecting the ADDR pin to the right place to select 1 of 4 addresses), and the Uno has one I2C bus - so that means 4 devices.

You *could* use software I2C to add more devices on other pins, but that's slow and clunky.

But that aside, if you used something to increase the number of I2C buses available, according to the datasheet the peak current consumption is 1mA during sampling, and assuming 300mA maximum for the Arduino's 3.3V regulator, that would mean a maximum of 300 MPR121 connected to the Arduino. Note that, if you could actually *get* to the Arduino amongst that tangle of wires, you'd find it getting rather hot...
> 2 votes

---
Tags: arduino-uno, sensors
---


title: Using Intel Galileo Ethernet Port

text:
# Question
Title: Using Intel Galileo Ethernet Port
Is it possible to use the galileo's ethernet port through arduino IDE? Or should I buy an arduino ethernet shield? Will I be able to use galileo as a server to which arduino board can send data to?

# Answer
> 2 votes
I suppose you mean the "Galileo integrated Ethernet port" (the on-board RJ45). Then the answer is "no, not directly". The whole code provided by Intel in Arduino 1.6 IDE applies to the W5100 based shield, not the integrated Ethernet interface (which is a bit stupid, imho...)

Technically, however, this is possible, but you will need to create a library in C/C++, which interfaces with the system lib (the Linux one). You can then access the wonderful world of BSD sockets (much more powerful than the sockets within the W5100).

Note however that the configuration of the integrated Ethernet board is not very easy with the Galileo, because the default Yocto image does not allow you to change default IP parameters (the Yocto image uses DHCP by default). So technically, you need then to deal with a startup script that changes the IP parameters at startup, but it's pretty heavy to do.

# Answer
> 0 votes
The Galileo board is Arduino compatible; meaning that you can run Arduino sketches on it, and use its I/O pins the same way you would with, say, Arduino Uno.

Therefor you can communicate between Galileo and Arduino the same way you would with two Arduino devices. This can be done using your favorite communication channel - Serial, I2C, OneWire, RF or even Infrared - it all depends what exactly are your needs, knowledge and timing requirements. Of course, doing it this way, would require you to have code running on both the Galileo and the Arduino, in charge of the inter-communication.

By doing so, you could utilize the Galileo as a 'server' as you say, that will receive commands from the Arduino, send them over the network and reply to the Arduino with the response.

# Answer
> -1 votes
Yup - the Galileo Ethernet port works the same way as any other Arduino. For some sketch examples have a look at

> File \> Examples \> Ethernet

---
Tags: ethernet, arduino-galileo
---


# Question
Title: How to network multiple Arduinos so they react to the same signal
I want to build a project that contains multiple Arduino nano's, each connected to one controlling Raspberry Pi. I would like to send one signal (a string of characters or numbers) which would be the master state, which the other Arduinos would react to based on their programming. What is the best way to do this?

Can the Arduino support a protocol for this, or will it need additional hardware?

Max distance: 30 meters

# Answer
> 1 votes
Rule 1 do not connect Arduino pins to long wires.

You can achieve your your goal in many ways, a serial interface looks good from here. I am doing it with a RS485 interface, note it is an interface not a protocol. You can use CAN, Wi-fi and many others. It sounds like all the units except 1 will be receiving data, the other is transmitting it to the other devices. RS485 will work good and it needs only 5V. It will work over several thousand feet and some reasonable speeds. You can use a UART either hardware or software to accomplish the task with a RS-485 driver at each node. You need to remember you need to wire from point to point with the terminating resistors only on the end nodes.

---
Tags: arduino-nano, communication, networking
---


# Question
Title: 433Mhz transmitter interference when using long cable, only on Arduino Due
When the 433 transmitter is wired close to the Arduino Due (within 12" away), it works as expected. But when I put it on the end of a 15' cable, it has the following 2 symptoms:

-All the other nearby 433Mhz transmitters and receivers stop working. (I've never seen this happen from any other cause).

-My Extech 480836 EMF meter shows a big jump in electromagnetic radiation along the entire length of the 15' cable (it jumps from *0.1 uW/m2* to *3 mW/m2* a few inches away). The reading only goes down to normal if I unplug the transmitter's data wire from the Arduino.

The transmitter in question is still able to send signals correctly when wired with a 15' cable to the Due (properly activating remote switches), even though it disables every other 433 transmitter in the area.

I've tested this with 2 different kinds of 433 transmitters, getting the same result. Both of the transmitters work fine whenever wired closely to the Arduino Due, and both work as expected when connected to an Arduino Uno. The problems still occur even if I'm not sending any wireless transmissions from the code. Disconnecting the transmitter's data wire from the Arduino Due causes the problem to stop immediately.

I'm using the RCSwitch library. The simple code below works fine on an Arduino Uno, whether the transmitter is wired far or close to the Uno. The same code works fine with the Due when the transmitter is close to the Due. But when the transmitter is wired 15' away from the Due, then the problems occur. On the Due I've tested using 5v and 3v for powering the transmitter. Changing the voltages doesn't seem to affect the problem.

```
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();

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

  // Transmitter is connected to Arduino Pin #8
  mySwitch.enableTransmit(8);
}

void loop() {}

```

Why am I having this strange behavior? Do you have any suggestions on how to fix it?

# Answer
I think I found the problem. It seems that there's an anomaly with the Due where when a pinmode is set as OUTPUT, it sets the pin as HIGH by default, whereas with the other Arduinos it's set as LOW. This forum page is discussing the problem: http://forum.arduino.cc/index.php?topic=154869.0

Likewise this page suggests the problem is a bug with the wiring\_digital.c file: http://forum.arduino.cc/index.php?topic=185230.0

In RCSwitch.cpp, this is the enableTransmit code:

```
void RCSwitch::enableTransmit(int nTransmitterPin) {
  this->nTransmitterPin = nTransmitterPin;
  pinMode(this->nTransmitterPin, OUTPUT);
}

```

It seems the code sets the pin as OUTPUT, which would cause an anomaly on the Due alone.

I solved the problem by calling the enableTransmit function just before sending a signal, and then calling disableTransmit() immediately afterwards. Can anyone think of a cleaner/better solution?

Out of curiosity, can anyone suggest what a standard transmitter might be sending when the data line is constantly held at HIGH?
> 0 votes

---
Tags: arduino-due, wireless
---


# Question
Title: Serial comms failure after long time - can't open COM port
I've been using an Arduino UNO to log data: it's queried by a LabView VI over a VISA connection. It'll happily sit there and log for days, but very occasionally one of the VISA functions will fail.

After this, I can't open the COM port again (in LabView or elsewhere) and the only way to restore communication is to unplug and replug the USB cable. The Arduino hasn't crashed because I can see the other results of the program it's running working fine, but Serial comms are a gonner.

Has anyone experienced this? Do you know if this is an Arduino problem, a Labview problem, a Windows problem? Or something else?

I'm writing a minimum working example to try and catch this happening in the most simple code possible, but since the error usually takes several days to show up I can't tell you the results yet!

# Answer
In the end I found a solution, more or less through trial and error.

Labview default its VISA VIs to "asynchronous" mode: I found that by switching them to "synchronous" (right click on them and select "synchronous") this problem disappeared.

I think this is caused by the computer occasionally getting ahead of the Arduino and asking for the next measurement before it's finished receiving the first one. Switching to synchronous mode forces execution to wait until the VISA exchange is complete before it continues.
> 0 votes

# Answer
The assumption I am making is "VISA connection" is a PC operating VISA. I have seen ports shut down on windows several times yet the same port works fine while in DOS. My suggestion is try a different computer, that should narrow down your problem to which side of the connector is failing.
> 0 votes

---
Tags: arduino-uno, serial, programming, usb, communication
---


title: Extracting high and low bytes from long

text:
# Question
Title: Extracting high and low bytes from long
I am learning Arduino from "Arduino cookbook by Michael Margolis", i was reading about bitwise operations and extracting low and high bytes from int. He said that there is no function in Arduino to extract high and low bytes from long at the time of his writing. He stated an alternative to the problem by adding two line of code.

```
#define highWord(w) ((w) >> 16)
#define lowWord(w) ((w) & 0xffff)

```

The first line i clearly understood like this, please make corrections if i am wrong.

```
32bit binary of 16909060 is 0000 0001 0000 0010 0000 0011 0000 0100

```

by right shifting last 16 bits we will arrive at

```
32bit binary of 16909060 after right shifting 16bits is 0000 0000 0000 0000 0000 0001 0000 0010

```

I am not able to interpret the second line.

```
#define lowWord(w) ((w) & 0xffff)

```

I would be very grateful if some body explain how the above line of code works? Thanks.

# Answer
The second line masks off the top two bytes using a bitwise AND.

When you use a bitwise AND it follows the normal rules for any boolean truth table. 1 & 1 = 1, 1 & 0 = 0... Since the value is being ANDed, effectively, against 0x0000FFFF, the top two bytes will be cleared to zero while the bottom two bytes are preserved. In this way you can extract the lower two bytes out of the four byte long.
> 4 votes

# Answer
An alternative way of seeing the two operations is through the operators "integer division" and "reminder of the integer division".

In a more generic fashion:

`#include <limits.h>`

`#define highBits(value, number_of_high_bits) \
 (value / (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))`

`#define lowBits(value, number_of_high_bits) \
 (value % (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))`

This will work regardless the number of bits used for `value` and with an arbitrary number of `high_bits` to either keep or shave.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Math with analog input values coming out wrong
Im getting stuck in a while loop because Im having trouble running a calculation on some sensor values. When I read my four sensors values and compare the ratio of the first two to the second two, I keep getting 0.00, no matter what the values are. Here's my code:

```
while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
    if (backleft + backright > frontleft + frontright) {
      myStepper2.step(10);
    }
    if (backleft + backright < frontleft + frontright) {
      myStepper2.step(-10);
    }
    int backleft = analogRead(A0);
    int backright = analogRead(A1);
    int frontleft = analogRead(A2);
    int frontright = analogRead(A3);

    Serial.print("Backleft Reading: ");
    Serial.println(backleft);
    Serial.print("\n");
    Serial.print("BackRight Reading: ");
    Serial.println(backright);
    Serial.print("\n");
    Serial.print("Frontleft Reading: ");
    Serial.println(frontleft);
    Serial.print("\n");
    Serial.print("Frontright Reading: ");
    Serial.println(frontright);
    Serial.print("\n");
    float ratio = (frontleft + frontright) / (backleft + backright);
    float math = (5 + 6) / (4 + 5);
    Serial.print("Math: ");
    Serial.println(math);
    Serial.print("Ratio: ");
    Serial.println(ratio);
    Serial.print("\n");
    delay(500);

  }

```

Im getting values for my sensors (backleft, backright, frontleft, frontright), but 'ratio' always comes out 0.00. Because of that, Im getting trapped in the loop I believe. What's going on here?

Also, just to check, I added 'math' float as that quick calculation, but I'm getting a value of 1.00 in Serial Monitor. Why? It should be 1.222.

# Answer
> 1 votes
Read this: Integer arithmetic and overflow.

```
float math = (5 + 6) / (4 + 5);
Serial.print("Math: ");
Serial.println(math);

```

The compiler is treating your expression (the RH side of the "=" sign) as **integers**. Thus it is working out:

```
11 / 9 = 1

```

Then you assign that `1` to a float. Too late to make it a float! It is already truncated.

Try:

```
float math = float (5 + 6) / float (4 + 5);
Serial.print("Math: ");
Serial.println(math, 4);  // 4 decimal places

```

You get:

```
Math: 1.2222

```

---

This also looks wrong:

```
while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
    if (backleft + backright > frontleft + frontright) {
      myStepper2.step(10);
    }
    if (backleft + backright < frontleft + frontright) {
      myStepper2.step(-10);
    }
    int backleft = analogRead(A0);
    int backright = analogRead(A1);
    int frontleft = analogRead(A2);
    int frontright = analogRead(A3);

```

How many `backleft` variables do you have? The one in the `while` instruction will **not** be the one you are doing the analogRead on. It doesn't "forward read" variables. I bet you have a different `frontleft` / `backleft` etc. set of variables declared earlier. These will **not** be updated inside the loop.

(To make them get updated drop the word `int` from inside the loop).

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