# Question
Title: Simultanous read and read/write on two serial connections
At the moment I'm using two softserials to connect to a GPS and an GSM module.

It seems not possible to have two open software-serials. So I was looking for an solution

After the initial-setup, the GPS module is only needed to be read from; while the GSM module needs to be bidirectional. So:

```
GPS > listen only
GSM > listen and write

```

Now I came across the GPS library from Adafruit, which uses an interrupt to receive data. Is this *instead* of a software serial. Or do I again run into the limitation?

An other solution might be to use the D0 and D1 to attach eg the GPS module. But than I won't be able to see the debug messages in my serial monitor. Is that correct?

Sorry in advance for these n00b questions. But I'm frustrated the things dont work as I want :)

**edit**

* This is the adafruit GPS board.
* And the board with whom it is connected: Gboard
* The Sim900 is connected to D2/D3 and the GPS is connected to A2/A3.
* D0/D1 are connected to a FTDI breakout board, which is plugged into my USB.

# Answer
So you want three serial ports: upload/debug (hardware serial), GSM (software serial) and GPS (software serial). Unfortunately, two SoftSerial ports are not going to work at the same time (or even send and receive at the same time on one SoftSerial port). In your current configuration it's not going to be solvable.

If you can wire the GPS to different pins, there are a couple of options to try. One would be to disconnect the FTDI when running (reconnect to program) so you can use the hardware serial port for either GSM or GPS (probably the former). If you need some print statements for debugging, you could use SoftSerial or AltSoftSerial (and connect the FTDI differently). Reconnecting between upload/debug and run phases would be a pain but it comes with the platform you are choosing and the number of serial ports you need; you might be able to wire up a DPDT switch externally to do the switching rapidly.

The other and perhaps easier approach would be to connect the GPS to pins 8 and 9, and use AltSoftSerial for the GPS; as long as your baud rate to the GSM is high enough that might work. (SoftSerial for the GSM will turn off interrupts for excessive periods of time at low baud rates). Using AltSoftSerial makes use of the single 16 bit timer (Timer1), so this won't work if you use any other library which requires Timer1.
> 0 votes

# Answer
`Adafruit_GPS.h` (line 132-), which is included in `Adafruit_GPS.cpp` (line 13) refers in turn to the SoftwareSerial library on AVR platform and Arduino IDE version \> 100.

```
#ifdef __AVR__
#if ARDUINO >= 100
    SoftwareSerial *gpsSwSerial;
#else
    NewSoftSerial *gpsSwSerial;
#endif
#endif

```

This means it uses software serial on an Uno. It also means if your problem is indeed with Software Serial, that is the library to check for bugs / updates or commit a patch to.
> 2 votes

# Answer
The solution to your problem might be to combine AltSoftSerial with SoftwareSerial. I haven't done it myself (yet) but I have the same problem as yours.

SoftwareSerial does busy wait for counting time between two bits, so it can't read simultaneously from two ports (some bits could be lost).

AltSoftSerial was created to overcome some of these limitations. It's interrupt-based. Unfortunately, it's harwired for one port (and pins 7 & 8). My understanding is that you can combine it with SoftwareSerial to read from 2 simultaneous ports. Pins 7 & 8 aren't what you need, from the description of the GBoard, but AltSoftSerial is open source, you can change the pin numbers (and possibly some masks) in the source code.

Hope this helps.
> 1 votes

# Answer
I've done exactly this. The secret sauce for me was the SoftwareSerial.listen().

Before running your GSM commands you have to make sure the GSM module's SoftwareSerial port is "listening". Then when you're done you have to `listen()` again to the GPS.

This is, of course, not terribly efficient, while the GSM port is listening any GPS data will be lost, but at least in my case the impact was negligible.

My code is here: https://github.com/lectroidmarc/gsm-tracker

As an aside, I have also considered plugging the GPS into the UART and running debug messages to a SoftwareSerial serial port, to be monitored during testing with another Arduino. I'm just not sure the benefit would be there.
> 0 votes

# Answer
There is a working example of this, using the Adafruit Ultimate GPS, and the Arduino GSM shield http://www.mallinson-electrical.com/shop/gpsgsm I hope this helps
> -1 votes

---
Tags: arduino-uno, serial, pins, interrupt, softwareserial
---


title: Using Arduino Nano as USB Host

text:
# Question
Title: Using Arduino Nano as USB Host
I'm pretty new to microcontrollers and Arduino and since I can't find any satisfying information on my problem, I hope that you might answer them:

My project is actually quite simple: I just want to write out data over a serial connection via USB, the problem: My Arduino Nano has to run as USB Host. That's because the other device is a vacuum cleaner: Neato XV-25 with a mini usb jack. I was already able to 'talk' to it using a Raspberry Pi.

Since I don't have much knowledge about USB communication, I would like to know the following, before I start digging deeper:

1. I found out, that I would not be able to use the 'usual' usb port of the nano. But I've read a few things about that 'V-USB' library, but did not understand very much. Would it be possible to create a USB Host with this library, that can communicate via a virtual serial connection?
2. I stumbled across the USBHost for Android Nano. It's a shield, but I'm not sure if it would fit my needs. Is it able to handle serial communication? And is there somewhere a store where I can get it cheap? I think more than 20$ for a shield is a bit too much...

# Answer
> 3 votes
1. > V-USB is a software-only implementation of a low-speed USB **device** for Atmel’s AVR® microcontrollers

No host support here, sorry.
2. The USB host shield handles the hardware bit and simplifies the software bit. It is up to the firmware to support the various USB profiles. Version 2.0 of the library supports CDC with a few devices; check to see if they would be correct for your purpose.

---
Tags: shields, arduino-nano, usb
---


# Question
Title: Is it bad to leave my Arduino UNO on uninterruped?
I'm developing a project (Data logger) that requires that the Arduino remains on for several weeks.

Is it okay to leave it on for about 6 weeks? Do I need to frequently reset it?

# Answer
This question has a very broad answer. As it depends upon your implementation of both hardware and software.

In very short -

That all depends on your code. The hardware should be able to be left on indefinitely, assuming it is all within spec's. Assuming that, then the biggest concern is the code running on it. Where largest problem of concern is running out of resources. Such as memory. If your code as a memory leak then it will be a problem. Or if there is a bug in the code that can cause it to get stuck. The later can be addressed by employing the WatchDog, which will reset (loose all data) if the code gets unexpectedly stuck.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Is it possible to extend the reach of a PN532 NFC/RFID shield?
I am working off an Arduino Uno with an AdaFruit PN532 NFC/RFID shield. The goal is to have a shoe box, with a false bottom. Under that false bottom would be my prototype, which I hope will be able to detect any MIFARE tag that is in the box, above the false bottom.

The range obviously for these devices is practically touching, but I was was wondering if there is anyway to extend the reach of the NFC/RFID shield, so that the entire false bottom of the box could act as that antenna.

# Answer
I suspect not. NFC is designed for short range for privacy reasons. Some RFID systems have longer ranges (a few meters). They work by using an electromagnet to create a switching magnetic field. The RFID/NFC chip takes power from the magnetic field and then modulates a signal onto it, which the sensor detects. In order for it to work the chip needs to be close enough to get as strong enough field to power itself, and to modulate that field.
> 1 votes

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


title: Fade in UV lights connected to mains

text:
# Question
Title: Fade in UV lights connected to mains
I have a PIR motion sensor and would like some ultra bright UV led lights to fade in when this is triggered. It is one unit, consisting of 225 led lights connected to 240v mains (Australia). I bought a relay for the basic on/off function but was wondering if fading on and off can be done relatively easily - this is my first arduino project. I would value any suggestions.

# Answer
> 1 votes
Most LED lights can't be dimmed from the mains supply.

In order to dim LEDs you have 2 choices: Limit the current through each LED or series string of LEDs, or pulse them very rapidly with a varying ratio of on/off times (known as a variable "duty cycle")

It's usually easiest to pulse them. To do that you need to be able to control the flow of DC to the LED array. If you were to take apart your IR array you would very likely find an AC to DC power supply that then feeds the LEDs through current limiting resistors.

If you can figure out the voltage and current that comes out of the DC power supply, you can select a power transistor (almost certainly a logic level power MOSFET) to wire in as an electronic switch that enables you to pulse the power to the LEDs using a logic signal from your Arduino.

This is actually a lot simpler than it sounds. You would cut 1 wire inside your LED array, solder in a single transistor to the 2 ends of the cut wire, and run the third wire from the transistor out to your Arduino.

Arduinos have several I/O lines that can be configured for PWM (Pulse Width Modulation) which is designed for this very purpose. You'd connect a PWM line to the gate of a logic level power MOSFET, and then send it a signal from 0 to 255, which would effectively dim the LED array in 255 brightness steps.

