# Question
Title: How do you wire a ssr relay to a arduino nano
I am trying to wire a fss1-102z 5v ssr relay to my arduino nano but i cant get it to work here is my circuit. It stays stuck on and i cant get it to turn off.

Bluetooth control code

```
char val;         // variable to receive data from the serial port
int ledpin = 2;  // LED connected to pin 2 (on-board LED)

void setup()
{
  pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT

    Serial.begin(9600);       // start serial communication at 115200bps

}

void loop()

{
  if( Serial.available() )       // if data is available to read
  {
    ;
  }
  val = Serial.read();         // read it and store it in 'val'

  if( val == 'a' )               // if 'a' was received led 2 is switched off
  {
    digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2
  }

  if( val == 'A' )               // if 'A' was received led 2 on
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
  }

  if( val == 'b' )               // if 'b' was received led 3 is switched off
  {
    digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3
  }

  if( val == 'B' )               // if 'B' was received led 3 on
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
  } //else (ledpin = 3, LOW)        //set led pin 3 to low state

  if( val == 'C' )               // if 'C' was received led 2 on for 1 second
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'D' )               // if 'D' was received led 3 on for 1 second
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin, HIGH);      // turn Off pin 3
  }

  if( val == 'E' )               // if 'E' was received led 2 on for 5 seconds
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'F' )               // if 'F' was received led 3 on for 5 seconds
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin, HIGH);       // turn Off pin 3
  }

  if( val == 'G' )               // if 'G' was received turn led pin 2 on for 500ms then switch off and turn on pin 3 for 500 mili seconds then off
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(500);                     // wait 500mili second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 2
    delay(500);                     // wait 500 mili second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'h' )               // if 'h' was received switch off all pins
  {
    digitalWrite(ledpin = 13, LOW);    // turn Off pin 13
    digitalWrite(ledpin = 2, HIGH);      // turn Off pin 2
    digitalWrite(ledpin = 3, HIGH);      // turn Off pin 3
}

  if( val == 'H' )               // if 'H' was received switch pin 2 on and off 1000 times

  for(int i = 0; i < 1000; i++)
  {
    digitalWrite(ledpin = 2, HIGH);  // turn ON pin 2
   delay (1000); //wait 1000 mili seconds
    digitalWrite(ledpin = 2, LOW);  // turn Off pin 2
   delay (1000); //wait 1000 mili seconds

  }

}

```

# Answer
> 2 votes
According to its datasheet, the `FSS1-102Z` doesn't work with DC-voltage. Also the minimal voltage required is 50VAC. Here is the excerpt from the datasheet:

# Answer
> 0 votes
* Is it really 5v relay?
* Need your code.
* Check your output is really 5v.

You do a lot of mistakes:

```
Int ledPin2=2;
Int ledPin3=3;
...
pinMode(ledPin2,OUTPUT);
pinMode(ledPin3,OUTPUT);
...
digitalWrite(ledPin2,HIGH);

```

I am on way now. I will edit and my answer when get back. Now correct your code

**EDIT**

You should improve your code... I edited it with switch cases. Also edit your comments because they are wrong!!! In the end there is `Serial.printout` states of pins. If you want uncomment them.

Here is the edited code:

```
char val;         // variable to receive data from the serial port
int ledpin2 = 2, ledpin3 = 3, ledpin13 = 13;  // LED connected to pin 2 (on-board LED)
bool status = true;

void setup()
{
  pinMode(ledpin2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin3, OUTPUT); // pin 3 (on-board LED) as OUTPUT
  pinMode(ledpin13, OUTPUT);
  Serial.begin(9600);       // start serial communication at 115200bps

}

void loop()

{
  if( Serial.available() )       // if data is available to read
  {
  val = Serial.read();         // read it and store it in 'val'
  switch (val){
    case 'a':
    digitalWrite(ledpin2, HIGH);    // turn ON pin 2
    status = true;
    break;

    case 'A':
    digitalWrite(ledpin2, LOW);
    status = true;
    break;

    case 'b':
    digitalWrite(ledpin3, HIGH);
    status = true;
    break;

    case 'B':
    digitalWrite(ledpin3, LOW);
    status = true;
    break;

    case 'C':
    digitalWrite(ledpin2, LOW);  // turn OFF pin 2
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin2, HIGH);      // turn ON pin 2
    status = true;
    break;

    case 'D':
    digitalWrite(ledpin3, LOW);  // turn OFF pin 3
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin3, HIGH);      // turn ON pin 3
    status = true;
    break;

    case 'E':
    digitalWrite(ledpin2, LOW);       // turn OFF pin 2
    delay(5000);                      // wait 500 milli seconds
    digitalWrite(ledpin2, HIGH);      // turn ON pin 2
    status = true;
    break;

    case 'F':
    digitalWrite(ledpin3, LOW);  // turn ON pin 3
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin3, HIGH);       // turn Off pin 3
    status = true;
    break;

    case 'G':
    digitalWrite(ledpin2, LOW);  // turn ON pin 2
    delay(500);                     // wait 500mili second
    digitalWrite(ledpin2, HIGH);      // turn Off pin 2
    digitalWrite(ledpin3, LOW);  // turn ON pin 2
    delay(500);                     // wait 500 mili second
    digitalWrite(ledpin3, HIGH);      // turn Off pin 2
    status = true;
    break;

    case 'h':
    digitalWrite(ledpin13, LOW);    // turn Off pin 13
    digitalWrite(ledpin2, HIGH);      // turn Off pin 2
    digitalWrite(ledpin3, HIGH);      // turn Off pin 3
    status = true;
    break;

    case 'H':
    for(int i = 0; i < 1000; i++)
  {
    digitalWrite(ledpin2, HIGH);  // turn ON pin 2
    delay (1000); //wait 1000 mili seconds
    digitalWrite(ledpin2, LOW);  // turn Off pin 2
    delay (1000); //wait 1000 mili seconds
  }
  status = true;
    break;
  }
  }

  /* Print out state of pin */
  /*
  if (status) {
   Serial.print("ledpin2 = ");
   Serial.print(bitRead(PORTD,2));
   Serial.print(" ,ledpin3 = ");
   Serial.print(bitRead(PORTD,3));
   Serial.print(" ,ledpin13 = ");
   Serial.println(bitRead(PORTD,7));
   status = false;
  }*/
}

```

---
Tags: arduino-nano, relay
---


# Question
Title: I can't scroll Arduino IDE's example & scketch lists down
I have Arduino IDE 1.0.5 in win7 x64. I have so many library units. A pity that I can't scroll down to my other options. Is it Arduino.exe's problem or something else? How can I add triangle to scroll down and scroll up to see whole Sketchbook and Examples list? Thanks.

# Answer
Try using 1.5.+. It has scroll arrows to allow larger lists of menus, bigger than the screen.

I find that most, if not all, sketches work equally well, if not better.

Up to 1.5.6r2 uses the same version of compiler as 1.0.+'s. 1.5.7 and newer uses a new compiler, that is more sctrict. All stock libraries work. And well written 3rd parties work. I personally use 1.5 and test backwards to 1.0.

There is a fork of 1.0 called ERW that has the scrolling. But 8t is becoming obsolete.
> 2 votes

# Answer
You can get to the examples in Explorer. Just go to `My Documents`\ `Arduino`\ `libraries`\ `<library-name>`\ `examples`.

This one made me chuckle. Thank you for sharing.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: What does the line "while (! Serial);" do in an Arduino program?
I'm new to Arduino, and I am trying a couple of tutorials. What does this line do in a program?

```
while (! Serial);

```

# Answer
On boards with an FT232 chip or other USB-\>Serial bridge chip (Uno, Mega, etc) it does absolutely nothing.

On boards with a direct USB connection, such as the Leonardo or the Yùn it waits for an active serial connection to be established by the PC (i.e., for the serial port to be opened by a piece of software).

When you open the serial port of a board like the Uno or Mega the whole board usually resets*, so opening the serial port allows you to see the first bits of the serial data. On the Leonardo etc it doesn't reset when you open the serial, so any serial output during the setup() function would be missed. Adding that line makes the board pause until you open the serial port, so you get to see that initial bit of data.

\*) Unless you specifically write some software that doesn't assert DTR when you open the port
> 12 votes

---
Tags: serial
---


# Question
Title: Cannot send two arguments from a WebClient
I am using the Arduino WifiWebClient to insert records into a RoR (Ruby on Rails) app. It works but it only inserts one field regardless of the number of arguments I send.

For example, if I test with Curl

```
curl -d "sale[itemId]=1234&sale[machineId]=4567"  http://myapp.herokuapp.com/sales

```

It will create a Sale record and populate both fields itemId and machineId. Everything OK.

But when I send the following instruction from the Arduino, it will only populate the first field:

(I am only including the POST method to simplifly the code, the rest of the code is similar to http://arduino.cc/en/Reference/WiFiClient)

```
void sendPOST() //client function to send/receive POST request data.
{
if (client.connect(URL,PORT)) {  //starts client connection, checks for connection
Serial.println("connected");

Serial.println("POST /sales HTTP/1.1"); //download text
Serial.println("From: Arduino1");
Serial.println("Host: evening-sierra-3769.herokuapp.com");
Serial.println("User-Agent: HTTPTool/1.1");
Serial.println("Connection: close");
Serial.println("Cache-Control : no-cache");
Serial.println("Pragma: no-cache");
Serial.println("Expires: -1");
Serial.println("Content-Type: application/x-www-form-urlencoded");
Serial.print("Content-Length: ");
Serial.println(31);
Serial.println();
Serial.println("sale[machineId]=\"09876543211234\"");
Serial.println("sale[itemId]=\"09876543211234\"");
Serial.println();

client.println("POST /sales HTTP/1.1"); //download text
client.println("From: Arduino1");
client.println("Host: evening-sierra-3769.herokuapp.com");  // Will be needed if apache is configured for VHOSTS
client.println("User-Agent: HTTPTool/1.1");
client.println("Connection: close");
client.println("Cache-Control : no-cache");
client.println("Pragma: no-cache");
client.println("Expires: -1");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(31);
client.println();
client.println("sale[machineId]=09876543211234\r\n");
client.println("sale[itemId]=09876543211234\r\n");
client.println();

Serial.println("ARDUINO: HTTP message sent");
delay(3000);
if(client.available())
{
  Serial.println("ARDUINO: HTTP message received");
  Serial.println("ARDUINO: printing received headers and script response...\n");

  while(client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
}
else
{
  Serial.println("ARDUINO: no response received / no response received in time");
}

client.stop();
}

```

# Answer
Solved!

Changed the following lines:

```
client.println("Content-Type: multipart/form-data");
client.print("Content-Length: ");
client.println(63);
client.println();
client.println("sale[itemId]=123456789012341234&sale[machineId]=123456789012341234\r\n");
client.println();

```
> 1 votes

---
Tags: arduino-uno, wifi, shields, web-service
---


title: uBlox LEA 6H and UNO no data

text:
# Question
Title: uBlox LEA 6H and UNO no data
While using NEO 6M and getting close-to-perfect accuracy, connecting the 3dr uBlox LEA 6H shows incoming characters, but gibberish data (at 38400) like it is connecting to a wrong baud rate (although it isn't, i've checked it with u-center and works when connected to Ardupilot). So i guess it is some kind of configuration to show only certain parts of NMEA (if it is showing NMEA and not something else).

# Answer
Your uBlox LEA 6H is most likly configured to use the UBX binary protocol and not NMEA at all. This protocol, as well as how to switch your LEA 6H between NMEA and UBX is in this document, from the uBlox website: http://www.u-blox.com/images/downloads/Product\_Docs/u-blox6\_ReceiverDescriptionProtocolSpec\_%28GPS.G6-SW-10018%29.pdf

You may be able to use the code from the ArduPilotMega project to communicate in UBX, they use the UBX protocol and the code is open source, but I can't guarantee its very good quality.
> 2 votes

# Answer
You can configure the ublox lea6H GPS to read either through NMEA protocol or the UBX protocol. You just need to send some configuration messages. For good data rate it is better to use UBX protocol as it gives data in binary format inducing less delay.In case you need to test your device you can use my GPS code for arduino mega - customized ardupilot gps code - UBX protocol.

https://github.com/ksskarthik/Team\_Pushpak/blob/master/TP\_GPS
> 1 votes

---
Tags: arduino-mega, tinygps, gps
---


title: Adjust resistance of a circuit

text:
# Question
Title: Adjust resistance of a circuit
I need to emulate a component that measures an input mechanically and varies resistance from 0 to infinity (a more detailed set of specs list it at 20-1,000ohms, though I'll have to actually check its true values myself once I have physical access to it).

My aim is to replace this troublesome mechanical component with a current (read as available and serviceable) component, and convert the signal from the new component into an emulated signal (varying resistance) from the old component.

I am not certain as to the resolution required (how big the steps can be), though it may be able to handle 50ohm 'leaps', just judging by the range of mechanical movement and my past experience with replacing similar mechanical systems with ready-made kits for conversions. I'd like to smooth the curve a whole lot more than 50ohm leaps though.

I have barely an idea where to begin on this. I thought maybe a resistor ladder and a set of transistors triggered by the arduino to connect into the different points in the line, though I suspect there has to be a better way to achieve a much better result (and I don't think I have enough outputs for that anyway).

Is there a digital component that can vary its resistance using a PWM signal or maybe an analog signal from an arduino?

FYI, I greatly appreciate your input.

**EDIT**

The controller provides a constant voltage to the component, and the controller then looks at the ground (the voltage over a static resistor) I presume. It is an actual load.

I may be able to provide a variable voltage to the controller on its ground pin, though I have never seen that done on them before. I think that may be the trick, though the controller may(??) dislike it? I can try that.. The next best thing (only 2nd because it requires more components) would be the digital pot.

Anyone ever forged a return signal on a circuit thats supposed to supply its own constant voltage to a resistor type sensor?

# Answer
What about a digital potentiometer Digital Pot

Many types available, generally controlled via a serial interface e.g SPI
> 3 votes

# Answer
A JFET can act as a voltage-controlled resistor. It will need additional components if you require precision (a shunt resistor and a couple of op amps come to mind), but it should do. JFETs are rarer than they used to be, but still should be available for a few decades.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Mega 2560 - TFT 3.5 Display is not working with libraries suggested
I attached two images of the shield.

I bought an Arduino Mega 2560 R3 with a TFT 3.5 Display shield in China.

What I know from my research is:

1. There are no data sheets available in the Internet.
2. The factory's web site, in China, is in Chinese, and there is no information in English.
3. I achieved to know the factory is www.mcufriend.com, because it is the only reference in the shield.
4. Apparently the drive to use is R61581.
5. Using suggested libraries from Henning Karlsen (http://www.henningkarlsen.com/electronics/library.php) (UTFT, UTFT Geometry, tiny Fat, UTFT Tiny Fat, UTouch and UTFT buttons) . These libraries don't work with this shield.
6. Some people say that this shield requires 3.3 \[Volts\] to work, but the Vcc pin connected goes to 5V and it contains a Voltage regulator. I suppose it drops the voltage from 5\[V\] to 3.3\[V\] in the middle of the back side of the screen shield (see the upper photo - U1).
7. The specs that I found, say that this is a 262,144 Color 320x480 Dot Graphic LCD screen using a LCD driver a Si TFT Panel.
8. This screen includes a touch pad and a Micro SD memory reader.
9. After using the geometry test included in the library folder UTF Geometry mentioned on #5, and using all the drivers found in the documentation included by Henning Karlsen in a .pdf doc, I couldn't get this shield to work.

Does anyone know how to make this screen work?

I know is too much technology involved to be a fake shield, but it should be very useful to have this working. Do you agree with me?

# Answer
> 0 votes
I have the same display. It has ILI9137 chip using 8-bit mode, so original Henning Karlsen UTF library doesn't work. You can find this library patched to support this display using Arduino MEGA at https://github.com/dgolda/UTFT

If display wouldn't work it is probably broken. I've received first piece broken - only backlight was working, but second and third was OK.

---
Tags: arduino-mega
---


title: Cheap arduino wi-fi TRIGGER

text:
# Question
Title: Cheap arduino wi-fi TRIGGER
I am looking for cheap way to have very basic wireless communication between an Arduino and a iphone. I don't need to send complex data, it would be sufficient to "trigger" the arduino: let's say it is reading a certain pin voltage and waiting for it to be up in order to do stuff, my goal is to trigger this pin up by any (wireless and iphone friendly) mean.

I have figured out two solutions: wi-fi shield, cheap RF transceiver. The problem with the latter is that it is not trivial to communicate with a RF transceiver from an iphone. I should add another arduino controlling an RF transceiver on the iphone side and commanding this arduino with an usb.

The wi-fi shield on the other hand is too expensive. Even small routers such as the wr703n (30 euro more or less) is too expensive in my opinion. I just want to send a "bit" of information, so I don't want to spend more than 10 euro.

The third option would be to hack some cheap wi-fi controlled tool, such a lamp or plug: do you know any? Do you have any other idea?

Thanks!

# Answer
WiFi you either need a WiFi router or for either the iPhone or Arduino to create a network.

RF transceiver you need external circuitry.

The common way to do this at the moment is using Bluetooth Low Energy. Using a Bluetooth Low Energy (BLE) shield you can directly connect the Arduino to a modern iPhone or Android phone (supporting Bluetooth 4.0).

Check out redbearlabs, who have a range of shields and BLE-enabled Arduino clones. There are example sketches and iOS apps on the net. I have made a BLE controlled RGB light using the redbearlabs BlendMicro and example OSX application.
> 3 votes

---
Tags: wifi
---


title: IRremote library and Moteino

text:
# Question
Title: IRremote library and Moteino
Does somebody know if the IRremote library is compatible with Moteino boards?

If not, do you know a cheap solution to build a IR-remote controllable via wireless?

# Answer
> 1 votes
You need two spare digital pins to use the IR-library. These pins can be set to whatever you like. Pins D3 to D7 are free on the Moteino so the library will be OK to use if you connect the IR LED and receiver to two of those pins.

# Answer
> 0 votes
Your Arduino do not need to be wireless to be able to control it wirelessly. If you have a wireless network at home (which most people do), there is usally some ethernet RJ45 ports as well. So instead you use a very cheap ENC28J60 to connect your arduino to the network. You can then access your Arduino wirelessly through your home router. As long as it is connected to your local network its should work.

As for connecting the IR sender and reciever, you need as said before, one digital pin for recieving IR-signals and one digital pin for sending. Which should be no problem even when adding the ENC28J60. It should also work very well with the Moteino if you choose to go that way.

---
Tags: wifi, ir
---


# Question
Title: Simple compiler design help: Variable length arrays?
I'm trying to write a simple compiler in C++ for a language that I am making up for my lab. The compiler will have to be able to turn a string like this:

```
"do command_one 3 times"

```

into a data structure that represents this:

```
<command_one>, <command_one>, <command_one>

```

it should also be able to turn something more complicated like this:

```
"do do c_one do c_two 2 times 2 times c_thr 2 times"

```

into a data structure that represents this:

```
<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

```

Another function will then read the commands out one by one.

These examples show all of the functionality that I would want from the compiler.

I'm having design issues for the compiler that I want to create. Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands. However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in C++ need to be initialized with a length, this could be a problem.

I am not fluent in C++ so I am hoping that a C++ whiz can show me a quick solution. I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.

EDIT: I am also intending to use this code for an Arduino, which supports C++ code but not the standard libraries. I found the vector solution to work in my C++ code, but it will not work in the Arduino interface. Is there a way to do the compiling WITHOUT using vectors?

# Answer
> 3 votes
In C++ there is a std library container called vector you can use to create variable length arrays. You can use it like this:

```
#include <vector>
// ...
std::vector<int> commands;
// ...
// parse string and generate commands, add your commands with push_back
commands.push_back(new_command);
// and you can access elements in the array like normal
commands[0];
// and also see how many elements are in the array
commands.size();

```

I also want to mention the std stack, which I think would be a helpful class for managing the states of your nested loops. Each time your interpreter enters a new loop for example, push to the top of the stack how many times to run, and each iteration count down till 0 and pop (just as an example).

Edit: Because you can't use vectors C++ also supplies the new and delete keywords to dynamically allocate and delete memory. However as arduino has really low memory I don't recommend trying to implement an expansible array on this. This post here mentions that program memory and global memory is shared on 2K: new operator on arduino

You may just want to go with a reasonably sized static array on arduino considering the memory limitations. I would suggest using a pool or the new + delete stuff but any implementation you add to deal with memory management will take away space you need for your interpreter and its instructions.

Also I don't know what data type you've chosen to represent your instructions but char is probably best on the embedded implementation if your instruction set is small as it only occupies one byte each.

# Answer
> 0 votes
After Edit:

Since you cant use vectors ...

... or use variable length arrays, if the compiler you are using it, supports it.

... the other viable solution is to get your own list or vector library, either from an existing open source library or implementing your own.

Cheers.

---
Tags: c++
---


title: Using timers on an Arduino Mega 2560

text:
# Question
Title: Using timers on an Arduino Mega 2560
I'm an amateur and I wish to use timers in my project. I'm using an Arduino Mega 2560 with a touch-sensitive screen with six DS18B20 temperature sensors and a DS1307 RTC (real time clock). I would like to query my sensors every 1 or 2 minutes to refresh the screen for temperature acquisition. I do not how to program timers to schedule the readings and which timers to use?

# Answer
You can use the function `millis()`, that returns the number of milliseconds since the Arduino board began running the current program (unsigned long). This number will overflow (go back to zero), after approximately 50 days.

The code below uses the `millis()` function, a command that returns the number of milliseconds since the Arduino board started running its current program, to blink an LED.

```
/* Blink without Delay

 Turns on and off a light emitting diode(LED) connected to a digital
 pin, without using the delay() function.  This means that other code
 can run at the same time without being interrupted by the LED code.

 The circuit:
 * LED attached from pin 13 to ground.
 * Note: on most Arduinos, there is already an LED on the board
 that's attached to pin 13, so no hardware is needed for this example.

 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

// constants won't change. Used here to
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

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

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

```

Source: http://arduino.cc/en/Tutorial/BlinkWithoutDelay
> 2 votes

# Answer
You can use the watchdog timer for that. Below is part of the code that I use to make temperature readings every 8 seconds using the watchdog timer. It compiles on Arduino IDE 1.0.5 for Arduino Uno R3 board, but be warned that I didn't run it as it is below (so it's untested). You can change variables `COUNTER_TRIGGER` and `WATCHDOG_PARAM` to adjust its timing it to your liking. Note also that I'm using ATmega328P, so map it accordingly to your MCU.

```
#include <avr/sleep.h>
#include <avr/power.h>

#define WDTCR_REG WDTCSR
#define SERIAL_DEBUG

int COUNTER_TRIGGER = 1; // 1 * 8 sec = 8 seconds
int WATCHDOG_PARAM = 9; // 9 = 8 sec
// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms, 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec

volatile long watchdog_counter = 0;
int counter_trigger = COUNTER_TRIGGER;

const byte TEMP_PIN = A5;

void setup() {
  #ifdef SERIAL_DEBUG
  Serial.begin(9600);
  #endif

  pinMode(TEMP_PIN, INPUT);

  //Power down various bits of hardware to lower power usage
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // ADCSRA &= ~(1<<ADEN); //Disable ADC
  ACSR = (1<<ACD); //Disable the analog comparator
  DIDR0 = 0x3F; //Disable digital input buffers on all ADC0-ADC5 pins

  sei();
  setup_watchdog(WATCHDOG_PARAM);
}

void loop() {
  #ifdef SERIAL_DEBUG
  Serial.print("Sleeping...");
  Serial.flush();
  delay(20);
  #endif

  sleep_mode();

  #ifdef SERIAL_DEBUG
  Serial.println("awake");
  #endif
  // Zzzz...

  #ifdef SERIAL_DEBUG
  Serial.print("watchdog_counter = ");
  Serial.println(watchdog_counter);
  Serial.print("counter_trigger = ");
  Serial.println(counter_trigger);
  #endif

  if (watchdog_counter >= counter_trigger) {
    watchdog_counter = 0;
    doSomething();
  }
}

void doSomething() {
  // do your thing here
}

// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms, 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR_REG |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR_REG = bb;
  WDTCR_REG |= _BV(WDIE);
}

// executed when watchdog timer expires
ISR(WDT_vect) {
  watchdog_counter++; // increment volatile
}

```

I don't remember where I got it. I'll add proper attribution when I find out who provided the code... soon.

I hope this helps.
> 0 votes

---
Tags: timers
---


# Question
Title: Help connecting an Arduino and an electronic speed controller
We have this controller that we are planning to use with this motor. How do we plug it to the Arduino to make it work?

This is a totally new subject for our school team, since we are mostly programmers, so your help will be really appreciated.

# Answer
> 1 votes
HobbyKing, which sells Arduinos and is a great source for motors and controllers, has an instructable on this at http://www.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/

I found another on the OpenROV site, at http://community.openrov.com/forum/topics/how-do-i-activate-electric-speed-controller-with-arduino

Did you actually try googling "arduino electronic speed control" before coming here?

# Answer
> 0 votes
As the controller and motor are from the same vendor, they can help you with specific questions.

That motor controller is designed to emulate a servo motor. So it takes a servo-motor signal: Ground Power PPM signal

The Arduino servo library will drive the PPM signal. Power and ground for the controller need to come from a separate power supply. The Arduino can't power it.

---
Tags: motor
---


title: Controlling ESC with Arduino

text:
# Question
Title: Controlling ESC with Arduino
I want to control these motors: hexTronik DT750 Brushless Outrunner 750kv with this battery: Turnigy 2200mAh 3S 25C Lipo Pack and these ESCs: TURNIGY Plush 18amp Speed Controller.

I am new to this field of driving brush-less motors. Can someone tell me if I need anything else? Will this set-up work without anything getting destroyed?

# Answer
> 2 votes
I 've been working on an autonomous arduino quadcopter for about 7 months now and I have a few tips for you.

1) your setup seems fine as long as your motors aren't going to draw more amps than your ESC can supply, but It is always a good idea to buy ESCs with a higher "max amps" than your motors draws. I would choose 25 amp max ESCs or higher.

2) In order to control the motors via PWM, I use the Servo library because you get a resolution from 700-2000 as opposed to "analogWrite" which gives a default resolution of 0-255.

3) your ESC probably has a minimum pulse width value before it will start. I would recommend writing a program that gives you the ability to plug in values from 700-2000, and use the program to slowlly find that arming pulse width value. Mine is 1110 for reference.