There are beginner sample projects that let you dim single visible light LEDs using this very approach. (For a single LED you don't need a transistor though, so they are really easy to wire up. All you need is a current limiting resistor.) I suggest you find and build one of those projects to get a feel for how (and how well) it works.

---
Tags: led, relay
---


# Question
Title: Arduino starter kit example LEDS modification
I just begun with the Arduino starter kit, and in the second example I would like to test some changes to learn more.

The point is to have a green LED shining, and when pressing the button the two red LEDs blink.

This is the code:

```
int switchState = 0;

void setup()
{
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // the button is pressed
  digitalWrite(3, LOW);

  digitalWrite(4, LOW);
  digitalWrite(5, HIGH);
  delay(250); // wait for a quarter second
  // toggle the LEDs
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  delay(250); // wait fo a quarter second
}

void loop()
{
  switchState = digitalRead(2);
  // this is a comment
  if(switchState == LOW)
  {
    // the button is not pressed
    digitalWrite(3, HIGH); // green LED
    digitalWrite(4, LOW); // red LED
    digitalWrite(5, LOW); // red LED
  }
  else
  {
    // the button is pressed
    digitalWrite(3, LOW);

    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);
    delay(250); // wait for a quarter second
    // toggle the LEDs
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    delay(250); // wait fo a quarter second
  }
} // go back to the beginning of the loop

```

I added a modification into the schema (a fourth LED in parallel with the green), like this:

But the added LED is not shining. It's a long time ago I finish school and I forgot a lot of things. Am I wiring the fourth LED incorrectly?

# Answer
> 1 votes
Blue LEDs have a higher Vf than green LEDs, hence much less current will pass through it, not enough to make it visible. Give it its own resistor instead of sharing the resistor with the green.

---
Tags: arduino-uno, led, wires
---


# Question
Title: Serial.println(): Where is the text printed?
When I used `Serial.println()` in the code I naively believed I would see the characters that I sent displayed on that little black area just under the interface (just like a terminal).

```
#include <Servo.h>

int moveServo;

Servo myservo;

void setup()
{
  myservo.attach(0);
  Serial.println("      Hello Earth");
  Serial.println();
}

void loop() {
}

```

Can someone tell me just where `Hello Earth` would be displayed?

# Answer
> 11 votes
The IDE on your computer has a menu item under the tools menu called "Serial Monitor." On my Mac, at least, it is indeed a black area under the source editor for the current sketch.

It won't work unless you call the `Serial.begin()` function in your setup method before the first `Serial.print()/println()/write()` function call.

Something like this:

```
//Set up the serial port @ 9600 baud for display back to the computer
Serial.begin(9600);
delay(25);
Serial.println("Hello world!":);

```

# Answer
> 3 votes
You can open the serial console in the Arduino IDE by pressing ctrl-shift-M (as in Monitor) or selecting it in the menu.

Also, to use the serial interface, you have to initialize it using `Serial.begin(9600);` in `setup()` before calling any other function which writes to it. You can use any other baud rate - but this is the default in the Arduino IDE, if you change it, you should change it in the IDE too.

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


# Question
Title: Why does my Arduino seem to reboot every time that I open Serial Monitor?
Every time that I open the Serial Monitor, my Arduino Uno, seems to go back to `void setup()`. Is it a normal thing?

# Answer
> 5 votes
That is a normal feature of Arduinos, not an error. I find it mildly annoying sometimes, but it's nice for interactive programs that want some kind of menu message to be the first thing you see in the terminal.

If you want help disabling the auto reset, your options are detailed in *Disabling Auto Reset On Serial Connection*.

---
Tags: arduino-uno
---


# Question
Title: Curious: What would happen if you connect 5V and GND port directly with a wire
Has anyone ever accidentally or inadvertently connected connected the supply port with the ground port with a wire?

Does Arduino provide internal safety to prevent the circuit board from shorting out?

# Answer
> 6 votes
There is some protection.

When powered from the USB port, the UNO has a 0.5 A fuse. This is a self resetting fuse that will trip when the current is high, and reset when it cools back down. These fuses are great for peripherals that might be exposed to occasional "oops". See the data sheet for more details of the part on the UNO.

When powered from the PWRIN plug, the voltage regulator provides some protection. The device on the UNO contains over current and over temperature protection, which is common for regulators such as this. The device will get very hot, and the protection will activate to limit the current (see datasheet for details). By design, the regulator chip should protect itself from being destroyed.

So to first order, if you by mistake connect the +5 on the header to GND, all that will happen is Vcc will be reduced to near zero Volts.

The caveat is that a small spark can be generated when you make this short to ground, especially if you have a bunch of capacitors on Vcc. That spark may cause a voltage transient that could damage a pin.

---
Tags: arduino-uno, power
---


# Question
Title: Keyboard Control Not Working As Intended
I'm trying to control a single motor.

If I press 'a', then motor 1 should turn to 0, if I press 's', then motor 1 should turn to 180

```
#include <Servo.h>

char key = 0;
const unsigned int BAUD_RATE = 9600;

Servo Servo_0;

void setup()
{

  Servo_0.attach(0);
  Servo_0.write(0);

  Serial.begin(BAUD_RATE);

 // Serial.println("      Arduino Serial Servo Control");
 // Serial.println("Press < or > to move, spacebar to center");
 // Serial.println();

}

/*
a - 97
s - 115
d - 100
f - 102
*/

void loop() {

  if(Serial.available()>0)
  {
      key = Serial.read();
      Serial.print("I received: ");
      Serial.println(key, DEC);

     if(key == byte(97))
     {

       Serial.print("Turning Motor 1 to 0 deg");
       Servo_0.write(0);

     }
     else if(key==byte(115))
     {
       Serial.print("Turning Motor 1 to 180 deg");
       Servo_0.write(180);

     }

     delay(1000);
}

```

But what is happening is that the motors are barely turning after I enter the key onto the Arduino monitor interface. Can anyone diagnose as to what might be happening?

# Answer
> 4 votes
The problem I see is that your servo is attached to pin 0.

Pins 0 and 1 are used by arduino unos and megas for serial communication, so you can't output to a motor and send/receive serial at the same time. Try moving the servo to pin 3 and see what happens.

In response to your comment, any character sent from any terminal (or other piece of hardware) will work; you do not need to use Processing to communicate with an arduino.

---
Tags: arduino-uno, motor
---


title: Building a gps system

text:
# Question
Title: Building a gps system
I'd like to build a simple GPS system. It should be very little. For the software side, I will build an API, so from my PC/smartphone/whatever else I could ask the GPS system where it is located (I think Google provides this kind of feature).

How can I do this? My main problem is the GPS and the its building. I'd like to build the smallest thing possible, because I have to hide it. My idea is to hide this GPS system in my bike: I'd like to locate my bike if someone stole it. As you can see, internet is a problem.

I'm not asking to design anything. I would only know what I need to build a basic GPS system that has just the feature described. What do I need? Is it possible to do it? Does GPS require Internet connection? I would know if I could make it or not without internet access.

# Answer
***"Is it possible to do it?"***

Well... everything is possible :-)

***"Does GPS require Internet connection?"***

GPS doesn't require internet. A GPS receiver (e.g. http://www.modulestek.com/prodts/GPS/Mars740-mini/Mars740-mini\_SPEC.pdf) is connected to the reading unit via USB or a RS232 interface. The protocol is very simple. However it only provides latitude and longitude. If you want to have an address, map data is required (for *this* you would need internet - or a large memory).

And of course such a system requires good signals from the GPS satellites.

***"What do I need?"***

First you need a GPS receiver (see above).

Second, you need a microcontroller unit which runs your application and does all the control of the external units.

Third, you need a GSM module (e.g. http://www.exp-tech.de/Shields/Wireless/GSM-GPRS/adafruit-fona-mini-cellular-gsm-breakout-sma.html) to send a message. Don't forget the antenna for connection to the mobile communication network.

Fourth, you need a power supply. Ideally it has a battery which can be reloaded when driving.

As you may see, if you put all this together you are far from the "smallest thing possible".

Actually any modern smartphone could be enough. Mount it "invisible" under your saddle, connect it to a bike charger, find the proper App and that's it - although it might not be the smallest solution.

I don't know any, but I'm sure there *are* products off the shelf that fulfil your requirements, designed and developed by experienced engineers, and thus smaller and maybe cheaper than what you ever could achieve on your own.
> 4 votes

---
Tags: gps
---


# Question
Title: Motor shield and wireless transceiver compete for same pins
I would like to use these 2 components with an Arduino Uno:

* Arduino Motor Shield R3
* nRF24L01 2.4GHz Wireless Transceiver

I use Stepper for the motor shield, and SPI + RF24 for the wireless transceiver.

I could write 2 sketches that work perfectly, but how can I combine them together?

My issue is that they both require access to pins 11, 12 and 13.

Any help is greatly appreciated!

# Answer
For prototyping, use male to female jumper wires to connect the Arduino Uno to the robot shield. It is a bit of a pain, but it makes it easy to free the conflicting pins for the wireless transceiver.

For a more permanent solution, look at Chris K's answer.
> 0 votes

# Answer
This is the core of embedded design and "hacking" and highlights one of my peeves about Arduino design: too much focus on the pin numbers and physical location on the PCBs, rather than the actual functions on those pins.

So? Physically move the pins on the Motor Shield. Here are 3 options in order of the most hack-ish to most-clean:

1) Use an edge cutter to cut the bottom of the pins off the motor shield then solder jumpers to the nub to other pins that **are** free.

2) Use a hot air station to desolder that header row, solder in your jumpers, and put back only the pins you want. Board designs with such limited foresight (like your situation) is what led me to buy my hot air station. And now I pretty much use sensor shields for my interfacing outside the stack or proto shields to be intermediate layers to translate pins.

3) Cut the trace on the motor shield PCB itself to free the SPI pins. Then find pins that have your function (pwm?) and also are NOT used by any other shields in your "stack". Solder a jumper from the exposed trace on SPI pins to your free "new" pins.

If you stalk through my answers there are write-ups on two test benches I made and you can get ideas from the various work-arounds I have employed to get my hardware working.
> 2 votes

---
Tags: arduino-motor-shield, nrf24l01+
---


# Question
Title: Serial.begin(): Why not always use 28800?
In a lot of the sample code online people add the line `Serial.begin(9600)` in the setup block.

When I look up what `Serial.begin()` is on the official documentation, it says that it controls the bit per second data transfer.

So the obvious question is, why not use 28800, the highest transfer rate? Why do people settle for 9600? What is the limitation here?

# Answer
> Why do people settle?

People settle because it is more than fast enough. The most common use is just to print some stuff on a terminal for debuggin. 9600 baud is 960 characters per second, or 12 x 80 character lines per second. How fast can you read? :)

If your program is using the serial port for bulk data transfer, you would choose not to settle.

> What is the limitation...

The limits on serial are high. Directly you can use 115200 baud in your programs and it will just work. The Arduino terminal will allow a max of 115200, but other programs such as RealTerm would let you run higher.

Hardware serial will run to 1 M baud. If you read around you will see people have used up to 1 M by directly controlling the UART. You might get benefit of high baud rates for uses such as transmitting via a bluetooth chip. If you are using the hardware serial interface to exchange from chip to chip with just a short distance, then 1 M baud is completely feasible. Think of all the SPI and I2C devices that operate just fine at 1 MHz clock rate.

Over larger distances, you will start to have problems with noise when using logic level (plain 0 to 5V) signalling. To use larger distances, you would add a transceiver to provide robust signalling, commonly RS-232 and less commonly RS-485. With RS-232 you could run a mega bit at distances of 10's of feet.

The microprocessor clock speed will be the real limit. With a hardware UART, the processor must load one byte to the UART every 10 bits (for N81). So when you get to 1 M baud it will be a challenge for the 16 MHz processor to keep the UART supplied with data. A new byte will be sent every 160 clock ticks, which is very few lines of code. For a short burst of data, you might achieve that rate. The message is, the processor will run out of speed before the UART is the limit.

Note, this all applies to **HardwareSerial**, software serial is very different.
> 55 votes

# Answer
In addition to all the interesting answers, it worth mentioning that setting the serial speed to *XXX* bits/s does not necessary imply *XXX* bits/s on the hardware.

Clocks -- even quartz based -- are imperfect and subject to drift. In addition, as the serial clock is usually generated through a power-of-two pre-divisor and (integer) counter, all value cannot be accurately obtained given a base clock frequency. With the help of the start/stop bits, asynchronous serial communication may be tolerant to some clock drift. But this has limits.

For example, if your ATmega328PA is running at 1MHz, you can achieve 9600b/s at 0.2% of error. But at 14400b/s the error is -3.5% (actually communicating at 13900b/s). And at 28800b/s, the error is +8.5% (actually communicating at 31200b/s). All those figures are from *ATmega48PA-88PA-168PA-328PA datasheet, p200*.

This is *not* an issue when two identical devices communicate together (as there are in fact communicating at the *same* speed). It *might* be an issue when communicating between different devices.

Increasing the base frequency does not necessary improve significantly the accuracy. For example, running the same ATmega328PA as above at 2MHz does not really give better results as those are mostly due to rounding errors. But running it 1.8432MHz give very accurate bps from 2400b/s up to 57.6kHz.
> 9 votes

# Answer
I think it is a kind of tradition to use a transfer rate that is not the slowest one (300) but also not one that could eventually cause problems in some setups (28800 or even 115200). The PC serial port (most often a FTDI232 USB adapter) can cope with higher rates but your DIY hardware may not. So 9600 bps has established itself as some kind of standard transfer rate for code examples.
> 3 votes

# Answer
Back in the mists of time, the "gold standard" for remote keyboards (using a a telephone modem, and teletypes, if you remember those) was 9600 baud, initially achievable only over a dedicated phone line. Time moves on, slowly; technology advances, rapidly; and memory moves even more slowly than time (it seems). We can routinely communicate, at least over a several meters, at a couple of orders of magnitude faster than 9600 baud. What was once considered a gold standard is no longer gold, but still thought of as standard.

tl;dr: It's history, not technology.
> 3 votes

# Answer
I think the main reason people use 9600 most of the time is that it's the default baud rate in the Arduino IDE. Also, faster data rates could also be unreliable if the serial signal has to travel a long way - although I have no idea why this was selected as an optimum speed.
> 0 votes

---
Tags: serial
---


# Question
Title: Optmizing print code when writing to file, and reducing print time
First things first, I have found some solutions to this problems but they all involved for printing to serial monitor. I am trying to take the information from the sensors and write them to an sd card. Here is my code so far:

```
//-----Writes Data to SD Card-----//
if(!Data) {
    u8g.firstPage();
    do {
       drawFileError();
    } while( u8g.nextPage() );
    while (1);  // don't do anything more:
}

dcounter++;
if (dcounter=1){

    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();
} else{
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();
}

```

two questions: is it possible for me to reduce this chunk of code into something smaller? is there a way to decrease print time?

Edit: Ahh I see, the problem with my code is that the last few values are floats.Any way to shorten those as well, or do i need to do it individually? I do agree about the adding string parts.

# Answer
> 2 votes
First of all, the only difference between the two parts of the "if" statement is that, the first time, it prints the header. Instead of that code, you could do this:

```
//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.print(strutcDate + "  ");
Data.print(strutcTime + "  ");
Data.print(strgpsStatus + "  ");
Data.print(strmodeIndicator + "  ");
Data.print(strlatitude + "  ");
Data.print(strlongitude + "  ");
Data.print(strspeedOverGnd + "  ");
Data.print(strcourseOverGnd + "  ");
Data.print(t);
Data.print("  ");
Data.print(f);
Data.print("  ");
Data.print(h);
Data.print("  ");
Data.print(hi);
Data.print("  ");
Data.print(press_pKa);
Data.print("  ");
Data.println(str);
Data.close();

```

Like already mentioned, you can append strings with the `+` operator. This would be the final code then:

```
//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
Data.close();

```

FYI, it doesn't seem like you should close the stream every iteration at the end since you only open it the first time.

# Answer
> 0 votes
I would analize what I want to write, extrapolate all numeric value, then create a structure that hold numeric value. So at every write I would write the structure (it is a binary write, so use fixed byte size) followed by all others string(or even place string in different file, but may turn out harder to manipulate or fix in case of problem).

Then to read it you'll need to read back the structure, followed by eventual know number of string. If string may be of unknown number,, just put the number of following string into the struct. Outside string, as you can see, you need no special char to signal the end of chunk of data :)

Unrelated: please, remove all println in the if rather than the header as they are equal to the else; then remove the else statement (but not the else body!) That way the if will open file and add header, and then the code will always add the rest of code. It would be a shame if you edit your else branch and forgot the if, or viceversa. Code style matters, trust me

# Answer
> -1 votes
Maybe this helps with speed. It will however use more memory, so use with caution.

```
Data.println(Header);
Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
Data.close();

```

---
Tags: arduino-mega
---


title: How does serialEvent gets into main()?

text:
# Question
Title: How does serialEvent gets into main()?
Ok, serialEvent "runs after loop()" and it is not an interrupt. AS far as I know main() has two functions - setup and "infinite" loop. So where does serialEvent comes in?

And if I do not want loop() to run and use only setup than I cannot use serialEvent.

# Answer
> 7 votes
Yes you are correct, the event handlers will not do anything in setup. Main runs "setup()", then loops infinity through "loop()", but gives the serial event handlers a chance to run in between. The actual main that runs on the arduino is this:

```
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

```

this is found (on linux at least) in arduino/hardware/arduino/avr/cores/arduino/main.cpp

"serialEventRun()" is in HardwareSerial.cpp, but is not very interesting.

To be clear, Serial itself will still work fine in setup(). If you want to use the same event handler function, all you have to do is call "serialEventRun()" yourself periodically.

---
Tags: arduino-uno
---


# Question
Title: Sample average of analog of current sensor
I have two problems in the code below. This ACS712 sensor is too noisy so I am not getting the count value properly, since I need approximate reading I consider curve is linear, and calculate the slope.

My problems are:

1. When I take a 10 sample average, the first value it reads properly, i.e. 512 is count value, other value taking as 0. I don't why.
2. Once current exceeds 1A, my relay output should go low. Once it goes low it waits for 30s & again it must high the relay high. Since I am checking output in loop, it making high & low without waiting for 30s. Can someone help me how can I do this?

If you used without MStimer, the `newaverage` values print 512 which is my reference, but for other 9 values print `newaverage` as zero.

```
#include <MsTimer2.h>

#define RELAY1  3
#define RELAY2  4

int num_readings=10;
//int total;
int readings[10];
int index;
float CS_Value;
static float Output_Current;
float mad;
float madstd;
float lowlimit ;
float highlimit;
int count;
int total;
int reading;
static int newaverage;
unsigned long Wait_Time=30000;
unsigned long Current_Time;
static int Tripped_Flag=0;

float standard_deviation(int avg1) {
  total = 0;
  for( int i=0; i<num_readings; i++)
    total = total + pow((avg1 -readings[i]), 2);
  return sqrt(total/num_readings);
}

int  average()
{
  total = 0;
  for( int i=0; i<num_readings; i++)
  {
    total = total + readings[i];
  }
  return total/num_readings;
}

void TakeReading()
{

  reading = analogRead(A0);
  readings[index] = reading;
  index = index + 1;

  if (index >= num_readings)
  {
    index=0;
    int avg = average();
    float std = standard_deviation(avg);
    madstd = mad * std;
    lowlimit = avg - madstd;
    highlimit = avg + madstd;

    total=0;
    count=0;
    for(int i=0; i<num_readings; i++) {
      // Check if the values of the readings are within the limits.
      if(readings[i] >= lowlimit && readings[i] <= highlimit) {
        total = total + readings[i];
        count = count + 1;
      }

    }

    // compute the new average
    newaverage = total/count;
    // send it to the serial port (as ASCII digits)

    Serial.print("Newaverage:");
    Serial.println(newaverage, DEC);
    Output_Current = 0.0336666666667*newaverage - 17.17;
    //return(Output_Current);
  }

}

void setup() {
  // sets the serial port to 9600
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);
  pinMode(RELAY2, OUTPUT);
  Relay_Intialize();

}

void loop()
{
  MsTimer2::set(50, TakeReading); // 500ms period
  MsTimer2::start();
  //  CS_Value=  TakeReading();
  Serial.print("current is :");
  Serial.println(Output_Current);
  //if (CS_Value>0.95 && Tripped_Flag==0)
  if (Output_Current>0.95 && Tripped_Flag==0)
  {
    Serial.println("Main Activate");
    Serial.print("Tripped_Flag_status:");
    Serial.println(Tripped_Flag);
    Relay_Activate();

  }
  else
  {

    Serial.println("Main Deactivate");
    Serial.print("Tripped_Flag_status:");
    Serial.println(Tripped_Flag);
    Relay_Deactivate();
  }
  Serial.println(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,");
  delay(1000);

}

void Relay_Activate()
{
  for (unsigned long start = millis(); millis() - start < 10000;)
  {
    digitalWrite(RELAY1,LOW);
    digitalWrite(RELAY2,LOW);
    Serial.println("RELAY GOT TRIPPED");
    Tripped_Flag=1;
  }

}

void  Relay_Deactivate()
{
  digitalWrite(RELAY1,HIGH);
  digitalWrite(RELAY2,HIGH);
  Serial.println("RELAY NOT TRIPPED");
  Tripped_Flag=0;

}

void Relay_Intialize()
{
  Serial.println("RELAY GOT INTIALISE....");
  digitalWrite(RELAY1,HIGH);
  digitalWrite(RELAY2,HIGH);
}

```

# Answer
> 2 votes
I didn't have a look at your item 2, but regarding item 1:

Please consider that in function `TakeReading()`, if the condition is never true, count is 0 when you come to `newaverage = total/count;`!

I don't know what the Arduino does in case 0/0, but -1 may be a proper return value.

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


title: Confusing Arduino Leonardo PWM

text:
# Question
Title: Confusing Arduino Leonardo PWM
I'm having problems with using Arduino Leonardo PWM outputs (I'm actually using YUN board).

I need 4 PWM outputs that generally have the same base frequency of around 10 to 20 Hz or so.

I'm using timer 1 (A-pin-9,B-pin-10,C-pin-11) and timer 4 (A-pin-13)