If you have anymore questions, I will glady answer them.

May I ask, what is your project?

---
Tags: motor, pwm
---


# Question
Title: ATMega328P not running sketch in standalone (works in Uno R3 Board though)
I bought an ATMega328P-PU and burned OptiBoot onto it using a second *Arduino Uno R3* with great success.

I then put the microcontroller back on the (empty) Uno R3 (DIP) Board for programming, connected USB and uploaded the blink sketch successfully.

Now to the weird stuff:

`Blink` works on the Arduino Board itself, but if I pull it out and stick it into my breadboard, the program seems to not start. Here are some facts:

* happens with or without external crystal `16.000` *(Pin 9-10)*
* happens with or without the 22pF capacitors from `crystal` to `GND` *(9-GND, 10-GND)*
* happens with Fuses set to internal OSC or to external clock *(Uno default)*
* happens with or without the `ADC VCC` *(Pin 20)* and `REFERENCE` *(Pin 21)* Pins @ 5V
* happens on 5V and on 3V3
* happens with or without external Pullup on `RESET` Pin (1)
* Most of the output Pins sit at `0.8 V`

# Answer
## I found the solution by accident.

While I used my multimeter to measure the voltages between GND and the Pins (for the last fact), I noticed the program running at weird speeds. I. e. the LED started blinking.

## What did I measure?

Actually I was just measuring one of the `crystal` pins *(Pin 9 or 10)*. The sketch went running for a few seconds and very different speeds and then stopped.

This small change in voltage gave the ATMega the `clock` signal it needs to step through the program.

Maybe I need less capacitance of the two capacitors as mentioned in the comments. I will update the answer with more information later on.

## The perfect solution

As pointed out in the comments, I really chose the wrong capacitors. It worked without, but we want the stability so use a bright light and a magnifying glass if you are unsure. Really, do it.
> 3 votes

---
Tags: arduino-uno, atmega328
---


title: Adding devices makes I2C read 0

text:
# Question
Title: Adding devices makes I2C read 0
I'm using an Arduino Due with a logic level converter to interface with two different 5v sensors via I2C. Being of poor quality, these sensors have no data sheet.

When either one of these sensors is plugged in, I am able to read from it without issue. The moment I plug the other one in as well, the I2C stops working, and I just get 0. I know that it's not an address collision issue, because they have different addresses.

I tried adding an additional set of pull-up resistors (such that they are in parallel with the built-in ones) in order to counteract potentially increased bus capacitance, but no dice.

What could be causing this issue? I apologise for asking such a noob question.

# Answer
Your problem is probably from the level converter. Which one did you use? Most level converters are uni-directional, and don't work for I2C. See the App note and device from NXP: http://www.adafruit.com/datasheets/an97055.pdf
> 1 votes

---
Tags: arduino-due, voltage-level, i2c
---


# Question
Title: Using IMU for a small Arduino and bluetooth support
I'm gonna start a project with an IMU with a bluetooth support inside a small board (mini or lillypad) and send datas to the mobile phone. But I'm quite new to those kind of technologies.

I'm going to choose a module for handling both operate voltage restriction and memory capacity for both library (IMU and bluetooth).

Any advice obj which arduino / IMU breakout / bluetooth module / battery to use? Or some similar projects?

# Answer
If you're new to Arduino I'd suggest avoiding the Mini and the BULLSH-fun that external programmers bring. Something like the Pro Micro is much easier, almost as small, and less likely to bite.

Often the best way to pick hardware is to look for a tutorial (like This one) before deciding what to buy. While I personally haven't used IMUs it looks like the "6 Degrees of Freedom IMU Digital Combo Board - ITG3200/ADXL345" from SparkFun would be (relatively) easy to use.

I've used the RN-41/2 Bluetooth modems (the same as are found in BlueSMiRF modules) and usually gotten on OK with them. There are plenty of tutorials available with a bit of Googleing.

Adafruit do a good line of Lipo batteries and chargers. They also have wireless charging modules if you're looking for extra brag-factor.

Hope this helps.
> 1 votes

---
Tags: bluetooth, accelerometer, gyroscope
---