I get pins 9,10,and 13 PWM output working decent, but for some reason pin 11 PWM frequency is much much higher.

Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Here is my code can anybody see anything wrong? thanks!

```
    #define PWM_4A_PIN  13
    #define PWM_1C_PIN  11

    #define PWM_1B_PIN  10
    #define PWM_1A_PIN  9

    void setup() {
     TCCR1B = TCCR1B & 0b11111000 | 0x05;
     TCCR4B = TCCR1B & 0b11110000 | 0x09;
     analogWrite(PWM_4A_PIN,128);
     analogWrite(PWM_1C_PIN,128);
     analogWrite(PWM_1B_PIN,128);
     analogWrite(PWM_1A_PIN,128);
    }

    void loop()
    {
    }

```

# Answer
> Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Unless D11 is configured as OC0A instead of OC1C, which means that it will work off timer 0.

```
TCCR0A &= ~(_BV(COM0A1) | _BV(COM0A0));
TCCR1A |= _BV(COM1C1) | _BV(COM1C0);
 ...
OCR1C = ...;

```
> 2 votes

---
Tags: arduino-yun, arduino-leonardo, pwm, atmega32u4
---


# Question
Title: Serial input parallel output shift registers with arduino
I need a way to rewrite the switch case part in a more efficient way.

```
int y , x ;
byte dataArray[6];

void setup () {
   pinMode(8,OUTPUT);
   pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);

   Serial.begin(9600);
   dataArray[0] = 0x3 ; //00000011
   dataArray[1] = 0x5 ; //00000101
   dataArray[2] = 0x9 ; //00001001
   dataArray[3] = 0x11; //00010001
   dataArray[4] = 0x21; //00100001
   dataArray[5] = 0x41; //01000001
}

void loop () {
   while (Serial.available()>0) {
     y = Serial.read();
     x = Serial.read();
     switch ( x ) {
     case 1:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     case 2:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     case 3:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 4:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 5:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 6:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     default:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;
     }
   }
 }

```

# Answer
```
unsigned char i;

digitalWrite(8,LOW);
for(i=0;i<=6;i++){
    if(x+i==6) shiftOut(11,12,LSBFIRST,dataArray[y]);
    else shiftOut(11,12,LSBFIRST,0);
    }
digitalWrite(8,HIGH);
delay(10);
digitalWrite(8,LOW);

```
> 2 votes

---
Tags: c
---


# Question
Title: Can I power an Arduino with a computer's motherboard?
I was thinking of using my Arduino to turn on and off a computer remotely. I would like to know if the 5v header pin on a computer's motherboard (which I’m using instead of a USB because the 5v pin provides a constant power supply) can power an Arduino UNO without frying it. If the Arduino can be powered where would the cable from the 5v motherboard pin go into the Arduino?

↑ These are the pins I would like to use

# Answer
> 2 votes
You want to tap off of the +5VSB pin of the ATX or BTX power supply connector and send it to the 5V pin on the Arduino. Where this will directly drive the VCC(5V) of the UNO.

Note that 5V of the USB basically drives the VCC directly, except through a MOSFET that acts as a blocking diode to prevent local VCC from flowing back to the 5V\_USB.

---

Not sure if you are suggesting that the 5V USB is frying Arduino's. If so that is bad. If true; Fix that first.

---

That said (with good 5V usb) you should be able to find or configure (BIOS) so that a USB connector will remain powered, and allow a wake up from mouse movement. Hence a possible solution would be to use a Leonardo/Micro's Mouse emulation to do just that as to wake the PC, without any hardware mod's.

Freeduino Micro's are pretty cheap.

# Answer
> 0 votes
As stated by @mpflaga you can power your Arduino by the 5v power rail. As @ Gerben mentions in a comment, doing this will bypass the polyfuse. Because of this, I create my own Arduino for less than $10 (US) with a power regulator. Using a `L7805ACP` will regulate the power.

Part List:

```
• 1 x P-DIP ATMEGA328P-PU programmed with Duemilanove Bootloader
• 3 x Through-Hole 22pF Capacitors (2 for crystal and 1 for Analog power smoothing)
• 1 x Through-Hole HC-49S 16 MHz Crystal (for clock)
• 1 x 5 Volt regulator (peak current 2 A, nominal )(L7805ACP
  Input Voltage = 7.5 to 18 V
  Output Voltage Low 4.8 Volts Nominal 5 Volts  High 5.2 Volts)
• 1 x 22 uF Capacitor (to stabilize power rail during rapid current draw.

```

---
Tags: arduino-uno, power
---


# Question
Title: 8X8 LED not lightning up according to matrix assignment on a Arduino Nano
I'm currently trying to code a simple program that would allow me to light up an individual LED on an 8X8 LED board using a double array.

Here are the problems:

All the rows can ON individually UNTIL I turn all 8 rows ON. When I do this the last column turns OFF by itself (see attached pictures).

The columns aren't even working properly either. Every time I assign a column ON, the last column faintly turns ON too (one of the LEDs light in that column is broken so that is expect to be OFF. See picture).

I think those are the reasons why I am not able to singly assign a particular LED to be ON according to assignments in the array. If someone could spot my mistakes, it would greatly be appreciated. Thanks!

```
int led2 = 2;
int led3 = 3;
int led4 = 4;
int led5 = 5;
int led6 = 6;
int led7 = 7;
int led8 = 8;
int led9 = 9;
int led10 = 10;
int led11 = 11;
int led12 = 12;
int led13 = 13;
int led16 = 16;
int led17 = 17;
int led18 = 18;
int led19 = 19;

int rowPins [8] ={led19, led18, led11, led7, led12, led5, led4, led16};//assigning each LED to a row.
int columnPins [8] ={led13, led17, led9, led10, led2, led8, led3, led6};//assigning each LED to a column

int image [8][8]=
{

{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},

};

void setup()
{
  for (int i = 0; i<8; i++)
  {
      pinMode(rowPins[i], OUTPUT);
      pinMode(columnPins[i], OUTPUT);
  }
}//end of setup()

void loop ()
{
for (int y=0; y<8; y++)
{
 for (int x=0; x<8; x++)
 {
   if (image[x][y]==1)
   {
     digitalWrite (columnPins[x], HIGH);
   }
   else
   {
     digitalWrite(columnPins[x], LOW);
   }
 }//end of 2nd for loop

  digitalWrite(rowPins[y], LOW);
  delayMicroseconds(100);
  digitalWrite(rowPins[y], HIGH);
}//end of first for loop
}//end of loop

```

# Answer
> 3 votes
I don't see any program statements in the code as shown to cause the described behavior, and imagine it is some hardware problem. (I'm assuming you put some non-zero values into the `image[][]` array; it looks to me like nothing should light up when `image[][]` is all-zeroes.)

Hardware problems break into several categories: A wiring problem (which we can't see without much better pictures); incorrect software setup of HW; temporary misbehavior of the processor; or permanent damage. For the sake of discussion, suppose temporary misbehavior applies.

Temporary misbehavior can be caused by overheating. Overheating can be caused by drawing or sinking a lot of current for too long a time. (If a large current is a fast transient event, it may have little effect.)

Note that most Arduino I/O lines are rated to sink or source at most 40 mA current each. Ground and Vcc lines have higher limits, like 200 or 100 mA. For more details see the spec sheet for your processor; also see ArduinoPinCurrentLimitations at arduino.cc, and Real maximum current for ATmega328? on Electronics SE.

If an LED is directly connected to 5V, it is likely to draw several times more current than nominal. Connecting an LED directly to an Arduino digital line also will allow it to draw too much current. Connecting 8 LEDs to a single processor IO line is likely to cause enough overheating to damage the processor permanently. You may need to add 8 or 16 resistors to your circuit.

Anyhow, instead of trying to debug while using a 100 μs multiplexing delay in your program, and instead of turning on lots of lights at the same time, try turning on one at a time for a brief but visible period each, and see if the array of lights scans ok, via code like the following:

```
int rowPins[]    = {19, 18, 11, 7, 12, 5, 4, 16}; //assign row lines
int columnPins[] = {13, 17, 9, 10,  2, 8, 3,  6}; //assign col lines

void setup() {
  int i;
  for (i=0; i<8; ++i) {
    pinMode(rowPins[i], OUTPUT);
    digitalWrite(rowPins[i], HIGH);
    pinMode(columnPins[i], OUTPUT);
    digitalWrite(columnPins[i], LOW);
  }
}
void loop () {
  int x, y;
  for (y=0; y<8; ++y) {
    digitalWrite(rowPins[y], LOW);
    for (x=0; x<8; ++x)  {
      digitalWrite (columnPins[x], HIGH);
      delay(250);     // wait about .25 seconds
      digitalWrite(columnPins[x], LOW);
    }
    digitalWrite(rowPins[y], HIGH);
  }
}

```

If multiple lights are on there may be miswiring on your project board, or the chip might be damaged, or there may be some roundabout leakage path from columns to ground or from rows to Vcc. If you make the delay longer or add a pushbutton to advance manually, you can check voltages on LEDs and wires, or measure currents in wires, and perhaps deduce what the path is.

---
Tags: led, arduino-nano
---


# Question
Title: Code to use an Arduino Mega 2560 to transfer UART <-> USB to debug an other Microcontroller
I have the following circuit and want to use the Arduino Mega 2560 as an debugger for an other Microcontroller.

So I am looking for the code to redirect the UART input from "P17 (RX2)" to the serial USB and the data coming from the serial USB to the output of "P16 (TX2)"

# Answer
> 4 votes
A very simple sketch to pass serial through looks like this:

```
void setup(){
  Serial1.begin(/*BAUD*/);
  Serial2.begin(/*BAUD*/);
}

void loop(){
  if(Serial1.available()){
    Serial2.print((char)Serial1.read());
  }
  if(Serial2.available()){
    Serial1.print((char)Serial2.read());
  }
}

```

I would advise both run at the same baud rate, otherwise you may need to do some extra buffering yourself if the arduino starts running out of buffer space. If you want to use the mega's USB connection instead of "Serial1" like your schematic, just switch "Serial1" to "Serial"

---
Tags: arduino-mega, uart
---


title: Budgeting Power for 5V Arduino Pro Mini

text:
# Question
Title: Budgeting Power for 5V Arduino Pro Mini
In my low power project, I'm using a Arduino Pro Mini (5V, 16 MHz, ATMEGA328) and a low wattage 3W power supply. Everything else on the system other than the Arduino uses a max of 1.98W.

How much power should I budget for the Arduino Pro Mini (without any mods, ie: disconnecting the voltage regulator and LED)?

# Answer
> 2 votes
Arduino mini, and atmega328 in general use less than 10mA with default arduino code. Turning down unused component (ADC and so on), using deep sleep and optimizing pbc would lover this consumption a lot, in the land of uA

---
Tags: power, arduino-pro-mini
---


title: Selecting a MOSFET Shield

text:
# Question
Title: Selecting a MOSFET Shield
Im building an electrical system for my EBike. My bike has 2 power sources, one is the 48 volt battery, the other is a 12 power converter coming off the battery pack. I need an arduino shield that has 4 switching channels. 2 that can take in the 48 volt and switch it on and off, and two that can take in the 12 volt and switch it on and off. Something that can take the 12 volt to power the arduino uno would be nice but I can find a chip to do that if necessary.

Since these are lights, normally off would be more more efficient but with the power consumption we are talking about, i can probably run the battery all day to the point of dry and the fets eat all of 50 feet worth of power staying closed.

Does anyone know of anything like that? I found several shields out there like this but all of them seem to be setup to take 1 voltage input and switch it between the 4 or 6 fets on the board, not different voltages per fet and since I'm a programmer, not an EE so I have trouble reading the schematics.

Because my grounds have to be tied, its easier to switch the positive on and off than the negative.

# Answer
You can make your own. Buy a protoshield and 4 fets (and a few resistors).

You can also use the shield you linked to, by not using the `+` terminals on the board. Just connect the `+` of the lights directly to the battery and only the `-` of the light to the shield.

The Uno can be powered by up-to 20V, so you can connect it directly to the battery.
> 2 votes

---
Tags: mosfet
---


# Question
Title: Not able to send SMS to Mobile using GSM900A and Arduino Uno
I tried the code shown below (found here)

```
void setup()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+919449835011\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Test SMS -Jay\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}
void loop()
{
}

```

I interfaced my GSM SIM900A module to the Arduino UNO (connections - GSM Tx to Arduino Rx, GSM Rx to Arduino Tx, GSM provided with supply (12V) using external adapter, GSM gnd to Arduino gnd).

I dumped the code into Arduino and then opened the Arduino IDE serial terminal. In the serial terminal, I get `AT+CMGF=1AT+CMGS="+919449835011"Test SMS -Jay\r` being displayed and I am not receiving any sms to my phone. I am not sure if its a problem with the code or connections.

# Answer
> 1 votes
looks like you should be using `Serial.begin(2400);`

also, I'm assuming your sms phone number isn't actually 919449835011 and that that's not actually the number you used in your code

---
Tags: arduino-uno, gsm
---


# Question
Title: Switch 230V 50Hz using a digital out pin
I would like to control normal household appliances like lamps, pumps etc. using my Arduino with up to 5 A. I looked a little around, but it seems, that most relais draw more current than the Arduino is capable of supplying.

How can I switch an 230 V AC current using my Arduino?

# Answer
The good advice to people asking how to drive a relay to control mains voltage is: **don't**.

Start with a complete solution such as those from PowerswitchTail.com and sold by many places: Powerswitch Tail

You can get these already built or in kit form. The 20 $ price is small price compared to damage to people or home you might incur with a home built solution.
> 4 votes

# Answer
Get a logic level n-channel MOSFET that is rated for your relay's voltage and current requirements, and an external DC power supply that's able to put out enough current to drive the relay. Feed the power supply into the relay coil. Connect the ground of the coil to the drain of the MOSFET. Connect the source of the MOSFET to ground. Connect the MOSFET gate to your Arduino control pin.

You might be able to find a relay that will run on 5V at low enough current that you can drive it with a MOSFET and the 5V out from your Arduino, but make sure you don't exceed the total current limit of your Arduino's regulator.

Make sure you put a flyback protection diode in parallel with your relay coil, pointing to block the normal flow of current through the coil, so you don't fry your transistor.

Alternatively you can buy solid state relays that can switch large AC loads using logic level signals, but they're expensive.
> 1 votes

---
Tags: relay, transistor
---


title: Powering motors

text:
# Question
Title: Powering motors
I'm trying to control two DC 3-6V motors with a HG7881 driver and an Arduino Nano, but the Nano is always resetting if it has the same power supply than the driver. I'm connecting the batteries to HG7881 Vcc and Nano Vin (and also same ground).

If I power the Nano with USB and the driver with batteries then it works but that's not a good solution for me.

So the question is, is there any way to make both driver and Nano work with the same power supply?

Thanks!

# Answer
> 1 votes
You need to know the peak current demands of your motor circuit before you can solve this problem. If you have a digital multimeter you can measure the constant current, and make a guess at the peak current. Put your multimeter in series with the motor driver and operate it at full power. The peak current may be as high as twice the steady current of the running motor. Also check the current with the motor under heavy load.

Then you need a power supply that can put out that much current, plus the current of your Arduino, without the voltage dropping below the minimum requirement for the Arduino voltage regulator (~7 volts).

What kind of batteries are you using? If you put 6 C cells in series you'll get 9 volts and pretty high peak current.

# Answer
> 3 votes
If the reset is due to transients when the motor starts or stops, you can get by with isolating Nano power via a diode and capacitor. (See below.) If, on the other hand, the motor is dragging the supply voltage so low the Nano won't run, you may need to add a separate battery for the Nano or upgrade your batteries, as mentioned in Duncan's answer.

To isolate Nano power from motor power, open the connection between battery V+ and Nano Vcc; connect the anode of a diode to V+; connect the cathode to the positive lead of a capacitor of a few hundred microfarads and to Nano Vcc. Connect the capacitor's negative lead to ground. If simple diode+capacitor filtering isn't enough, you probably should attach an oscilloscope and find out more exactly what's happening. Further options include series resistors, wound inductors, and ferrite beads, as seen in some Google images for power supply filtering.

---
Tags: motor
---


title: How to power IR LEDs with arduino?

text:
# Question
Title: How to power IR LEDs with arduino?
I need a circuit or something to power up IR leds as arduino only give 5v and IR leds needs 1.2V. Is there a way to make one arduino pin a power supply of 1.2 V code or something ?

# Answer
Typically, rational control of an LED sets the amount of current that goes through the LED, rather than setting its voltage. You could add series resistors so that when the desired current is flowing through the LED, about 1.2 volts is across the LED and the rest (say 3.6–3.8V) is across the resistor. (See Google images for typical circuits, and see various LED resistor calculator, eg the LED resistor calculator at hacktronics.com.) It also is possible to use PWM to control LED brightness.

Note that if you have 3.6V across a resistor and 1.2V across an LED, you are wasting 3/4 of the power expended. When LEDs are low voltage (ie, like 1.2V for your LEDs, vs. 1.6 for typical red or orange LEDs, vs 3+ V for white or blue) you can put several of them in series. For example, put three of your IR LEDs in series, and calculate R so that 1.2 V drops across a resistor and 3.6 across the series of LEDs. Also try four LEDs in series, and calculate R to drop 0.1 to 0.3 V.

***Edit 1:*** Ignacio Vazquez-Abrams says, a little obscurely, “Getting warmer. But this is a IR LED” and also “Pull up the datasheet for a IR LED. Read it carefully. The AVR can't handle one of the numbers”, perhaps in reference to IR LED current requirements.

Typical 5mm IR LEDs can handle several times more current than typical 5mm visible light LEDs. For example, a typical green LED might be rated 30 mA max sustained current and 20 mA recommended, while a typical IR LED might be rated 100 mA max and 50 mA recommended. Also note that 50 mA is 10 mA more than the 40 mA that most Arduino pins list as absolute max. A sustained current of 40 mA or more in or out of an Arduino i/o pin may damage the processor. If you want to drive a high-current IR LED, use an external driver (eg a transistor). See eg the answer to How can I efficiently drive an LED? in Electronics SE, which shows dropping resistor calculations, constant current sources, etc. Also see links given in JYelton's answer to Infra Red LEDs - Voltage Advice.

Treesrule14 points out “IR leds ... don't emit in the visible light range”, which is true; they emit infrared radiation, or heat. Note, using an IR LED in a remote control usually is incompatible with controlling its average brightness with PWM; the pulses used in PWM would conflict with the pulse train in typical 36, 38, or 40 KHz IR control protocols.
> 4 votes

---
Tags: arduino-uno, led, ir
---


title: Connecting arduino to a PC

text:
# Question
Title: Connecting arduino to a PC
How would you send data wirelessly from arduino uno to a pc?

I know you can connect wifi shield / wifi breakout to arduino and use that, but what other ways are there and how practical would they be?

# Answer
> 1 votes
You have several options. One is Bluetooth and another is nRF24L01+ 2.4GHz Wireless Transceiver. I love the `nRF24L01+`. They are cheap and there are tons of examples online.

The concept with the `nRF24L01+` is to connect the RF24 to a Ft232rl Ftdi Usb to Ttl Serial Adapter. The Ft232rl connects to your PC. Most modern computer languages support communicating via Serial. This is the way to go.

Google around for a ton of tutorials

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


# Question
Title: Receiving and sending on the Arduino Duemilanove with an MAX3232 chip
I have a max3232 hooked up to the RX and TX pins of the Arduino Due. I'm trying to write a simple program to relay messages received from USB and output as RS232 through the chip. Here is my code:

```
char readbyte;

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

void loop(){

  while (Serial.available() > 0 ) {
    readbyte = Serial.read();
    Serial.print(readbyte);
  }
}

```

This program works when I don't have the MAX2323 hooked up (e.g. I send "123" and get "123" echoed back), but when I hook up the MAX2323, the Arduino isn't sending back. I've written another test program that sends random data and it seems to work fine. I'm at a lost at what is wrong with my simple program, can anyone help?

Here is the schematic:

# Answer
With your final comment, the behavior is understandable. The schematic will help

You have wired two devices to the single UART on the processor.

The TX pin (output) on the ATMEGA8 is connected to the input pins of both your MAX2323 and the FT232 chip on the Ardiuno. That works okay because 1 output pin can easily drive 2 inputs.

The RX pin (input) on the ATMEGA8 is connected to the **output** pins of both your MAX and FT. The two transceivers are both attempting to drive the single input -- this is a bad thing. When one output pin tries to drive logic 1 and the other is driving logic 0, one of the devices will win and one will lose. Whether any of the devices is physically damaged depends on whether one device can source enough current to damage the other.

But you haven't broken anything because of the wise series resistors, R8, you see on the schematic. The series resistor limits the current to 5 mA even if you short the RX pin to ground. The series resistor is what creates the unequal behavior:

* The ability of the FT chip to source current and drive a logic 1 is limited. So when the FT chip tries to drive logic 1 and the MAX is output 0, a 5 V drop will be seen across R8. The RX pin is on the MAX side, so the Arduino sees 0.
* The MAX chip is not limited. When it drives 1 and the FT is at 0 there is still 5 V across the resistor. But the RX pin is on the MAX side and sees the 1's (data).

If you want the Arduino to receive from two devices you need to "add" the data correctly with a circuit. There are several ways, here are two:

* Use an OR gate to combine the data. The serial bus is idle at zero. When data comes across it is a sequence of 1 bits. Remove R8 and connect the M8RXD side to the OR input. Connect the MAX to the other OR input. Connect the OR output to the RX input.
* Cheap and small is "wire or'd". Remove R8 and replace with small diode, pointing at RX. Connect small pull down resistor (10k) from RX to ground. Connect external MAX with diode pointing at RX. In this arrangement, either chip will source current towards the RX ping to drive a logic 1, but neither chip can sink current to drive the logic 0. Only the pull down resistor creates the 0.
> 1 votes

---
Tags: serial, arduino-duemilanove
---


# Question
Title: Using VirtualWire and RCSwitch in same PRoject
I have the problem, that I want some Arduinos communicate in a wireless mesh network using the VirtualWire library but also be able to receive (and send) codes for my rc sockets using the RCSwitch library.

I have some Arduinos using VirtualWire and some devices using the hx2262 IC for RC-Decoding.

I want to send and receive messages between the Arduinos (each message must be at least 10 bytes long) and also be able to send and receive messages from the hx2262 RC power sockets.

My idea would be to use VirtualWire for inter Arduino communication and RCSwitch for the power sockets. Both work fine as long as I do not put both libraries on the same controller.

Does anyone have an idea to solve that problem?

# Answer
I finally found a solution: Just use both libraries. The problem I head: VirtualWire uses Pin numbering, RCSwitch uses Interrupt numbering. That was the reason, why it did not work.
> 0 votes

---
Tags: virtualwire
---


# Question
Title: Is it ok to share the same power rail for the arduino and a shield?
I have a two amp 5VDC power rail. I have configured a motor shield to use external DC (by moving a jumper.) Is it ok to share the rail between the arduino's 5V and Gnd pins, and the motor shield?

# Answer
> 2 votes
the Vin pin on the Arduino is the source to the internal voltage regulator. It needs about 7 volts in order to work. If you try to feed 5V into the Vin then the Arduino won't get a full 5V.

Motors draw a lot of current, and cause transients on the power line as they switch on and off. (They will cause transients even in a regulated supply, because it takes the regulator time to respond to the rapidly changing load of the motor.) If you're going to feed both your motor shield and the Arduino's 5V from the same power supply, you will need a reservoir capacitor between 5V and ground as close to the Arduino 5V input as possible. The reservoir capacitor will even out drops and spikes in power to the Arduino.

You'd be much better off feeding 7-9V into the Arduino's Vin. That way it's power is regulated separately.

# Answer
> 0 votes
Yes, but I wouldn't try to do it through the 5V pin on the Arduino. Run a separate 18AWG or larger wire to bring power and ground to the shield.

---
Tags: power, shields, arduino-motor-shield
---


# Question
Title: Improvement security in a domotic project
I recently started with a domotic project, I began creating a lock opening with a RFID currently I'm trying improving the code (I took from http://forum.arduino.cc/index.php?topic=256260)

but I have some question about the security of this system (or any in the domotic way).

First, I know any system is 100% secure. starting from there, I was thinking, what happens if someone known that the system is built in the arduino platform and has some knowlege about it, that person can create a sketch, upload to the board and make "opening" all the pings?, they will have access to that room or thing I'm protecting (or trying). This is just a excercise, I don't want to go in depth about the external security that the board/system must have.

So, searching topics about it, I didn't find anything to help in the solution of this theoretical problem. I read some articles about the bootloader and I think, the solution can be there, I know Arduino is a openSource solution, but I think it doesn't mean insecure, so I think some kind of system who check a key before to load a sketch can help. It can have a default key, who can be used to the developing process, and other key (any) who must be verified, in the current sketch.

I'll try to explain it a little better:

**Developing Mode** Bootloader \[No Key\] -----\> can upload any sketch

**Production Mode** Bootloader\[check mode\] -----\> \[Sketch with the secure key\] \[Upload New sketch\] -----\> Bootloader\[check the key in the new sketch with the key in the current sketch\] (allow or block access, according as appropriate)

I don't have deep knowledge in criptography or bootloading, so I don't know if it's corret solution. I saw there are some way to "download" the code of the board (in a bin), I don't know if with this way the key will be exposed.

can someone tell me if this basic security would be helpful? if it's, can be possible to implement? how? Will the key be exposed in the bin (in case of download)?

# Answer
> 1 votes
First of all, a quick rule that you should follow... It is called Kerckhoffs's principle. Wikipedia states it as this:

> A cryptosystem should be secure even if everything about the system, except the key, is public knowledge.

So, you're never going to reach "full security."

If the attacker can physically access your Arduino, all bets are off. They can upload new code, replace the Arduino, or just simply rewire your circuit so the door opens.

Also, they may be able to remove the RFID module and replace it with another Arduino board that sends random data in the right format hundreds or thousands of times a second. If they find the key code, they can make a new RFID tag with that ID. Thus, it is essential to keep that ID private.

So here's what you should do (in this scenario, password = RFID key's ID):