# Question
Title: Why does an Arduino MEGA 2560 have different PORTS
I'm currently looking at my Arduino MEGA 2560 board and was just wondering why there are different ports to it e.g. ANALOG IN, DIGITAL, Communication? in fact I've only seen this in some microcontrollers. Not many microcontrollers have ports dedicated to certain things. Is anyone able to give me an answer as to why there is different ports to the microcontroller? is it making it easier for the chip to handle etc. A detailed but not too detailed answer would be great!

# Answer
Thats because Arduino has configured the Mega to do so. In microcontrollers you need to select what use will each pin have based on the availability. To make user interface easy arduino has done this based on what is commonly used by everyone. Even then some functions are still not disabled.

For example 50,51,52,53 are SPI pins on mega which use Pin change interrupt for working. Thus it not necessary we use them for SPI we can also use them for Pin change interrupt.

Similar is the case for pins 10,11,12,13. These PWM pins can also be used for Pin change interrupt but other PWM pins cannot.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Cant's code against Yun Wireless Section
Just got my Yun today. Successfully connected to my home wireless, installed YunSysUpgrade\_v1.5.1, and divied up my Micro SD card for Linino and Windows file system with YunDiskSpaceExpander, and got files serving on the native file server from the SD card.

But I can't seem to touch the wireless section from a sketch.

I'm running a mod of the example ScanNetworks sketch - here's the relevant part:

```
void loop() {
  delay(1000);
  String fv = WiFi.firmwareVersion();
  Serial.println("Version: ");
  Serial.println( fv );
  Serial.println("Status: ");
  Serial.println( WiFi.status() );
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

```

Here is the ouptut: no version and a status of 255 (which I cannot find documentation on....)

> Version:
>
> Status:
> 255 Scanning available networks... \** Scan Networks \** number of available networks:0

I looked at installing wifi\_dnld.elf, but could not find jumper 3 on my Yun, so assumed it was for the 'true shield'.

What am I doing wrong, or do I need to return this to amazon?

# Answer
`WiFi` library won't work with the Yun: it's meant to work only with the WiFi shield.

On the Yun, everything but the pins is connected to the linux cpu. For the microcontroller to use all the devices available to linux, including wifi, you need to use the `Bridge` library. Try running example `WifiStatus` (Examples -\> Bridge -\> WifiStatus)

A drop in replacement (almost) of both Ethernet and WiFi libraries is the `YunClient`/`YunServer` pair, part of the `Bridge` library. Check out the docs at http://arduino.cc/en/Reference/YunBridgeLibrary.
> 1 votes

---
Tags: arduino-yun, sketch
---


# Question
Title: Can arduino create a file in its memory?
I am an arduino enthusiast and i am new to it.just wanted to know weather the micro processor itself could create a file in its memory while its is running. I know that it is possible to read a write from a file in c++ but is it possible to do so in an arduino (while it's running).

# Answer
> 2 votes
To answer the original question: Basically, yes, you can write libraries to implement a file system using the memories of an embedded microcontroller.
However, if it's feasible highly depends on the controller architecture and its peripherals.
Some of them (e.g. the one on Arduino Due) allow Flash reprogramming while an application is running from Flash.
Others require to have the application running in a special boot block or even in RAM when accessing the Flash for writing (this should be the case on an Arduino Uno)
And others don't allow Flash accesses from application at all.

Anyway:
The use of this for your purpose is very little, because the interface to the PC would also have to support the file system (for example, you could implement a FTP server and use an Ethernet connection...).
Therefore, the SD card approach is surely a very good suggestion.

---
Tags: memory-usage
---


title: Importance of resistor

text:
# Question
Title: Importance of resistor
I'm new to Arduino and also new to electronics. I'm following the tutorial here. I'm not understanding the importance of the resistor in this schematic diagram. Can someone please help me on this?

# Answer
> 10 votes
That resistor, where positioned, is called a pull-down resistor, and if replaced by a straight wire, that circuit would short out when the switch was closed.

The purpose of this is that when a digital input pin is not connected, it floats, and if the switch were open that pin could see upwards of 2v floating value from external and internal noise. With Digital circuitry, any value in this float range can be invalid and return invalid results.

A pull down resistor will generally have a very high ohmic value \>5kohm, as to allow as little current pass as possible. Here, you are shorting the pin to ground through the resistor so it will not have a LOW value when the switch is open, instead of possibly invalid.

When the switch is closed, you will have 5v passing through switch into the pin, to be read as a HIGH value, also sending 5v across a 10k or so resistor to ground, consuming only .5mA of current.

It you want to see what I mean by a floating value, debug the output of any analog pin with a wire going nowhere, and watch as the value changes. Try touching the wire, now add a pull down to ground, or try pulling it up to 5v and observe the behavior.

Happy Arduinoing!

# Answer
> 4 votes
Without the resistor, closing the switch would connect the positive supply directly to the negative supply. This would cause the voltage across all digital components in the circuit to drop close to 0V, **crashing the whole thing**.

# Answer
> 4 votes
In the above circuit there are several other resistances that are being ignored for simplicity and because most of them are extremely tiny. However, one of the resistances is significant, and that it the internal resistance of the power supply.

Without the resistor shown in the schematic, the internal resistance of the battery becomes the most significant resistance in the circuit and the voltage measure at D2 would remain near zero when the switch is closed and very near zero when the switch is opened.

If the resistor shown were several thousand ohms or greater, the voltage at D2 would measure close to 5 volts when the switch is closed and zero when the switch is open (however D2 will be subject to picking up any nearby static electricity or strong electromagnetic fields when the switch is open).

To prevent D2 from being subject to spurious noise, resistors are often used between signal points and ground to dampen any such undesired noise. To better imagine how this works, imagine a 100 megohm resistor connected to D2 with the other end hanging out into the air. The unconnected end of the large resistor is acting like an antenna picking up any possible noise in the vicinity. Because the resistor shown in the diagram is so much smaller then the imaginary resistor, the noise will seem to be shorted out to ground in comparison.

In a very real sense, this schematic is telling you to add in a known resistor to ground or suffer from the effects of all the resistors not show; some being very very high resistance and some being nearly non-existent.

# Answer
> 2 votes
Check out the internal pull-up resistor (disconnected by default) for Arduino as well. Save yourself wiring up an extra resistor.

```
pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5

```

From SparkFun: Pull-up Resistors

---
Tags: resistor
---


# Question
Title: How do voltage and resistance work for two 5v servos when using an external 12v power supply?
I have a 12v/1.5 amp barrel plug power supply on my Arduino Uno. I have two servos that say they are rated for 4.8v to 6v, but no amps are specified. When my circuit is configured as it is in this image, it appears to work fine. (In my test sketch, I'm constantly and simultaneously rotating them from 0 - 180 degrees and then in reverse.)

But I don't understand why it works. I assumed the 5v pin can only supply 5v of total power to the whole configuration. Is it instead supplying a regulated 5v at as needed between both servos from a total pool of 12v (presumably up to 10v at once)? Do I need voltage regulation? Shouldn't I have to know the amps for the servo(s) and use some sort of resistance?

Thanks for any information and advice you can share on learning about the concepts underlying a situation like this.

Update: I ultimately modified my approach based on the feedback received here by wiring a separate 5v/2a power supply to the breadboard for the two servos, and wiring the rest of the circuit appropriately (using a common ground, etc.).

# Answer
> 4 votes
Because the supplies of both servos are connected in parallel, they both see the same voltage. Hence there is no "pool", both are being supplied the same 5V.

There is a regulator on the Arduino which reduces the 12V input down to 5V. It does so by burning off the other \[7V times however much current is being used\] as heat. Since you are supplying it with 1.5A, the most it can supply is in turn 1.5A.

# Answer
> 4 votes
Addition to Ignacio. Explanation from real life.

Gregir, look at your home devices like TV, micro wave, fridge and so on. They all need 220-230 V AC and you can plug all them to one socket. As Ignacio said voltage doesn't plus. The current does plus, for ex. you have 2 servos connected in parralel, both 5V, no load current 0.1A. So to run them with no load you will have to supply 5V and 0.1+0.1=0.2A.

I tried to explain at very basic level ;)

---
Tags: arduino-uno, power, voltage-level, servo, current
---


title: Detecting grass, pavement, gravel

text:
# Question
Title: Detecting grass, pavement, gravel
I think about building my own robotic mower, therefore I would like to detect if the surface the mower in moving on is grass, pavement, gravel ... etc.

Which sensors would be the best choice in order to achieve this?

The benefits:

* no parimeter wire to bury
* possible lawn edge detection (here most mowers fail to do a good job)

# Answer
> 0 votes
I have found this DIY mower page (where they apparently already implemented a grass sensor). Grass sensor. Other useful info can also be found (mixed in english and german).

They are measuring the capacity of the underground in about 2cm (1inch) height.

On gravel or other hard material this is near 0 (as the sensor is in the air). On grass the value is higher.

Haven't though of this solution, should be the way to go.

# Answer
> 2 votes
You could try to use a force sensitive sensor to detect when grass blades touch it.

# Answer
> 1 votes
You may need to use a combination of sensors. I can't think of any single sensor that can reliably detect the different surfaces.

An IR sensor could detect the difference between grass (cooler) and pavement/gravel (warmer).

An ultrasonic ranging sensor could detect the difference in heights between the grass and pavement/gravel.

A photoelectric sensor could detect the difference in reflectivity between the grass and gravel/pavement.

A visual camera could be used with image processing to detect color differences, although this may be too processing intensive for an Arduino.

A final possibility would be measuring the resistance to movement of the wheels. The robot will travel easier over the hard surface of pavement/gravel.

I would think that a combination of the above sensors would provide the most reliability and accuracy. However, it will still likely be limited to one location without recalibration. The weather will even cause a change in some of the sensors (photoelectric for example on a sunny vs. cloudy day).

# Answer
> 1 votes
A combination of colour sensors as the predominant one and proximity sensors as the secondary one should work fine. Around $10 so definitely worth trying out. Also, the code should be relatively easy.

Here are links as samples. I hope this helps :)

$6 colorvsensor

$4 Proximity sensor

---
Tags: sensors
---


# Question
Title: Is it possible to sample sound with arduino?
I have the arduino duemilanove with atMega328. The frequency is 16Mhz.

I want to sample and record from the audio jack. I searched and i found if i want to record "everything - so to speak", i have to sample at 44100Hz.

That means this is unfeasible with my arduino, since my frequency is only 16MHz?

# Answer
For the AtMega328's ADC the datasheet says

> • Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)