* **Make sure they can touch or access as little as possible.** If you can, embed the RFID receiver inside a wall so they don't know where the receiver is and would have to break the wall to access it. If they break the wall, they could break the door, so this isn't necessarily a major security flaw. Of course, remember the sensitivity of your receiver.
* **Obfuscate your code:** If you do something where you combine only certain bits/bytes of a few different strings to get a passcode to be compared to the sensor value. Of course, the compiler will remove most of this in an attempt to optimize your code. Note that this isn't actual security, just making the intruder having to do more work. A lot of people discourage this since it gives you a false sense of security, but I encourage it because it will take a little bit longer to hack into your application if they get your code. Remember that at any time they can use `Serial.println(finalPasswordHere);`.
* **If you're really worried, hash it.** AVR chips probably don't have enough power to do advanced hashes like SHA-512. There seems to be a few MD5 hash algorithms for Arduino. MD5 isn't really secure with only a few digits, but if you have a 30 character hash that would take a long time to brute-force it. Add a salt with a ton of random characters (ex: `lsjJK399!$%^&flk2`) that aren't normally found in lookup tables. You'd combine the salt and the ID for the tag into one hash and put that in the code. Then, you'd hard code that hash into the main code. When you want to check if the ID being scanned is correct, you'd hash it with the salt and then compare that to the known hash. If you have more than one ID in the system, it's a good idea to have a different salt for each.

# Answer
> 0 votes
A major factor in digital security is physical security. If you want a secure system you have to keep the bad guys from being able to connect wires and such.

If you have your Arduino inside a secure box inside your locked house, and it is not connected to the internet, the only way an intruder will be able to access it is to get into your house. Once inside the house you should require a second, higher level of security to unlock the Arduino's enclosure and muck with it.

If the Arduino is inside your house and an intruder doesn't have physical access to it, they can't install new apps on it or do ANYTHING with bootloaders.

If you don't use encryption of some sort you will not have very good security.

You can build an RFID or NFC system that uses a challenge-response scheme with encryption.

Something like this: When the house detects a unique RFID identifier, it generates a random number and encrypts it with that key's public encryption key. It sends the encrypted number to the key, which decrypts it using it's private key, then re-encrypts it with the house's public key and sends it back. The house decrypts the number, verifies that it is the correct number, and only then unlocks the door. The house is programmed to time out pretty quickly if it doesn't receive the correct key, to avoid brute force cracking of the encryption.

You also want a system where after a modest number of wrong responses, the system locks out for a couple of minutes.

With crypto, it doesn't matter if an intruder captures the RFID/NFC communication between the house and the key. What's sent is a one-time, encrypted code. Without the encryption keys, the intruder can't do anything with that data. It just looks like noise.

Even better is to add second factor authentication like a numeric code the user has to type, some sort of biometric scan, etc.

The above requires a fair amount of smarts in the key. There are RFID chips out there that have built-in crypto support. I don't know how good they are however. You either need hardware crypto support or a pretty high powered chip (ARM or better) to do crypto in a pocket sized device.

---
Tags: bootloader, sketch, safety
---


title: Arduino IDE #ifdef

text:
# Question
Title: Arduino IDE #ifdef
I use my Arduino IDE to either upload my sketch to a Arduino or ATTiny or ATmega328. As you know each device can have a different pinout. Does the Arduino compiler support `ifdef`, depending on the board I am connected to?

For example

```
#ifdef Attiny85
       a=0; b=1; c=2;
#else
       // arduino
       a=9; b=10; c=11;
#endif

```

# Answer
> 15 votes
Yes. Here is the syntax:

```
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    //Code here
#endif

```

You can also do something like this for the Mega:

```
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    //Code here
#endif

```

Assuming the implementation for the ATtiny is correct, your code should be like this:

```
#if defined (__AVR_ATtiny85__)
       a=0; b=1; c=2;
#else
       //Arduino
       a=9; b=10; c=11
#endif

```

---
Tags: arduino-ide, compile
---


title: What is the best way to get started?

text:
# Question
Title: What is the best way to get started?
I am interested in learning about arduino. What is the quickest and cheapest way to find out if this is something I can and want to do?

# Answer
> 0 votes
By an Arduino starter kit and do all the projects. There are components and instructions for 15 different circuits. This is not cheap, but I think it will give you a good taste for electronics.

# Answer
> 1 votes
The starter kit would get you everything you need to do a whole set of projects. Alternatively there is a PDF on the Arduino site with a whole set of projects in it. You could go through it, put together an inventory of the parts you need, and order those parts from an electronics supplier like Mouser, DigiKey, Jameco, etc, and save some money.

The starter kit is probably worth the extra money, though, because it has everything you need, plus an organized set of lessons that teach you the various skills you'll need.

---
Tags: arduino-ide
---


title: Serial data to arduino problem

text:
# Question
Title: Serial data to arduino problem
I cant understand what is going on here , I was trying to find way to send through Serial a number for example 12 and then extract from it number 1 and 2 and store them in two different variables , but suddenly i was unable to make a simple division !!

# Answer
Anonymous Penguin's code works for me on an Uno after fixing a couple of typos. It is often best to make sure that both the numerator and the denominator are floats to ensure that the result is also treated as a float. So please try the following where the 10 is replaced with a 10.0:

```
while(Serial.available())
{
  float number = (float)(Serial.read() - 48) / 10.0;
  Serial.println(number, 4);
}

```

If you want to deal with each digit separately an array might be best but that will depend on your end goal.

```
const int MAX_LENGTH = 10;
char buffer[MAX_LENGTH];
char lineFeed = 10;

int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
int i = 0;
while( i < length )
{
  //do what ever needs to be done to each character here, I'll just convert them to an int and print them as an example
  Serial.println( buffer[i]-48 );
  i++;
}

```
> 3 votes

# Answer
Do you want to eventually do `12 / 10` or `1 / 10` and `2 / 10`? If the second one, you'll have to read all the serial values into an array and convert those characters to their plain integer values (subtracting 48 from each value). After that, you'll have to add them together with the correct placeholders (`A * 100 + B * 10 + C`).

Basically, the `read()` function returns **one character in the ASCII format**. ACII basically representing characters on your screen with numbers. 48 displays a 0 on your screen, 49 a 1, and so on.

You're also facing a problem where your numbers are getting truncated. This means it cuts off the decimal. For when you send `100`, it is `48 / 10 = 4.8`, however `4.8` becomes just `4`. The same thing happens for 49.

To fix this, you need to use a `float` data type. This allows decimal values. You also want to make sure that the conversion from float to string works correctly for the `Serial.print()` so you don't end up with `4` again.

Final code:

```
while(Serial.available()) {
  float number = (float)(Serial.read() - 48) / 10;
  Serial.println(number, 4);
}

```
> 4 votes

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


# Question
Title: Using Arduino to control a 12v car light system?
I am new, but I am wondering what options I may have to control a 12v line that connects to a light with Arduino i/o.

Given the voltage limitations of an arduino, I am thinking using some kind of 5v relay to switch a 12v line on/off ( if it exists )

Though I was also hoping to be able to utilize the PWM pins in conjunction with a 12v line to 'reduce' it to 6v without using a resistor. (though I would have no idea how to go about this, or if it is even possible).

Any help appreciated.

# Answer
Yes, you can use a relay. However, you'll almost certainly need to drive the relay with a transistor because the current requirements of the relay will be too high for an Arduino pin.

Better to use a logic MOSFET N-channel transistor as an electronic switch. You connect the Arduino's output pin to the gate of the transistor. You connect the + terminal of your 12 volt source to one end of the light, and connect the other wire from the light to the drain on the MOSFET. You then connect the source pin on the MOSFET to ground, and tie the ground of your Arduino to the 12 volt negative terminal.

In this setup, the MOSFET acts as a switch. When you switch the output pin of your Arduino to HIGH, the MOSFET turns on, providing a very low resistance path to ground. Current flows from the +12 volt supply, through the light, through the MOSFET, and to ground.

When the Arduino's output pin is low, the MOSFET acts as an open switch. There's no path to ground so the light is not lit.

You can't use PWM to lower 12 volts to 6 volts without some additional circuitry. PWM rapidly pulses the output from all the way on to all the way off. If you feed a PWM pin into a transistor, it can be used to create a higher voltage and/or current pulsed signal. However, pulsed DC is not the same thing as a lower DC voltage. You'd need to feed the pulsed 12 volts through a reservoir capacitor, perhaps 2 capacitors (and possibly a choke) in order to average out the pulses into a lower DC voltage. That simple approach would work ok for powering a 6 volt incandescent light, but would not be good enough to power a solid state component because the output would not be even enough. It would have a fair amount of ripple and high frequency noise in it.
> 3 votes

---
Tags: pwm, voltage-level, system-design
---


# Question
Title: How does Arduino IDE for mac deal with functions in other files
I'm a longtime C programmer. I've also done a little C++, a little Java, and a LOT of Objective-C, but am fairly new to the Arduino platform and it's IDE.

So far all my sketches have had a single source file.

I see how you copy libraries into the libraries sub-folder of your Arduino source folder, either from the Mac finder or from the IDE.

I'm trying to understand somebody else's project (The "Camera Axe" device for high speed photography.) in that project there is a folder for the entire sketch, "cameraAxe". In that folder there's a file called "cameraAxe.ino", which follows the usual convention that the sketch's main source file needs to be inside a folder with the same name.

However, for this project there are 17 other source ".ino" files. Looking at the main "cameraAxe.ino" file, it only #includes 2 files, "EEPROM.h" and "DogmCA.h", both using the convention of enclosing the filename in angle brackets so the compiler knows to look in it's libraries directory. That makes perfect sense to me, and works like any other C compiler I've ever seen.

What I **DON'T** understand is how the compiler knows where to find the code for the many functions that are defined in other files in the same folder. There a function projectileMenu() which handles the menu for configuring a projectile sensor. That function is defined in the file menu01\_projectile.ino, but it doesn't have a header, and there's no #include anywhere.

Does the compiler treat all the ".ino" files in your sketch folder as part of your source and compile them all together and as if they are one large file? I see tabs in the IDE for each of the files, which suggests that it does.

What if there are dependencies among the files? What defines the order in which they are compiled? Or is it a 2 pass compiler where the order of function definitions doesn't matter?

::wanders off, muttering in confusion::

# Answer
arduino has its own little .ino preprocessor that generates forward declarations (like in a header file) for all function in the project's .ino files. Most of the time this just makes things less confusing for new users.

I'm not familiar with the entire process, but the effect is that any function in any .ino is known to all other .ino code.

Anything with .h or .cpp in a library or in the project file is treated as normal c++ code and not subject to arduino's manipulations. It will need "#include"s.

If you are interested, there is a hack to make arduino not mess with a function in a .ino file: add an empty "throw()" like this:

```
void foo() throw() {
}

```
> 3 votes

---
Tags: arduino-ide, c, build
---


title: Attiny84A and IR Sensor

text:
# Question
Title: Attiny84A and IR Sensor
I have a GP2Y0A21YK0F Sharp IR Analog Distance Sensor 10-80cm + Cable, Arduino Compatible and its is connected to my Arduino. All works well and I can read the analog data with the following code:

```
#include <SoftwareSerial.h>
#define RX 2 // receive
#define TX 3 // transmit
#define SEN1 4
SoftwareSerial mySerial =  SoftwareSerial(RX, TX);

void setup()
{

  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{

   int reading = analogRead(SEN1);
   mySerial.println(reading);
   delay(500);
}

```

When the code runs on the Attiny with the `GP2Y0A21YK0F` IR Sensor connected, the Attiny84 resets over and over. The Attiny84 and `GP2Y0A21YK0F` are part of the same circuit e.g. Attiny and `GP2Y0A21YK0F` share the power and ground rail.

When I disconnect the `GP2Y0A21YK0F`, the program runs and stops resetting. I was able to reproduce this on an Attiny85 and ATMega328.

The strange thing is, it works fine on the Arduino. Any help is greatly appreciated.

# Answer
It sounds like the microcontroller is browning out.

IR sensors are notorious for taking a lot of power when they operate; often they will tax a small power supply and cause the voltage to droop low enough to reset/brownout the microcontroller.

Try either putting a fairly beefy capacitor on the power bus, or getting a larger power supply.

Hope this helps!