So, sampling two channels at 10bit resolution and 44.1kHz is not possible.
If 8bit resolution is enough, and if there's only one channel to sample, it should be able to do the job.

Edit:

To answer Connor's comment:
Of course, this does only apply when using the internal ADC. Connecting an external ADC (via SPI or whatever) makes it possible to sample data at the desired speed.

But anyway, the next question is: Is 16MHz fast enough to process the sampled data (which are received every (22.6/channels) microseconds? ;-)
> 6 votes

---
Tags: audio, frequency
---


title: Wireless Sensor (IMU) to Arduino

text:
# Question
Title: Wireless Sensor (IMU) to Arduino
I was doing some research about this subject and I only have more questions than answers.

I want a little IMU sensor (I don't know which hardware I should get) that sends data wirelessly to my Arduino.

The sender part (IMU + sender + battery) should be small (tennis ball size is fine) and the receiving part should be an Arduino.

What should I buy? How can I achieve this? I was looking at a lot of ideas: Xbees, bluetooth, radio receivers, Arduino Nano, etc.

My focus is on the Arduino code, I just need that the IMU sends data at least at a ratio of 10ms.

As a plus I would love to have more than one Wireless IMU sensor connected to my Arduino.

# Answer
> 3 votes
You have not really given enough specifications for any choice of radio to make a difference in your scenario. Any list of products would be very long, overly summarized, and not relevant in a month, So I'll try and outline the thought process I would take in finding the fit for a project I was making.

**Radio:** Which type of radio to choose will depend on a lot of specific factors, but its more than likely that multiple options will work perfectly. You seem to know the major methods, Xbee, bluetooth, Wifi, and for very long distances, GSM.

You should consider the problem, define what you need by looking at the amount of data per second you want sent, the necessary range, the power you have available in the battery, any region specific laws, and anything else you can think of needing. Also consider if you really need an arduino as the receiver, or if you have a Bluetooth equipped laptop or wireless router on hand that could take that roll for you. Then look around at sparkfun or wherever and find the cheapest, most popular method that fits the bill.

**IMU:** Many IMU's exist with more or less the exact same features, so I will recommend a similar process. Look at the power consumption, output rate, sensitivity, and communication method you project needs, and find the cheapest and/or best rated item at your preferred electronics retailer that fits the bill. the MPU6000's are popular these days. The altIMUv4 has a magnetometer and barometer included as well. Shop around.

You will most likely want to put an arduino nano/micro/trinket/whatever with the IMU to translate to your communication method. Some radios work with UART serial, but not many IMU's output like this. Those that do cost more because they have a coprocessor on board. Consider if buying a co-processor equipped board will make your sensor processing easier before you discount it for the elevated price. In depth sensor fusion gets pretty hairy, and for some, not having to worry about it could be worth $50.

---
Tags: sensors, communication
---


# Question
Title: problem using std::map. Are there known obstructing macros?
I have a header file, where I try to collect global variable declarations. When trying to typedef a map I get the following error:

```
n file included from Dis0_10.ino:7:
/var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build8295701509021940161.tmp/globals.h:23: error: expected initializer before '<' token

```

relevant code snippets from global.h are:

```
#ifndef GLOBALS
#define GLOBALS
#include <map>

```

...

```
typedef std::map<uint8_t,uint8_t> memmap_t;

```

I have no clue, why this statement should fail. I consider it rather straight forward. So I think there must be some problems of this kind here. Or am I missing another include?

# Answer
> 3 votes
The C++ standard library is not available for arduino.

Some implementations of similar containers or certain functions exist on the web, but for the most part the standard library is impractical on a device with such small amounts of both RAM and program memory.

An implementation of SGI STL for AVR has been documented here: http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/

map is mentioned as being particularly impractical for anything less than an arduino mega(1280). An example of maps working is included on the page so it seems like a good lead if you really must use one, but I've never done this myself so I cant guarantee it still works.

---
Tags: c++
---


# Question
Title: Use Arduino Mega to program Arduino Duemilanove
I hava an Arduino Duemilanove but I think that its FTDI chip is crashed.

I have an Arduino Mega too, so can I use it to program my Duemilanove?

# Answer
Yes, this is not an uncommon activity. This is called using an Arduino as an In-System Programmer (ISP)

This page has the information and Arduino program you need. You'll need to adjust for the Arduino Mega pin differences, but that's fairly easy. http://arduino.cc/en/Tutorial/ArduinoISP

Where the ArduinoISP page references pin 13, on the Mega it's pin 52. Where the ArduinoISP page references pin 12, on the Mega it's pin 50. Where the ArduinoISP page references pin 11, on the Mega it's pin 51. Where the ArduinoISP page references pin 10, on the Mega it's pin 53.

Otherwise you should be able to connect the Mega to the patient in the same way as described, load the ArduinoISP sketch into the Mega, preferably from the GitHub repository linked in the article (https://github.com/rsbohn/arduinoisp).
> 1 votes

---
Tags: arduino-mega, arduino-duemilanove
---


title: Sense Whether Circuit is Closed

text:
# Question
Title: Sense Whether Circuit is Closed
How can you sense a closed circuit? I want to have 4 pins with disconnected wires and when touched with a fifth wire play a specific note on a piezo buzzer until disconnected again.

This project loops through several keys and checks whether they are being touched using the Capactive Sensor library. I want to do something similar, but not with capacitive sensing. Alternatively, it may work to have the buzzer always trying to play a note, but only sounds when one of the 4 circuits is close. I'm just not sure how that would work in the code.

Here is their code that uses capactive sensing:

```
#include <CapacitiveSensor.h>
#include "pitches.h"

#define COMMON_PIN      2    // The common 'send' pin for all keys
#define BUZZER_PIN      A4   // The output pin for the piezo buzzer
#define NUM_OF_SAMPLES  10   // Higher number whens more delay but more consistent readings
#define CAP_THRESHOLD   150  // Capactive reading that triggers a note (adjust to fit your needs)
#define NUM_OF_KEYS     8    // Number of keys that are on the keyboard

// This macro creates a capacitance "key" sensor object for each key on the piano keyboard:
#define CS(Y) CapacitiveSensor(2, Y)

// Each key corresponds to a note, which are defined here. Uncomment the scale that you want to use:
int notes[]={NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5}; // C-Major scale

// Defines the pins that the keys are connected to:
CapacitiveSensor keys[] = {CS(3), CS(4), CS(5), CS(6), CS(7), CS(8), CS(9), CS(10)};

void setup() {
  // Turn off autocalibrate on all channels:
  for(int i=0; i<8; ++i) {
    keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF);
  }
  // Set the buzzer as an output:
  pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
  // Loop through each key:
  for (int i = 0; i < 8; ++i) {
    // If the capacitance reading is greater than the threshold, play a note:
    if(keys[i].capacitiveSensor(NUM_OF_SAMPLES) > CAP_THRESHOLD) {
      tone(BUZZER_PIN, notes[i]); // Plays the note corresponding to the key pressed
    }
  }
}

```

# Answer
> 6 votes
Connect your fifth wire to ground. Set the four inputs to `INPUT_PULLUP`. The four inputs will default `HIGH`, and be pulled `LOW` when connected to the ground wire.

---
Tags: sensors
---


title: USB D+ D- to Arduino Mega RX TX

text:
# Question
Title: USB D+ D- to Arduino Mega RX TX
Is it possible to directly communicate USB D+ D- to Arduino Mega serial port TX RX?

# Answer
No, D+/- are high frequency USB signals. TX/RX is 5V UART protocol, i.e. compeletely different. But you can e.g. use AT90USB128x processor to avoid 16u2 bridge. The prosessor is not so mighty as 2560 but it's cheaper and simplifies design.
> 2 votes

---
Tags: serial, arduino-mega
---


title: Unusual LCD behaviour

text:
# Question
Title: Unusual LCD behaviour
Can someone please tell me what's going on with my LCD screen and how I can fix this issues below?

I have the following:

* Arduino Uno R3 w/ ATMEGA 328P-PU
* 16x2 LCD
* TowerPro MicroServo SG90
* DPDT Slide Switch w/ 120 ohm resistor

**Objective:** Read the sensor value (If switch is on or off), and move a servo accordingly while displaying switch state on LCD.

**Issue:** LCD display seems to receive random data during program run (see image). All starts up well, and as soon as a few seconds have lapsed in the void loop(), the screen becomes garbled. Also, the switch value (while debugging) gets a zero reading while HIGH, acting accordingly as if the switch was off. The servo motor runs as it should, but gets random pulses every now and again where it starts to buzz, but doesn't turn.

**Images:** Three images below.

**Schematic:**

**Coding:**

```
#include <LiquidCrystal.h>
#include <Servo.h>

const int sensorPin = A0;    // select the input pin for the potentiometer
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
int oldPos = 0;
int pos = 0;
int oldStat = 0;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo servo;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.setCursor (0, 0);
  lcd.print("Starting up FSS!");
  delay(700);
  lcd.clear();
  lcd.print("Init SERVO...");
  delay(500);
  servo.attach(9);
  lcd.clear();
  lcd.print("SERVO Success!");
  delay(400);
  lcd.clear();
  lcd.print("Testing SERVO...");
  servo.write(0);
  delay(200);
  servo.write(90);
  delay(200);
  servo.write(45);
  delay(300);
  lcd.clear();
  lcd.print("SERVO Running!");
  lcd.clear();
  lcd.print("Select AUX Source");
  pinMode(ledPin, OUTPUT);
}

void loop() {
  lcd.clear();
  lcd.setCursor (0, 0);
  lcd.print("Select AUX Src");
  lcd.setCursor(0, 1);

  sensorValue = analogRead(sensorPin);
  Serial.print("Sensor: ");
  Serial.println(sensorValue);

  if(sensorValue == 0){
    //if(sensorValue = oldStat){
      oldStat = sensorValue;
      digitalWrite(ledPin, LOW);
      lcd.print("Switch is OFF");
      pos = 45;

      Serial.println("Switch is OFF");
    //}
  } else{
    digitalWrite(ledPin, HIGH);
    lcd.print("Switch is ON");
    pos = 120;
    Serial.println("Switch is ON");
  }

  if (pos != oldPos){
    servo.write(pos);
  }

  oldPos = pos;

  delay (700);
}

```

# Answer
> 4 votes
Insufficient decoupling. Put a 100nF cap on the supply lines at the LCD and a 100uF cap on the supply lines at the servo.

---
Tags: arduino-uno, lcd, servo
---


title: Controll LED Strip with Arduino BLE

text:
# Question
Title: Controll LED Strip with Arduino BLE
I'm working on this project where I have interfaced a LED strip (a two wire LED strip) with this Arduino (its not an Uno). I have setup every thing correctly according to this instructable. I'm able to make a simple blinky pattern and I turn it on/off with an Android app I made to communicate with the Arduino using Bluetooth on my phone. Cool.

What I cannot understand is, since the strip is two wired, how should I address individual LEDs on the strip to make more complex patterns? Can I use bit shifts? Reading an article from Makezine (insufficient reps to post more than 2 links), it says that I should connect the strup directly to the output pin. IMO, this will fry the Arduino or in a less virulent sway, not light up the strip in any way.

# Answer
Addressing individual LEDS on a simple strip with LEDs in series and/or parallel connection is just not possible.
Connecting the strip directly to an output pin is completely nonsense. Forget it.

You need a strip with digital LED controllers populated, as described (for instance) in another link mentioned in your second link: http://www.adafruit.com/products/306

Have a look at this, then I'm sure you will come back with more detailed questions ;-)
> 1 votes

---
Tags: arduino-uno, bluetooth
---


# Question
Title: Connecting a Long Stem Thermometer to an Arduino to automate the recording of temperature in an experiment
Is there a way to connect and read the output of a long stem thermometer like this one to an Arduino?

# Answer
> 0 votes
Interfacing with a temperature sensor such as the DS18B20 (https://www.sparkfun.com/products/11050) would be much simpler than trying to interface with a thermometer with unknown internals.

Theoretically, yes, you can use the thermometer you posted, but it won't be simple. The only way to know what you would have to do to interface with it is to open it up and see what's inside. You would still have to calibrate it though to make any sense of the readings you get from it.

---
Tags: arduino-uno, hardware
---


# Question
Title: Resistance in Switch (negative vs positive logic)
I tried in my Arduino the negative logic to get a digital input from a switch (with 10 KΩ resistance). If I want to use the positive logic what kind of resitance I have to use? For me seems that 10KOhm it to big and probably a smaller resistor should be used. How do we compute the value of the resistor? The schemes of Negative and Positive Logic from Valvano's notes/ebook - University of Texas gives 10 kΩ in both cases. Is it correct?

# Answer
From a pure electronics viewpoint, there is no real difference between both circuits, the difference will be handled by your code running on the MCU, as a close switch will either be `HIGH` or `LOW` depending on the logic you used to wire your switch.

The resistor must be present for 2 reasons:

* to avoid producing a shortcut between `+5V` and `GND` when the switch is closed, without it the shortcut would probably damage your power supply circuitry (if both pins are directly taken from Arduino, that would mean damaging Arduino supply circuits)
* to make the voltage pin attached to the pin the "*winner*" of both voltage pins when the switch is closed, ie that pin will provide the level to Arduino input pin

The value of the resistor should be:

* high enough to limit the current between `+5V` and `GND` when the switch is closed, preventing damage and limiting overall power consumption of your circuit
* not too high to allow providing a voltage level to the input pin

Using 10k means that, applying Ohm's law, when closing the switch, a 0.5mA current would flow from `+5V` to `GND`, which is generally acceptable in terms of consumption and cwill not damage your power supply.

Note that the input pin is "**high impedance**" which means it has no voltage level if not connected to anything, and it does not supply or sink any current (or more accurqtely a negligible current only).

Finally, it is good to know that Arduino MCU offers the `INPUT_PULLUP` mode for digital pins, where an internal resistor pulls up the pin input to 5V. This enables you to directly connect your switch between the pin and `GND`. So you just have to code:

```
pinMode(XXX, INPUT_PULLUP);

```

instead of:

```
pinMode(XXX, INPUT);

```

For information, according to ATmega328P datasheet (the MCU of Arduino UNO), those internal pullup resistors have a value between 20k and 50k.
> 3 votes

---
Tags: arduino-uno, button
---


title: Read Arduino code generated by Simulink

text:
# Question
Title: Read Arduino code generated by Simulink
I am trying to do a Hardware-in-the-loop (HIL) system with Arduino and Simulink but the driver of my motor (Pololu VNH5019) works at 20kHz and simulink PWM block only supports 490Hz.

I would like to read and modify the code before it is sent to the Arduino to modify this and add other libraries.

It would be that possible?

If it is not possible, there is any other visual environment (with blocs, like simulink or Xcos) to generate Arduino Code?

# Answer
> 1 votes
Simulink just supplies code for all the things you could be up to, triggered by a serial command of yours. This is very slow and I think it's obvious, that you would want a fast and slim realization of everything possible, if you attempt to do HIL.

If there is a special part you think is only easy for you with blocks, just ask right away, but it is really easy to do everything you can wish for in a few simple lines. Also this is better for you, because you really know, what's going on.

I could provide some detail code, since I'm doing HIL myself atm, but you would need to specify a bit, what you are up to.

To really answer your question: I don't know of any other visual programming tool for arduino and as stated above, my best knowledge is, that simulink uses pretty messy things. And loads them onto the board right away, right?

# Answer
> 1 votes
Simulink most definitely supports higher PWM frequencies than 490Hz. I know because I have used it to generate PWMs in the 20kHz range on microcontroller boards. I suggest you post more details or screenshots of your work. Have someone help you determine where you are going wrong.

---
Tags: arduino-uno, matlab
---


title: Is my Arduino UNO fried?

text:
# Question
Title: Is my Arduino UNO fried?
The title sums it all up. While testing the new proximity detector I bought off of Amazon, a spark flew from some random area and my Arduino's On LED went off while its Loop LED stayed in a dim state. I am here to ask you guys if this basically counts my Arduino as fried and that I need a new one, or if I should wait and see if it works again, being that I wrote this 5 minutes after the thing happened.

Thanks in advance,

afroraydude

# Answer
It's hard to tell without further testing. Do the following:

1. Remove the Uno from the faulty circuit, making sure you remove all the wiring from the Arduino board.
2. Plug the Uno into the USB port. Does the ON LED light up? Does the built-in LED on D13 blink three times? (this should happen if you had the optiboot bootloader)
3. Remove the USB cable and plug the Uno to a 9V source through the barrel power connector. Do the same test above.
4. Can you upload the Blink sketch? If you can, does it make D13 LED blink once a second?

Report your findings by updating your question.
> 6 votes

---
Tags: arduino-uno
---


# Question
Title: Extract arduino collected data periodically
I'd like to extract data collected by a battery powered arduino for example once a day without stopping it and not using SD card.

It's posible, when I want to extract the collected data, to connect a laptop through the USB and then get data because Arduino is, at regulat time intervals, calling 'Serial.println(...)'?

# Answer
This is a bit crude, but I think you could use an FTDI cable (which is a USB to UART converter) to have a program in your laptop talk to the Arduino using its UART (serial) interface.

To do it, you could plug the USB side of a FTDI serial cable to your laptop. The other end of the cable has a plug with 6 pins, 2 of which are the TX and RX serial signals. You could plug those two signals to pins D0 and D1 (RX & TX) of your Arduino using male-to-male jumpers.

In terms of software, you could code the Arduino sketch to listen on the serial port for a command from your laptop. When the command arrives, it would output the stored data (could be comma separated values with CR+LF as end of line). Your laptop would then listen for the answer and retrieve the data.
> 1 votes

# Answer
Yes, you can do it. Depends how much data to have enough storage space. You also need consider potential memory endurance. E.g. external I2C ferromagnetic memory is good option. Of course it's not on Arduino board, you implement extension.
> 0 votes

---
Tags: debugging
---


# Question
Title: How to send RPM data as analog input from arduino to Xbee
I am new to arduino and Xbee these stuff. Trying to send RPM (obtained and calculated by arduino using puulse function) data from arduino to Xbee as analog input to xbee series1.

It seems XBee analog input read a range of 0 volts to 1.2 volts. However, not quite sure how to implement and write the corret code. Following are Arduino code and schematic circuit. Any idea? I really appreciate your help.

```
int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
   Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
}

void loop()
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

analogWrite(pin_out,(int)rpm);

Serial.print("RPM=\t");

Serial.print(rpm);

Serial.print("\t rps= \t");

Serial.print(rps);

Serial.print("\t dt=\t");

Serial.println(val);

}

```

# Answer
> 2 votes
I would suggest you to send bytes instead of "analog value". When you calculate your value, not sure why you use `float` and then convert it to `int`, but here is how i would do. Communicate to xbee via serial communication, send bytes to xbee(its even easier than "analog value"). Added if statment to print RPM every second.

Here is my code:

```
#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
  Serial.println("I am ready to send some RPM!");

  // set the data rate for the SoftwareSerial port
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

/*Print RPM every second*/
If(millis()-time>1000){
  Serial.print("RPM=\t");
  Serial.print(rpm);
  Serial.print("\t rps= \t");
  Serial.print(rps);
  Serial.print("\t dt=\t");
  Serial.println(val);
  time = millis();
 }
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}

```

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


title: How to reset Arduino from software

text:
# Question
Title: How to reset Arduino from software
As you know, the Arduino IDE resets the Arduino when the Serial Monitor is opened. I want also my program to do it. But I don't know how.

I examined the source code of the Arduino IDE (Serial.java & SerialMonitor.java), but I can't find where it sends the reset command. Where is it?

I use C# to communicate with serial.

# Answer
OK, I have solved this by sending DSR pulse as seen on code below:

```
mySerial.DtrEnable = true;
mySerial.Open();
Thread.Sleep(1000);
mySerial.DtrEnable = false;

```
> 10 votes

---
Tags: serial, reset
---


# Question
Title: error: ‘sleep’ was not declared in this scope
I am trying to use the sleep function in lieu of `delay()`, but when I include `sleep()`, I get `Sweep.cpp:60:10: error: ‘sleep’ was not declared in this scope`

I read some place, about `#include <avr/sleep.h>` but that is a fail.

```
#include <avr/sleep.h>
void setup() {
}

void loop() {
  digitalWrite(13, HIGH);   // set the LED on
  sleep(1);              // wait for a second
  digitalWrite(13, LOW);    // set the LED off
  sleep(1000);              // wait for a second
}

```

I was able to locate `sleep.h`:

```
$ locate sleep.h | grep avr
/usr/lib/avr/include/avr/sleep.h

```

So then I started reading `avr/sleep.h`, and it seems like I'm doing it right, according to the examples. So, why might this be failing?

# Answer
"sleep()" is not a function on arduino. The sleep.h file contains functions for the hardware sleep functionality used to reduce power consumption when processing isn't necessary. "delay()" is the right thing to use.

AVR only has one thread, and so there is no meaning to pausing execution by deferring to another thread. Hardware interrupts will always interrupt the current code no matter what it is doing, they are not equivalent to threads (although they can introduce similar bugs).

If you want to wait and still do other calculations you will need to write code that can wait for a time without blocking. This can be done many ways, one way being to use the arduino library function "millis()" to repeatedly check if it is time to do a certain action, and doing something else for a while if not.

Also, vanilla arduino should be using its own packaged avr lib, for example:

```
arduino/hardware/tools/avr/avr/include/avr/sleep.h

```

instead of the one located in your usr/lib directory.
> 4 votes

---
Tags: programming, library, avr, sleep
---


title: ctc mode on atmega 328

text:
# Question
Title: ctc mode on atmega 328
I'm trying to use CTC mode on Arduino 1 but I have the following problem. I need to generate an interrupt on threshold B and A and I have set the prescaler to 1 since I want to generate interrupt A at 15999 (correspond to 1ms) and interupt B at 15( ie a number small enough from the start of counting). I'have write a println function in ISR(A and B) to proof the calling of the latter but the program does not print all the characters in the println function and furthermore the counter does not reset at treshold A but stop his work. How I can resolve the problem?

Here is the program I wrote:

```
void setup() {
    TCCR1A = 0x00;                // No outputs on compare math, no PWM mode
    TCCR1B = 1 | (1 << WGM12);    // Enable CTC mode up to OCR1A and prescaler /1 -> Start
    //TCCR1B = 0b00001001;
    TCCR1C = 0x00;                // Nothing to set into C register

    OCR1A = 15999;                // Set Threshold A
    OCR1B = 15;                // Set Threshold B
    TCNT1 = 0;                    // Clear Counter

    TIFR1 = (1 << OCIE1A) | (1 << OCIE1B);    // Clear Interrupt flag Match A and B

    TIMSK1 = (1 << OCIE1A) | (1 << OCIE1B);   // Enable Interrapt flag Match A and B

    analogRead(A0);            // Dummy Read to make Arduino setting the AD
    ADCSRA |= (1 << ADIE);     // Enable AD Interrupt on conversion completed
    ADCSRB = 5;                // Select Timer 1 Match B as trigger
    ADCSRA |= 1 << ADATE;      // Enable Auto trigger

    Serial.begin(115200);      // Initialize the USART
    Serial.println("Start");   // Write the welcome message

}

void loop() {
    // Nothing to do
}

ISR(ADC_vect)
{
    Serial.print(TCNT1);
    Serial.print(" - ADC Conversion Completed (");
    Serial.print(ADC);
    Serial.println(")");
}

ISR(TIMER1_COMPA_vect)
{
    TCNT1=0;
    Serial.print(TCNT1);
    Serial.println(" - Interrupt A");
}

ISR(TIMER1_COMPB_vect)
{
    Serial.print(TCNT1);
    Serial.println(" - Interrupt B");
}

```

# Answer
> 4 votes
I don't know about configuring the timers on an AVR off hand, but one thing I will point out:

* Never ever use Serial in an ISR.

Serial is interrupt driven - when there are characters in the outgoing serial buffer an interrupt routine sends them out through the serial port. That can't happen when you're in an interrupt routine yourself, so when the buffer fills up the next Serial.write() (print, etc) blocks until there is room in the buffer for the next character. As the ISR can't run, that space never appears, so the print(), write(), etc never finish and the program locks up.

Instead you should store any incoming values in your ISRs into volatile variables, and set flags to indicate to your main program what has happened in the ISR - then your main loop() reads (and resets) those flags and prints out the statuses you want.

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


# Question
Title: split reading sensors values from stream after it via xbee
I'm trying to make project to monitor my home. I am using some gas sensors and temperature and humidity sensors. I want to do this wirelessly and I think the best thing to do that is XBee.

I use this code for the transmitter Arduino:

```
char dataPacket[64];

int gx = 1;
int gy = 321;
int gz = 456;
int ax = 654;
int ay = 789;
int az = 987;
int mx = 147;
int my = 258;
int mz = 369;

void setup(){

 Serial.begin(9600);

}

void loop(){

   sprintf(dataPacket, "X%d" ,gx);
    //  sprintf(dataPacket, "A%dB%dC%dD%dE%dF%dG%dH%dI%d", gx, gy, gz, ax, ay, az, mx,     my, mz);
Serial.println(dataPacket);

    }

```

gx gy gz .... these are the sensor reading variables

and in the receiving Arduino I use this code

```
void setup(){
    // Start up our serial port, we configured our XBEE devices for 9600 bps.
    Serial.begin(9600);
}

void loop()
{

    if(Serial.available() > 0)
{
     while(Serial.available() > 0)
 {
        char dataPacket[64];

for (int i = 0; i < 64; i++)
{
  dataPacket[i] = Serial.read();
 Serial.print(dataPacket[0]);

}

String show = Serial.readStringUntil('C') ;
delay(500);

}
}
}

```

but i can't split the values from the stream and put them into their variables (gx gy ...)

Does anyone have idea how to split it?

# Answer
> 2 votes
Try a communication protocol with a `,` as a delimiter like:

```
messageId,data1,data2,data3,....,dataN\n

```

And use the `Messenger` library to parse it.

See my answer on comms protocols here:

Communication Protocol Best Practices and Patterns

An how to use the `Messenger` library here:

Send Processing color data into Arduino

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


# Question
Title: Get board.vid and board.pid value in code
I'm working on a custom Arduino core based on the teensy code and want to be able to get the board USB VID/PID from boards.txt, as in .board.vid and .board.pid

From what I can tell, Arduino already does this for the Leonardo and similar since if I change the VID/PID in boards.txt then the sketch will run with those values.

But how do I actually get at them? Right now the code I have has hard coded values, but it would be great to make them dynamic.

# Answer
The preprocessor will sub in the values for the names "USB\_PID" and "USB\_VID"

this line in "platform.txt" grabs them and makes build flags for them:

```
build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'

```

the -D\* option in the build is equivalent to the following lines being in the code

```
#define USB_VID /*value of build.vid*/
#define USB_PID /*value of build.pid*/
#define USB_MANUFACTURER /*value of build.usb_manufacturer*/
#define USB_PRODUCT /*value of build.usb_product*/

```

If you are curious, they are used by the libraries in "USBCore.cpp". Also, they will never be defined for devices they don't apply to.
> 1 votes

---
Tags: usb
---


# Question
Title: Performance of internal vs external resistors
Is there any significant performance trade-off between buttons wired with the internal vs external pull-up/down resistors? I see a lot of tutorials demonstrating the use of external resistors when wiring a simple button, like this and this. But since the Arduino/AVR includes internal pull-up resistors, you can wire a button without any external resistor as demonstrated here.

Is there any good reason to complicate your design with an extra resistor?

# Answer
> 5 votes
If you are using the pin as an input in close proximity to the Arduino there is little reason to use an external pullup.

There are a number of factors to consider.

If the switch is some distance from the chip and/or in a noisy environment it will be more susceptible to interference as the internal pullups are high impedance (20kΩ to 150kΩ depending on model).

If the pin is used as both input & output the pullup can reduce the voltage swing.

In other applications e.g. Raspberry Pi the state of the pin between boot and software initialisation can be significant, but this should not be an issue with Arduino.

# Answer
> 0 votes
I think it depends on the application you're going for. A simple switch probably doesn't need a resistor, since it doesn't require the chip to provide any specific voltage or current.

If you're trying to run an LED or something that requires a specific amount of current or voltage, then you may be better off supplying the power connection & resistor rather than relying on the chip to provide the proper power to the device.

Another situation may be where you're approaching the maximum power output of the chip that you might change to external pull-up/down resistors.

---
Tags: arduino-uno, button, resistor
---


title: Compiling includes with Ino

text:
# Question
Title: Compiling includes with Ino
I'm attempting to compile this simple bounce.ino example with the ino tool, but it's giving me the error:

```
Bounce2.h: No such file or directory

```

I've placed it in the same directory as bounce.ino. Why can't it find the header?

Edit: I'm using Ubuntu.

# Answer
> 0 votes
What OS are you using?

If you're in Linux (and some OS X installations) you should note that bounce.h and Bounce.h are two completely different files - you need to make sure you have the capitalization the same in your #include directive as the actual file on disk is.

---
Tags: build
---


title: 20x4 LCD shows alternating blank lines

text:
# Question
Title: 20x4 LCD shows alternating blank lines
I just acquired a Arduino learning kit, which includes a 20x4 LCD display. I was going to test it, so I grabbed an example "hello world" program from the Arduino docs, connected the display appropriately, and then "Voila! ... Oh, it didn't work.".

The display lights up both its backlight and characters, however not in any desirable pattern. The first and third lines are full white (display is white-on-blue), while lines 2 and 4 are full blue. See picture:

The below schematic is exactly how I've connected the display, which should be correct.

simulate this circuit – Schematic created using CircuitLab

I triple-checked all wiring for any shorts, adjusted the potentiometer to a good value and quadruple-checked the connections, and wasn't able to find any errors.

The dead-simple example program is following:

```
#include <LiquidCrystal.h>

// LiquidCrystal display with:
// rs on pin 12
// rw on pin 11
// enable on pin 10
// d4, d5, d6, d7 on pins 5, 4, 3, 2
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() {
    // Print a message to the LCD.
    lcd.begin(20, 4);
    lcd.print("hello, world!");
}

void loop() {
}

```

# Answer
Just putting the jumper wires in the plated holes, doesn't always give a good connection. Try applying some lateral force, to make sure all of them have proper contact. Wiring looks otherwise fine.

A more permanent solution would be to solder some male headers to the display, so you can properly seat it into the breadboard.
> 1 votes

# Answer
I had similar problem and I found that I had wrong contrast/brightness. Communication was working but just the characters were invisible. I spent much time, changed the LCD and in the last minute before went to rubish I got it.
> 0 votes

---
Tags: arduino-uno, lcd
---


title: Add -D option via boards.txt

text:
# Question
Title: Add -D option via boards.txt
I'm trying to find a way to set a -D compiler option from within the boards.txt file. Basically set a #define for use in code. There are already some special ones like board.vid but is there a generic way to do it?

Somehow the Teensy add-on adds a little magic that allows the IDE to recognize options like: .board.define0=-DHELLOWORLD .board.option0=-DHELLOWORLD

In other words, add the -DHELLOWORD (#define HELLOWORLD) to the command line for GCC.

BUT, I can't get this to work without the Teensy add-on installed.

Is there a way to do this with the stock IDE?

# Answer
> 2 votes
Yes, it is possible in the 1.5.+ IDE. while not possible in the 1.0.+ and earlier.

Hardware-specification refers to both the boards.txt and platform.txt files.

in short the boards.txt file specifies...

```
uno.build.f_cpu=16000000L

```

and the platform.txt uses in the compile commands such as ...

```
 -DF_CPU={build.f_cpu}

```

You can your own. There is already a "build.extra\_flags=" that some of the USB devices use to add their own FLAGs conditionally on the board type.

---
Tags: compile, gcc
---


# Question
Title: How to wire QRB1114 IR sensor to an Arduino Uno
What's the best way to wire a QRB1114 IR sensor to an Arduino Uno? I'm attempting to use it as a white-line-on-black-background line detector. Google shows many different ways wire it to an Arduino, but I'm using this one because of its simplicity.

However, when I tested the circuit using the AnalogInput example code, I'm not getting the expected behavior. It registers a reading of 0 for both white and black backgrounds (I'm using white and black electrical tape as test surfaces), and occasionally registers between 5-10 if there's nothing in front of it at all.

What is the most likely problem? Is this circuit an improper way of wiring the sensor? Is my sensor defective? Is the code not reading it properly?

This is my test code:

```
#define BUTTON_PIN 2
#define LED_PIN 13

const int IR_SENSOR_PIN = A0;
int sensorValue = 0;

void setup() {
    Serial.begin(9600);
    pinMode(LED_PIN, OUTPUT);
}

void loop() {
    sensorValue = analogRead(IR_SENSOR_PIN);
    Serial.println(sensorValue);
    delay(1000);
}

```

# Answer
> 2 votes
It was a dumb programming/wiring problem on my end. As I discovered from this description, the signal pin needs a pullup resistor. Since my circuit doesn't have that, I need to enable the pullup resistor on A0, which I wasn't doing.

After modifying my code to do that, the sensor works as expected.

---
Tags: arduino-uno, sensors, analogread, ir
---


# Question
Title: Common Wire sizes for connecting peripherals to arduino
Please don't judge me for asking this question i have never touch arduino before but We plan to use it in our thesis we are doing a budget plan and it must include wires. can anyone tell me the common wire sizes used? This is to estimate the prices.

# Answer
Depends what you’re doing.

For low power (\< 12v, 500mA) peripherals and digital signals:

If you’re going to use breadboard (and you really should start with breadboard) you’ll need solid core hook up wire. You can find pre-cut, pre-stripped sets with a variety of lengths and colours if you’re looking for neatness and simplicity. (An example can be found at: http://www.maplin.co.uk/p/jump-wire-kit-fs65v) Usually it’s 22AWG wire, so you could get a reel and cut it yourself if you’re going to need a lot or are going to solder it in place.

After you’re done breadboarding and want to make something more permanent you should look at rainbow cable. You can tear it to get anything from 2 to 32 way cables, and it’s almost impossible to get the wrong way around. You can solder it directly to a PCB or crimp connectors onto the ends for more flexibility. (You can find this stuff everywhere, but Sparkfun is always there if you can’t: https://www.sparkfun.com/products/10649)

For higher power (\> 12v, 1A):

Keep it away from the Arduino! Use switching transistors, relays, or MOSFETs and use cabling that meets, or preferably exceeds, the power that you’re going to put through it.

I don’t know where you’re going to buy this, but in the UK I use Mouser, Farnell, and RS for most of my electronics supplies. Never buy cabling off Ebay, a lot of it is counterfeit and won’t meet the claimed spec.

Hope this helps.
> 6 votes

---
Tags: wires
---


title: Auto detecting Baud Rate of Arduino

text:
# Question
Title: Auto detecting Baud Rate of Arduino
I'm trying to detect baud rate of Arduino Mega2560 by using C#. My code is below:

```
SerialPort SP=new SerialPort();
SP.BaudRate = 115200;

```

BaudRate is specified as a constant like this, but I would like to automatically detect it.

For instance, if Arduino code includes Serial.begin(xxxx), program should declare SP.BaudRate = xxxx.

How can I do it?

# Answer
I'm not a C# programmer but this StackOverflow answer might be what you're looking for.
> 1 votes

---
Tags: serial, arduino-mega
---


# Question
Title: Uploading Sketches from Windows Command Line
The resources I've found regarding the Command Line interface seem to be out of date so I was hoping to find someone with experience using it. I'm currently running Arduino 1.5.6-r2 BETA on Windows 8.1 looking to upload code to an Arduino Leonardo.

I'm trying to create a script(Powershell) file that I can just use to upload code without user intervention. The actual upload part using Arduino CLI is just straight not working for me. If my understanding is correct I should have it already due to my version of the Arduino IDE but none of the functionality works so I'm doubting myself.

Source: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc

This is the command I'm attempting to run from Windows Command Prompt:

```
C:\Program Files (x86)\Arduino\arduino.exe --board arduino:avr:leonardo --port COM3 --upload C:\Users\Dev\Documents\Arduino\myProject\myProject.ino

```

Any insight into what I'm missing would be very much appreciated!

**EDIT:** Additionally, if anyone could provide information regarding the build/upload process which could lead me to a solution from within C# that would be even more amazing.

# Answer
Turns out that the Ignoring Bad Library Name error that I had been receiving regardless of if I ran Arduino IDE through command line or standalone was the issue. For whatever reason it was blocking the script with a dialog that then failed the upload regardless of if I manually moved through the popup.

Final setup for those looking for this in the future:

Windows 8.1 x64 with Arduino IDE version 1.5.6-r2(I will revert to 1.0.5 and test with that, and report results) using a Leonardo board. Command is as follows:

Working Directory: C:\Program Files (x86)\Arduino

```
arduino --board arduino:avr:leonardo --port COM14 --upload C:\Users\Dev\Documents\Arduino\sketch_jun06a\sketch_jun06a.ino

```

EDIT: As promised, I attempted this with version 1.0.5-r2 and was unsuccessful. Potentially a 1.5.+ feature.
> 3 votes

# Answer
I recommend you to look into cross-platform tool named PlatformIO. It has support for *Windows OS* and doesn't require *Arduino IDE* or any tools.

From Get Started let's install platform and setup environment for your Arduino Leonardo:

**Install new development platform**

```
> platformio platforms install atmelavr

```

**Initialize new PlatformIO based project**

```
> cd path\to\empty\directory
> platformio init
# Project has been initialized!
# Please put your source code to `src` directory, external libraries to `lib`
# and setup environments in `platformio.ini` file.
# Then process project with `platformio run` command.

```

**Setup environments in the *Project Configuration File* `platformio.ini`**

```
[env:my_leonardo_board]
platform = atmelavr
framework = arduino
board = leonardo

```

**Process the project’s environments**

```
> platformio run --target upload

```

P.S: What is interesting, this tool allows you to manage libraries via CLI and then you can build Arduino-based source code with single line

```
#include <%HEADER_FILE_OF_INSTALLED_LIB>

```
> 1 votes

---
Tags: uploading, arduino-leonardo
---


# Question
Title: 'readPulsioximeter' was not declared in this scope
I am new to Arduino. I am trying to use Pulsioximeter sensor with e-health Platform (http://www.cooking-hacks.com/documentation/tutorials/ehealth-biometric-sensor-platform-arduino-raspberry-pi-medical) on Arduino Uno. *Line number 13 is working fine in the example code given in the library and works just fine.* But when I try to upload my custom code (setup function definition is given below), **I get an error stating 'readPulsioximeter' not defined in this scope**. The error doesn't seem obvious to me. Please guide.

Here is the custom code upto setup() function:

```
#include < eHealth.h >
#include < PinChangeInt.h >
bool configuration = false;
//bool in_it=true;
byte val; // variable to receive data from the serial port
int ledpin = 13; // LED connected to pin 48 (on-board LED)
int A=1;
void setup() {
           pinMode(ledpin, OUTPUT);
           Serial.begin(115200);
           eHealth.initPulsioximeter();
           //Attach the interruptions for using the pulsioximeter.
           PCintPort::attachInterrupt(6, readPulsioximeter, RISING);
           delay(500);
}

```

**EDIT1:**  readPulsioximeter is declared in eHealth.h library which has been included in program. The function has been defined as below in eHealth.cpp file:

```
    //!******************************************************************************
    //!     Name:   readPulsioximeter()                                             *
    //!     Description: It reads a value from pulsioximeter sensor.                *
    //!     Param : void                                                            *
    //!     Returns: void                                                           *
    //!     Example: readPulsioximeter();                                           *
    //!******************************************************************************
    void eHealthClass::readPulsioximeter(void)
    {
        uint8_t digito[] = {0,0,0,0,0,0};
        uint8_t A = 0;
        uint8_t B = 0;
        uint8_t C = 0;
        uint8_t D = 0;
        uint8_t E = 0;
        uint8_t F = 0;
        uint8_t G = 0;
        for (int i = 0; i<6 ; i++) { // read all the led's of the module
            A = !digitalRead(13);
            B = !digitalRead(12);
            C = !digitalRead(11);
            D = !digitalRead(10);
            E = !digitalRead(9);
            F = !digitalRead(8);
            G = !digitalRead(7);
            digito[i] = segToNumber(A, B, C ,D ,E, F,G);
            delayMicroseconds(2800); //2800 microseconds
        }
            SPO2 = 10 * digito[5] + digito[4];
            BPM  = 100 * digito[2] + 10 * digito[1] + digito[0];
    }

```

# Answer
> 1 votes
The problem is that you have no function called "readPulsioximeter" in your code. Either define it, pick a different function, or remove that line of code.

# Answer
> 1 votes
It looks like your missed naming the eHealth object, and that that statement should read:

`PCintPort::attachInterrupt(6, eHealth.readPulsioximeter, RISING);`

as you did with the initPulsioximeter call. (In otherwords, "which pulsioximeter?").

---
Tags: arduino-uno
---