(**edit**: I reverted another user's edit to this answer; "droop" is in fact the correct term for what is going on: http://en.wikipedia.org/wiki/Voltage\_droop)
> 3 votes

---
Tags: power, attiny, analogread
---


title: Arduino starter kit servo is shaking

text:
# Question
Title: Arduino starter kit servo is shaking
In the example of the arduino starter kit the point is to use a potenciometer to control a servo.

The code is

```
angle = map(potVal, 0, 1023, 0, 179);

```

The output in the serial

```
potVal: 1023, angle: 179
potVal: 1015, angle: 177
potVal: 1023, angle: 179
potVal: 1016, angle: 177
potVal: 1023, angle: 179
potVal: 1023, angle: 179

```

I noticed that the servo is shaking like trying to go passing over the 179, when it is suppose to use an angle max 180º (0-179)

What could be the problem?

# Answer
I like this method the best (personal preference) for smoothing signals:

```
//In setup
int bufferedVal = analogRead(A0);
int unbufferedVal = analogRead(A0);
#define _TOLERANCE_ 5

//The loop
unbufferedVal = analogRead(A0);
if(abs(unbufferedVal - bufferedVal) >= _TOLERANCE_ ) {
  bufferedVal = unbufferedVal;
}

```

This finds the error using the `abs()` function (absolute value; makes sure it is positive).

Another thing you can do is round it to the tenth placeholder (i.e. 88 -\> 90, 83 -\> 80) so it always is a good number to work with:

```
int val = analogRead(A0);
val += 5;
val = val / 10;
val = val * 10;

```

The last two lines work because of the lack of precision that integers offer with decimals. If I divide 88 by 10, it doesn't output 8.8; it outputs 8 instead. We then multiply by ten again so it isn't 8 when it really should be 80. The only problem with this is it only rounds down. We can fix this by adding 5 (the halfway point between 10 and 0). That way, it goes: 88 to 93 to 9.3 to 9 to 90.

**NOTE:** I'm not sure if the compiler will notice the redundancy of the last two lines. If it acts weird, try using the `volatile` keyword.
> 4 votes

# Answer
If the problem is due to jittery pot readings, you may want to smooth the `potval` data sequence by code like the following, where `rawreading` stands for what you just read from the potentiometer's input line.

```
potval = alpha*potval + (1-alpha)*rawreading;

```

Set `alpha` to a number (eg 0.8 or 0.9 or 0.95 etc) between 0 and 1. `alpha` represents the fraction of the old value that you retain, and `1-alpha` represents the fractional influence of the new raw reading. `alpha` closer to 1 causes smoother but slower response.

If you prefer integer arithmetic for faster or smaller code, then represent `alpha` as a ratio of integers. For example:

```
potval = (potval*12 + rawreading)/13;

```

The technique mentioned above is called *exponential smoothing* or *exponential moving average*.
> 5 votes

# Answer
Since the previous answers were all code-related, let me suggest you use a smoothing capacitor. In noisy environments, or where you want to get more consistent readings, place a capacitor across your signal lines (signal to ground). The result is less "spikes" in your readings, and can sometimes cause a slight delay in signal changes, as charge has to build up in the capacitor before the voltage goes up.

http://www.learningaboutelectronics.com/Articles/What-is-a-smoothing-capacitor
> 1 votes

---
Tags: arduino-uno, servo, map
---


# Question
Title: How to serial connect arduino galileo to alarm system
i'm a little new in this. I have an alarm system panel which has TX,RX wires with 12V output/input.

how can i read the output with arduino and control it with serial communication?

# Answer
First of all, you'll need to make sure this is UART and not another protocol. Don't worry, if it's not UART the worst thing that could happen is jumbled data.

After that, you will need a 12v to 5v (or 3.3v) logic level shifter. When you have that you'll need to connect the Arduino to the system through the level shifter to pins 0/1.

You won't know what you'll receive or can send without looking at the serial output and doing a little tinkering. You don't even know what the serial port does. It could just be for setting up the system.
> 1 votes

---
Tags: serial, arduino-galileo
---


# Question
Title: Sonar and servo stop working when usb cable unplugged
I am using the following components to build simple motobot:

* Arduino Uno
* Arduino motor shield,
* servo,
* sonar HC-SR04,
* magician chessis,
* DC adapter with 4 AA batteries.

All works fine while USB cable is plugged. As soon as I unplug USB cable servo and sonar stop working, although motors connected to motor shield continue rolling.

From what I read around internet motor shield operates with 7-12V voltage. I need 5V for sonar and servo. So they both are connected to 5V pin on the shield board.

How could I overcome this issue?

# Answer
Sonar modules are notorious for pulling so much instantaneous power during their brief pulses that they often reset the processor, causing the Arduino to start all over from the beginning.

Do you have any way of knowing whether your program is executing more-or-less normally, or if your program in the Arduino is getting reset? If not, you need better debugging tools.

## (tangential rant about debugging tools)

Many people debug by sprinkling their code with print(F()) statements that get sent to a LCD screen or a serial port. Other people debug by sprinking their code with statements that turn on and off a series of LEDs of various colors, or at least a single LED with a (hopefully easy-to-decode) blink code. Some kinds of problems are much easier to track down with an oscilloscope.

## dealing with high-current pulses

My best guess is that the sonar is pulling very brief high-current pulses from the battery, which causes the battery voltage to droop low enough to reset the Arduino. When the USB cable is plugged in, (I'm guessing that) the additional power supplied by the USB cable somehow keeps the Arduino from resetting.

Many sonar modules (very briefly) pull 1 A or 2 A, far more than a USB cable or a handful of AA batteries can supply.

There are many ways to solve that problem, but if I were you I would first see if that is really the problem in this case. Possibly the quickest way to tell is:

* Use at least 2 separate battery packs.
* Hook all the grounds of all the battery packs and all the devices together.
* hook the positive power of one battery pack to the Arduino and nothing else.
* Hook the power lead of all the other devices to some other battery pack (ideally a different battery pack for each device).

Then run the test again. This should give you a clue as to whether the problem is the Arduino seeing power-supply droop (which separate battery packs should "fix"), or something else.

If the problem really is power supply droop, there are a variety of ways to fix it:

* (a) Many people recommend: use a large 1000 uF capacitor directly across the power pins of the sonar, and a 10 Ohm or 100 Ohm resistor between the battery positive and that capacitor. (a) (b) (c) (d) (e) (f)
* (b) Use a large capacitor directly across the power pins of the Arduino, and a diode from the battery to that capacitor so that normally the diode allows the battery to charge the capacitor, but when the sonar or whatever briefly drags the battery voltage to a low level, the diode blocks the sonar from pulling energy "backwards" out of that capacitor, and the capacitor is large enough to run the Arduino during the sonar pulse.
* (c) Get a dedicated "logic" battery array to power the Arduino and a few LEDs, etc., and a separate (often much larger) "dirty power" battery array to power the sonar, motors, etc.
> 1 votes

# Answer
Add an extra 2-4 AA batteries in series. 4 x AA is 6V for fresh batteries, 4V when the batteries are at the end of their life, which is not enough.

An alternative is to get a boost converter, e.g. this, so you can supply 5V with less than 5V.
> 0 votes

# Answer
Because I use nodejs with help of johnny-five library I asked the question on the project wiki. This is the answer from Rick Waldron:

You can't unplug the USB, doing so kills the communication between the program and the board. Those components that continue functioning only do so b/c they are still receiving power. To free the bot from tethers, check out the guide at the bottom of this page: https://github.com/rwaldron/johnny-five/wiki
> 0 votes

---
Tags: arduino-uno, arduino-motor-shield
---


title: Blank Serial Print AdaFruit BTLE

text:
# Question
Title: Blank Serial Print AdaFruit BTLE
I working on a prototype with an Arduino UNO and an AdaFruit Low Energy Blue tooth

I have an array of uint32\_t that I am trying to send via blue tooth to a given device. I don't think i can send the array so I was trying to send it as a comma separated string.

I can print out each individual index of that array just fine, but its completely blank when i try to make a comma separated String.. See code and comments below.

**Ay Array:**

```
uint32_t items[]= {0,3513728,7925384,0,0,0};

```

**In My Loop:**

```
String output = "";

for(int i = 0; i<6;  i++){

  BTLEserial.print(items[i]); // Prints as expected
  output += getStringForUI32_T(items[i]);
  output+=",";

 }
 BTLEserial.print(output); // prints BLANK

```

I imagine this has something to do with memory but I am at a complete loss.. Please help!

# Answer
> 1 votes
I'd probably do it directly like:

```
for(int i = 0; i<6;  i++) {
  BTLEserial.print(items[i]);
  BTLEserial.print(',');
}
BTLEserial.println();

```

But with the string I think it would be something like:

```
String output = "";

for(int i = 0; i<6;  i++) {
  output += getStringForUI32_T(items[i]);
  output+=",";
}
BTLEserial.println(output[0]);

```

But as someone else got it working using String on your adafruit thread maybe this is just barking up the wrong tree.

---
Tags: arduino-uno
---


# Question
Title: Receiver xbee receiving data even if the Transmitter is not sending?
TX code:

```
#include <SoftwareSerial.h>

const int MAX_LENGTH = 2;
char buffer[MAX_LENGTH];
char lineFeed = 2;

SoftwareSerial   Xbee(10, 11);

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

void loop() {
  int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
  int i = 0;
  while( i < length )
  {
    Serial.print(buffer[i]-48);
    Xbee.print(buffer[i]-48);
    i++;
  }
}

```

RX code:

```
const int MAX_LENGTH = 2;
char buffer[MAX_LENGTH];
char lineFeed = 2;

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

void loop() {
  int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
  int i = 0;

  while( i < length )
  {
    Serial.print(buffer[i]-48);
    i++;
  }
}

```

NOTE :

1- The Rx xbee is receiving data even if am not sending and even if the TX xbee is powered off

2- When i send data from the TX xbee id didn't get revived by the RX xbee

I need to solve both problems.

\*** What i need exactly is to send serial data from my pc to arduino and send it wireless through xbee and then receive to the other arduino connected to my circuit

# Answer
> 2 votes
The reason that it is printing characters with no input is that the readBytesUntil function has a timeout. If no new characters are received for a certain amount of time, "Serail.setTimeout()" seconds, it will just continue with the code. the default timeout is 1 second.

The reason you are not receiving what you transmit (or at least a reason) is that the RX code does not read from an xbee, but reads from regular "serial".

I recommend you try something simple first to test the xbee's configuration, like having TX run this:

```
void loop(){
    xbee.println("Hello");
    delay(1000);
}

```

and RX run something to echo serial like this:

```
 void loop(){
     if(xbee.available()){
         Serial.print((char)xbee.read());
     }
}

```

And make sure you set up an xbee object an the receiving side first.

---
Tags: arduino-uno, xbee, c
---


title: Power supply voltage confusion

text:
# Question
Title: Power supply voltage confusion
I just ran into this article: Arduino: What adapter?.

It says that the external power supply should be 9-12V. That really surprises me, since my Arduino Uno can also be powered via USB, which is 5V.

Later he talks about a 9V pin. But I can only see a 5V and 3.3V pin on mine. Is he talking about a different version of Arduino?

Judging from the picture, his Arduino looks slightly different from my Arduino Uno R3, but I can't tell which version is on the picture.

# Answer
> 9 votes
The board has a voltage regulator which converts 9-12V to the 5V that the chip uses.

Why does it need 9V if the board works at 5V? Well, it doesn't need 9 exactly, but it needs something greater than 5. The reason for this is that the regulator has whats called a dropout voltage.

Looking at the schematic of the Uno we see it uses a NCP1117, which has a dropout of 1.2V. So the minimum voltage you can give it to get 5V is 6.2.

The 9V pin is the Vin pin which is at the same level as the input voltage (before converting).

# Answer
> 7 votes
And the third part of your question: It is possible to bypass the voltage regulator and feed REGULATED 5 volts directly to the 5V pin.

That's how the Arduino is powered using USB. The USB power is already regulated 5V, and is fed directly to the 5V pin.

Beware of doing this yourself however. You better be certain the 5V you're feeding in is a clean, filtered and regulated 5V. If it's not you run the risk of destroying your Arduino (and possibly anything connected to it's 5V lines.)

---
Tags: voltage-level
---


# Question
Title: What are the current limits on an Arduino Micro?
Just to make sure I don't set my board on fire, is there any information out there about the maximum current per pin/pin group on an Arduino Micro?

This page states I can get 40mA per pin, but are there limits on group of pins?

As stated here, there are pin groups which should not exceed 100mA. But could not find anything about that in the ATmega32u4 datasheet, or any other Arduino Micro related websites.

# Answer
> 4 votes
It's in the notes in section 29.2:

> 3. Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:
> ATmega16U4/ATmega32U4:
> 1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
> 2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
> 3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
> 4.)The sum of all IOL, for ports F0-F7 should not exceed 100 mA.
> If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.
> 4. Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:
> ATmega16U4/ATmega32U4:
> 1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
> 2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
> 3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
> 4)The sum of all IOH, for ports F0-F7 should not exceed 100 mA.

Note that the device will likely not *fail* if these are exceeded, but the rest of the numbers in the table may no longer apply.

---
Tags: arduino-pro-micro
---