# Question
Title: How to send data from a smartphone to Arduino
My goal is to build an extremely low cost quadcopter, by using the sensors of my smartphone (it will be mounted on the quadcopter). The arduino will only control the speed of each motor, as received from the smartphone. What methods exist to transfer data from a smartphone to arduino?

My first idea was to simply use USB, but it turns out that my smartphone doesn't support the USB host mode. Is it possible to send data over USB without USB host mode? What alternatives do I have? I thought of using the audio port: Can I directly connect an audio channel to analog in?

# Answer
I have been using a bluetooth module - they can be had for just a few dollars (depending on which country you're in). I've got an HC-06 which works great : http://www.dx.com/s/hc-05

It has 4 pins: VCC (connect to +5V on Arduino), GND, RX and TX (connected to RX and TX, digital pins 0 and 1 on the Arduino).

You will probably not be able to use Bluetooth and USB at the same time - both will be sending to the Arduino at the same time, and the communications will get garbled.

I have an app called "Bluetooth Serial Controller", which lets me send commands over bluetooth.

If using this, think carefully about what will happen if your phone goes out of range of your arduino.
> 1 votes

---
Tags: communication, usb
---


# Question
Title: Emergency! INO file disappeared on computer. Still on Arduino!
For some reason, my Arduino program has disappeared from my computer, and it was a really long, complex program. It is currently still on my arduino, and I HAVE to get it back. Please, someone help me. Arduino UNO, Macbook Pro.

Edit: Perhaps I wasn't clear. I need the INO file back FROM MY ARDUINO.

# Answer
> 5 votes
The .ino file is lost, however, your Arduino IDE uses your `%temp%` to store immediate data.

Look in `%temp%`, folders akin to `build116193871148509168.tmp` contain build files. The original ino is not there, but I remember the `cpp` files generated by IDE should be there.

Some info about how to find the `temp` on Mac: https://stackoverflow.com/questions/11607834/where-are-the-hex-files-compiled-by-arduino

# Answer
> 2 votes
Your INO file is not (ever) on your Arduino.

When you "upload your sketch" to the Arduino, it is first compiled. Your Arduino cannot interpret a sketch directly, and there are various processes which convert your sketch into machine code. This process is not practically reversible.

---
Tags: arduino-uno
---


# Question
Title: What is the best way to establish wireless communication between the Lilypad and a Mac?
I want to build a wearable device for a dancer using the Lilypad and I need to first send the programme from my Mac to the Lilypad board and then transfer the data read by sensors back to my Mac.

I want to know what is the best wireless solution to use here. I've seen various options such:

# Answer
> 0 votes
I have been using a hc-06 module very successfully. http://www.dx.com/p/hc-06-wireless-bluetooth-serial-pass-through-module-for-arduino-works-with-official-arduino-board-238364#.VLg153WjlIc

Connect pins to +5v, Gnd, and digital pins 0 and 1 (rx & tx).

Do not try to connect to USB and this at the same time, as communication will get garbled.

---
Tags: bluetooth, electronics, system-design, wireless
---


title: arduino nano V3 updated schematics

text:
# Question
Title: arduino nano V3 updated schematics
Does anybody know where to find an updated scematics of Arduino Nano V3? All the Nano drawings I found (even in the Arduino official site) are based on ATMEGA 168 , no one including ATMEGA 328!!!

Thanks

Mike

# Answer
Go for the manufacturer of this board website i.e. www.gravitech.us. You can get the eagle files and all the data you need. Alternatively, you can download the eagle file of nanov3 directly using this link: http://site.gravitech.us/Arduino/NANO30/ArduinoNano30\_Eagle.zip
> 2 votes

---
Tags: arduino-nano
---


# Question
Title: Simple word translator, return error: invalid array assignment
I know this is not a good question. But I am clueless with this error : invalid array assignment (at function convert). For extra information, I involved a lot of copying/pasting programs I haven't exactly understand from internet in the convert function (the strncpy ones) so.. yeah.

This is the program I've done (the menu/mn button currently not used):

```
#include <LiquidCrystal.h>
#define WORD 11
#define LETTER 15
LiquidCrystal lcd(7,6,5,4,3,2);
int i=0;
char input[] = "a";
char output[15];
const int dw = 8;
const int ri = 9;
const int le = 10;
const int up = 11;
const int ok = 12;
const int mn = 13;
int checker = 0;
int bounceCk = 0;

int bdw=0, bri=0, ble=0, beu=0, beo=0, bem=0;

void setup()
{
  pinMode(dw, INPUT);
  pinMode(ri, INPUT);
  pinMode(le, INPUT);
  pinMode(up, INPUT);
  pinMode(ok, INPUT);
  pinMode(mn, INPUT);
}
void intext()
{
  int lim=16;
  lcd.setCursor(0,1);
  lcd.print(input);
  for(i=0; i<lim ; )
  {
    lcd.setCursor(0,1);
    lcd.print(input);
    if(digitalRead(dw)==HIGH)
    {
      checker=digitalRead(dw);
      delay(100);
      bounceCk=digitalRead(dw);
      if(checker==bounceCk)
      {
        if(input[i]>'z')
          input[i]='a';
        input[i]=input[i]+1;
      }
    }
    if(digitalRead(up)==HIGH)
    {
      checker=digitalRead(up);
      delay(100);
      bounceCk=digitalRead(up);
      if(checker==bounceCk)
      {
        if(input[i]<'a')
          input[i]='z';
        input[i]=input[i]-1;
      }
    }
    if(digitalRead(ri)==HIGH && i<16)
    {
      checker=digitalRead(ri);
      delay(100);
      bounceCk=digitalRead(ri);
      if(checker==bounceCk)
      {
        i=i+1;
      }
    }
    if(digitalRead(le)==HIGH && i>0)
    {
      checker=digitalRead(le);
      delay(100);
      bounceCk=digitalRead(le);
      if(checker==bounceCk)
      {
        i=i-1;
      }
    }
    if(digitalRead(ok)==HIGH)
    {
      checker=digitalRead(ok);
      delay(100);
      bounceCk=digitalRead(ok);
      if(checker==bounceCk)
      {
        lim=i;
      }
    }
  }
}
void convert()
{
   char sumber[WORD][LETTER] = {{0}};  /* declare a progmem unsigned static array of kata x huruf */
   char dasar[WORD][LETTER] = {{0}};  /* declare a progmem unsigned static array of kata x huruf */

  /* copy various strings to statically declared storage SUMBER */
  strncpy (sumber[0],"memakan", strlen("memakan")+1);
  strncpy (sumber[1],"makanan", strlen("makanan")+1);
  strncpy (sumber[2],"menyuci", strlen("menyuci")+1);
  strncpy (sumber[3],"perubahan", strlen("perubahan")+1);
  strncpy (sumber[4],"penulisan", strlen("penulisan")+1);
  strncpy (sumber[5],"tercampurkan", strlen("tercampurkan")+1);
  strncpy (sumber[6],"pengelompokan", strlen("pengelompokan")+1);
  strncpy (sumber[7],"pengembangan", strlen("pengembangan")+1);
  strncpy (sumber[8],"kehebatan", strlen("kehebatan")+1);
  strncpy (sumber[9],"memotret", strlen("memotret")+1);
  strncpy (sumber[10],"melakukan", strlen("melakukan")+1);

  /* copy various strings to statically declared storage DASAR*/
  strncpy (dasar[0],"makan", strlen("makan")+1);
  strncpy (dasar[1],"makan", strlen("makan")+1);
  strncpy (dasar[2],"cuci", strlen("cuci")+1);
  strncpy (dasar[3],"ubah", strlen("ubah")+1);
  strncpy (dasar[4],"tulis", strlen("tulis")+1);
  strncpy (dasar[5],"campur", strlen("campur")+1);
  strncpy (dasar[6],"kelompok", strlen("kelompok")+1);
  strncpy (dasar[7],"kembang", strlen("kembang")+1);
  strncpy (dasar[8],"hebat", strlen("hebat")+1);
  strncpy (dasar[9],"potret", strlen("potret")+1);
  strncpy (dasar[10],"laku", strlen("laku")+1);

    /* mencari input pada sumber */
  int k=0, search=0, sel=9;

  while(search==0)
  {
    sel=strcmp(input, sumber[k]);
    if(sel==0)
    {
      output[]=dasar[k]; //!!!!THE ERROR IS HERE!!! happen to either this or output=dasar[k]
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Base Word:");
      lcd.setCursor(0,1);
      lcd.print(output);
      search=1;
    }
    else
    {
      k=k+1;
      if(k>=11)
      {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Error:NF");
        lcd.setCursor(0,1);
        lcd.print("word n found");
        search=1;
      }
    }
  }
    /*
    //print the values
    while (*sumber[i])
        printf ("  %s\n", sumber[i++]);
    */

}
void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Type your word:");
  intext();
  convert();
  delay(15000);
}

```

I found more errors before, I've fixed those, but can't fix this one. I think this problem is caused by the wrong instruction or wrong format. But can't found solution...yet.

The program is converting words to its basic word in Bahasa, you can compare it to English like this. You type "eaten" and it will return "eat". You type "understood" it will return "understand". When you type "stunk" it will return "stink". Or something like that.

Example in bahasa :

"memakan" (eating) -\> "makan" (eat)

"makanan" (food) -\> "makan" (eat)

"pengembangan" (development) -\> "kembang" (becoming bigger/better)

etc

I hope someone will give me a clear hint or two (I'm not too bright, but I still need to learn how not just copying things around), Thank you very much!

# Answer
> 0 votes
It looks like you're trying to copy the contents of a particular sub-array in `dasar` across to the `output` array. However, this isn't valid in C/C++:

```
output[]=dasar[k];

```

To copy data from one array to another, you either need to copy each element one-by-one (e.g. in a loop), or use a block memory operation like `memcpy`.

Here's how I would do it:

```
memcpy(output, dasar[k], sizeof(output));

```

This should work because arrays are basically just pointers in C/C++. It uses the start of `output` as the destination of the copy, and uses the start of `dasar[k]` as the source. The number of bytes it copies is taken from the total size of the `output` array.

# Answer
> 0 votes
Just replace the line in error with:

```
strcpy(output, dasar[k]);

```

---
Tags: lcd, string
---


# Question
Title: Reading the audio signal from a smartphone
i want to read the audio signal from my smartphone. Can i just cut a headphonewire and connect it to the analog in? (Arduino uno) I sadly dont know much about electronics.

greetings

# Answer
No. It partly depends on the phone, but most put out a low voltage AC signal. This would drive the Arduino inputs negative. You can do this by biassing the input at the mid point (+2.5V) and feeding audio in via a capacitor. There are many projects which use similar to record audio.

PS I would not recommend cutting a headphone cord. The wires are very fine, and almost impossible to solder. If you want to do this make a custom cable.
> 2 votes

---
Tags: audio
---


# Question
Title: Question about viability of building a Bill Counter machine
I have a need for a bill counter at my current job, but besides counting bills we also could use a machine to count admission cards.

The idea is to either buy a bill counter machine (like those that the Banks have), or make one from scratch by buying the parts. Besides the bill counting feature i wanted to make it so that it also counts the certain number of cards, and check if they are either stamped or not.

My question is:

Is this possible?

If so, is it easier to just buy a arduino and use it with other parts (sensors, moving gears etc etc), or to buy a bill counter and just "crack" the OS?

Any insight would be appreciated!

PS: I am a 1st year Computer Science student, but i have 0 experience in programming in Arduino

# Answer
There are many more things to consider than just put some parts together if you try to build a counter from scratch. Automated currency handling has come a long way to today's bill counters or any vending machines. You may perfectly handle the computing part of task with an embedded system like the arduino, but paper handling is an art of itself.

If you think of this task as a challenge to acquire and hone engineering skills, go ahead. It may be one of the best training tasks one can think of. But while you may learn a lot from this conundrum, you will propably end up without an usabale device. :)

You have to consider, there are subtasks in

* mechanics
* electronics
* programming

which may include

* paper handling (separation, traction, alignment)
* pattern recognition
* motor control
* high speed sensors
* signal detection and processing
* error and fault processing and handling
* motor and gear connection
* bearings and mechanical substructure
* user interface

and many more.

To modify an existing device solves a lot of mechanical problems in advance. But it may still be difficult to change the firmware of a bill counter to your needs.

You will have to

* break into the system (may be impossible)
* reverse engineer the firmware
* understand the mechanical constraints
* find a way to adapt the system to your needs.

A third way, which in my eyes is rather intriguing, is to take an existing bill counter, rip out the controller and try to plug in your own controller, e.g. an arduino. This gives you a real chance to reach your goal while still having the opportunity to learn a lot.
> 0 votes

---
Tags: programming
---


# Question
Title: Op Amp Understanding + Holiday Lights Tutorial
I am following Jeremy Blum's tutorial for Holiday Lights: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds

I am just trying to set up the circuit for one of the audio channels. I believe I followed the breadboard schematic. However, when I connect the Arduino the power, but without any audio input, the LED lights up. I would've thought that would not be the case.

Can someone help me correct my understanding here? Thanks.

Image of my breadboard: http://postimg.org/image/ibqfvezqp/

# Answer
Per Jeremy Blum:

> If the input doesn’t have a audio input plugged in, then it’s said to be “floating” and you \>can’t really count on the circuit to do what you would expect. The audio input connection \>introduces a known voltage (0 when no sound is playing) connection between the positive op-\>amp input and GND that we then amplify. Try connecting the input to GND and you should see \>the LED turn off.

Source: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds/comment-page-2/#comment-1373392
> 1 votes

---
Tags: led
---


# Question
Title: updating firmware on arduino wifi shield
I'm trying to upgrade firmware on my wifi shield by following the upgrade instructions for Mac. I was wondering what this means?:

> Connect a jumper on the J3 connector, that put the shield in the programming mode. Then connect the USB cable to the shield USB mini socket

**How can I do this?**

# Answer
> 3 votes
A "jumper" is a little piece of metal (or a 0-ohm resistor) that connects two pads or pins together. So, create an electrical connection across J3 ("DFU programming jumper" in all the pictures). You will then be able to program the shield via USB.

# Answer
> 0 votes
The jumper is only neccesary if your device is not R3 (revision 3) Be carefully if you connect the shield and your computer does not recognice the port. You gonna need a driver in the link below there are all the steps include other links to download software as Flip 3.4.7 who has the executable batchisp which one you can made the changes read the web site:

http://www.dfrobot.com/community/?p=3760

and extra information about that in official site of arduino WiFi Shield Firmware Upgrading

there you gonna have an idea how to do it.

for me was more clear as in this site describe everything and also teach to probe if there is an update having sucess in the process to installing something it could be as a question answered with non the specific thing you need.

http://www.binarytaskforce.com/Weblog/2013/09/21/arduino-wifi-firmware-update/

I am also in the process to update my device if I will have success I will write to how I do it. At the moment reading a bunch of differents forums beacuse arduino team itself appearently had some troubles to provided a guided how to do it sucessfully.

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


# Question
Title: Serial.write and Serial.println return different values? Cannot use correct ones
I have a text file on an SD card, and I am trying to print the lines to the serial monitor.

This Code Works:

```
#include <SPI.h>
#include <SD.h>

File myFile;

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

  Serial.print("Initializing SD card...");

  pinMode(10, OUTPUT);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  myFile = SD.open("c.txt");
  if (myFile) {
    Serial.println("c.txt:");

    while (myFile.available()) {
      Serial.write(myFile.read());  //THIS LINE RIGHT HERE
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening c.txt");
  }
}

void loop()
{
}

```

However, if I replace the line `Serial.write(myFile.read());` with `Serial.println(myFile.read());`, then the code doesn't return the correct lines.

It should return numbers similar to this (albeit 3000 of them):

```
564
564
564
564
564
564
564
464
564
664
564

```

If I use `Serial.println` it returns numbers like this (and it doesn't stop at 3000 lines):

```
13
10
54
54
52
13
10
53
54
52

```

And if I try to do `int(myFile.read())` then the integer becomes the wrong numbers (returned by `println`), not the right ones (returned by `write`).\

How do I get a number returned by `Serial.write(myFile.read());` to be an integer?

# Answer
The text file contains the sequential ascii values that spell out the data, not binary data. `println` in printing the numerical value of each byte. For example, the 10's `println` prints are '\n' characters. `write` is printing the ascii character associated with the binary value (the new line). You need to parse the ascii characters into numbers.

Luckily for you the SD library inherits from the `Stream` class, so it will have the same `parseInt` function most often used to parse ints from the serial monitor.

You probably want to set `myFile.setTimeout(0)` first because the file isn't slowly getting characters from the serial bus, so the timeout would just slow you down.

Then you should be able to parse and print out the ascii integers with something like this:

```
int val = myFile.parseInt();
Serial.println(val);

```
> 5 votes

---
Tags: serial, sd-card, string
---


# Question
Title: data type error on sensor data to ethernet client
I'm having a hard time debugging this piece of code, and i'm hoping someone can point out where i am making the mistake.
My serial output is:

```
connected
GetData()
got data...
next stage...

```

I've tested with a simple network client that loops sending a hello world, and it works fine. Every time this code halts after attempting to send a value to the `client`. I know that `getData()` is causing the issue, but i cannot work out why, or how to best resolve it. (apologies for the code dump, i want to be thorough)

```
#include <LiquidCrystal.h>
#include <dht11.h>
#include <SPI.h>
#include <Ethernet.h>
dht11 DHT11;
#define DHT11PIN 8

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server(192,168,1,100);
IPAddress ip(192,168,1,50);
EthernetClient client;

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

const int trigPin = 6;
const int echoPinOne = 7;
const int echoPinTwo = 8;
const int echoPinThree = 9;
const int echoPinFour = 10;

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
  delay(1000);

  //Network
 if (Ethernet.begin(mac) == 0) {
    Serial.println("DHCP FAIL");
    Ethernet.begin(mac, ip);
  }
  delay(1000);
  Serial.println("connecting...");
  lcd.setCursor(0, 0);
  lcd.print("connecting");
  connect();
}

void connect(){

    if (client.connect(server, 8080)) {
    Serial.println("connected");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("connected");

    client.println("hello server");
    client.println();
    delay(500);
    lcd.clear();
  }
  else {
    Serial.println("connection failed");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Connection Failure");
  }
  delay(500);
}

void loop() {

   //network
  if(!client.available()){
    Serial.println("lost connection!-restart");
    lcd.println("Disconnection");
    client.stop();
    connect();
  }
  else {

    int inp[5];
    getData(inp);
    Serial.println("next stage...");
    char *output = (char *) &inp[0];
    client.println(output);

    client.println("first");

    Serial.println("sent first...");

    //here repeats the same process for the other sensors - omitted for clear reading

  }
   //end network

   delay(500);
}

void getData(){

Serial.println("GetData()");
long durationThree, inchesThree, cmThree = 0;
long durationOne, inchesOne, cmOne = 0;
long durationTwo, inchesTwo, cmTwo = 0;
long durationFour, inchesFour, cmFour = 0;

//SENSOR ONE
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinOne, INPUT);
durationOne = pulseIn(echoPinOne, HIGH);

delay(100);

//SENSOR TWO
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinTwo, INPUT);
durationTwo = pulseIn(echoPinTwo, HIGH);

delay(100);

//SENSOR THREE
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinThree, INPUT);
durationThree = pulseIn(echoPinThree, HIGH);

delay(100);

//SENSOR FOUR
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinFour, INPUT);
durationFour = pulseIn(echoPinFour, HIGH);

//DISTANCE CALCULATION
cmOne = microsecondsToCentimeters(durationOne);
cmTwo = microsecondsToCentimeters(durationTwo);
cmThree = microsecondsToCentimeters(durationThree);
cmFour = microsecondsToCentimeters(durationFour);
//Serial.println("sending...");
//char *out = (char *) &cmOne;
//Serial.println(out);
//client.println(out);
//Serial.println("sent!");      used this to test - same issue

Serial.println("got data...");
inputBuf[0] = cmOne;
inputBuf[1] = cmTwo;
inputBuf[2] = cmThree;
inputBuf[3] = cmFour;

}

long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}

```

# Answer
> 0 votes
The code you posted is performing incompatible casts and by thus is sending garbage to `client.println`.

There is no automatic conversion in C/C++ from an array of integers (`int inp[]`) or longs, to a C style string `char *`. A C Style string should end with null terminator `\0`, and the one in your code doesn't. For example, in this line:

```
char *output = (char *) &inp[0];

```

The `inp[0]` contains the first integer. The expression `&inp[0]` contains the address of that integer in memory.

Thus the cast to `(char *)` will yield a malformed C style string, since it will not end with a null terminator, and more important, will not contain the data you expect it would (this cast is saying - "hey, compiler, note that the *address* of that `int` is actually the address of a C style string").

You can, however, utilize the `String` type constructor that receives int/long, and send the duration in order, something similar to:

```
        void getData()
        {
            ... // rest of the code here
            client.println(String(cmOne));
            client.println(String(cmTwo));
            ... // etc.
        }

```

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


# Question
Title: Can I replace Atmega8 with Atmega328 in my freeduino board?
Can I replace Atmega8 with Atmega328 in my freeduino board? If so, let me know the steps needed.

# Answer
> 2 votes
Shouldn't be a problem. Some later versions already have a ATMega168 instead of the ATMega8. All three are pin-compatible.

In the arduino IDE you should however select a different board (one with a 328, like the UNO). That way the compiler knows the target MCU is the 328, and not the 8.

---
Tags: atmega328
---


# Question
Title: Multiple upload/ Synchronization problem
I am trying to do an experiment with Arduino Uno r3 board plus a 2-channel relay shield. What I need to do is to alternatively turn on and off the relay shields. So, it requires multiple compile and upload of the program to assign values to corresponding pins. What I have seen by now is that uploading the program to Arduino is a kind of painful process and it requires nothing to be connected to pins 0 and 1 to prevent synchronization errors. So, I was wondering how I can do my experiment without having to mount/unmount relay shield each time I want to upload a new program into it.

Thanks in advance

# Answer
> 0 votes
Well, you can write a program that takes numbers out of Serial input.

```
int pin1 = Serial.parseInt();
int pin2 = Serial.parseInt();
// etc., etc.

```

Simple.

---
Tags: uploading
---


title: Why doesn't this motor turn?

text:
# Question
Title: Why doesn't this motor turn?
When I upload the code, the DC motor makes a humming noise, but doesn't turn.

```
//2-Way motor control

int motorPin1 =  5;    // One motor wire connected to digital pin 5
int motorPin2 =  6;    // One motor wire connected to digital pin 6

// The setup() method runs once, when the sketch starts

void setup()   {
  // initialize the digital pins as an output:
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
}

// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
  rotateLeft(150, 500);
  rotateRight(50, 1000);
  rotateRight(150, 1000);
  rotateRight(200, 1000);
  rotateLeft(255, 500);
  rotateRight(10, 1500);
}

void rotateLeft(int speedOfRotate, int length){
  analogWrite(motorPin1, speedOfRotate); //rotates motor
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
  delay(length); //waits
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
}

void rotateRight(int speedOfRotate, int length){
  analogWrite(motorPin2, speedOfRotate); //rotates motor
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
  delay(length); //waits
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
}

void rotateLeftFull(int length){
  digitalWrite(motorPin1, HIGH); //rotates motor
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
  delay(length); //waits
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
}

void rotateRightFull(int length){
  digitalWrite(motorPin2, HIGH); //rotates motor
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
  delay(length); //waits
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
}

```

Why doesn't this work?

***Update:***

I plugged it into a different port (5v) as it is a 5v motor, but now it only turns left, not right. It just hums when it goes right.

# Answer
The IO drivers of most common logic chips or microprocessors such as the ATmega on your Arduino are nowhere near strong enough to drive typical electromagnetic motors.

To drive a motor, you should use a higher current switching device - a standard solution for bidirectional control being an H bridge part such as a TB6612FNG, L293D, L298, etc.

These are commonly sold on "motor shields" which you can plug into your Arduino, if you want to experiment with the concept before building something (and if you do want to build something, reviewing such a working schematic first would be a good idea).

You can in theory put an L293D or its DIP-packaged work-alikes on your breadboard, but you will need some care to get it right, especially if you use one of the other parts which requires external catch diodes.

Finally, you should not be powering most motors from the Arduino's onboard regulator or a USB port, but rather should use an external power supply.

=============

Responding to your edit, by changing connections to place the the motor between one pin and the 5v supply, you have done two things:

1) You have made it so that the voltage difference across the motor can be applied in one direction only, therefore it can only rotate in one direction.

2) You have made it so that only the N-channel MOSFET in an output driver is involved in powering the motor. That change is *almost* a useful idea, as N-channel devices are in fact much more capable than P-channel devices of similar dimension (and practical capacitance, voltage rating, and other tradeoffs) due to the greater mobility of negative charger carriers.

But this is still not really a solution, as it is unlikely that your motor's current rating is within even the current sink rating of the N-channel side of the ATmega output.

If you want a simple, unidirectional motor control, you could pursue this idea using one external N-channel MOSFET (or even a biploar NPN power transistor, which will be less efficient but also less delicate) to connect the unpowered side of the motor to ground.

If you want bidirectional control, you will need either + and - power supplies, or four external switching devices taking the roles of the low current N-FET and P-FET totem poles inside each of the two on-chip IO pin drivers you started with.
> 4 votes

# Answer
This is a huge simplification of @Chris Stratton's post, for beginners.

To put it simply, the power that runs your motor is going through your arduino. Your arduino is not made to carry that sort of power.

What you want is an H-Bridge - see https://itp.nyu.edu/physcomp/labs/motors-and-transistors/dc-motor-control-using-an-h-bridge/ \- the H Bridge is specially made to carry the power needed.

Note that this page is for a 9v motor, not a 5v motor like yours - you will need to find a more appropriate power supply than a 9v battery (or, you need to find a 9v motor). If you try to power it through USB, you will be drawing the power through your computer - you may damage it!
> 2 votes

---
Tags: motor
---


title: What do these pins on the Uno do?

text:
# Question
Title: What do these pins on the Uno do?
I've been wondering for a long time what these pins, labeled `ICSP` and blank, do.

I can't seem to find a diagram that explains them, so I've been wondering:

* What are they for?
* Are they GPIO, or do they do something special?
* How can you use them?

Thanks for the help.

# Answer
> 6 votes
They're for programming, as well as carrying the non-select signals for SPI. The right one is for programming the main MCU, the left for the USB communication MCU. You should almost never need to use them unless you need to write a bootloader to a new chip or change the fuse or lock settings on them.

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


# Question
Title: H-Bridge vs Motor shield for the arduino
Assuming we wish to control a small toy car with an arduino - meaning spinning the right and left wheels forward and backward and being able to break and control the speed, where each wheel has it's own engine (but of course two engines on the same side will run on the same speed and direction).

We saw we have two main options - Buying and wiring up a H-Bridge or buying a motor shield (which is based on one).

Are there any advantages for using a motor shield?

Thanks in advance.

# Answer
If I were a beginner, I'd go with the Motor shield.

I'm even personaly using the one from DfRobot, which as @Gerben said, is just plug and play.

It also allows you to select the input power for the motors, which can be either from the 5V Arduino pin or from an external battery. This is pretty convenient if you need more than 5V to power up your motors. It can also support 2A of current draw, which is more than enough for small arduino toy cards.

Here is the shield: https://www.dfrobot.com/index.php?route=product/product&product\_id=1180&search=2A&description=true
> 6 votes

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


# Question
Title: Driving conveyor belts using Arduino Unos
We are planning to drive conveyor belts with Arduino Unos using stepper motors. We are planning to use easy drivers, so that we control at least 3 motors with one Uno. Currently we are still at an initial stage, we are designing and planning the setup of conveyor belts. But what I wanted to ask was, regarding the coding.

How would I code so that say the belt moves forward for `x` seconds, and then after time it moves backwards for `y` seconds. Any basic idea on the code would be great thank you. I could do the basic code, but I just need help with timers part.

# Answer
> 1 votes
In regards to time control use the mills() function. You start by creating an:

```
unsigned long lastTime = millis();

```

Then later in the program create another variable:

```
unsigned long currentTime = millis();

```

Next Compare the two:

```
unsigned long elapsedTime = currentTime - lastTime;

```

For the most part I normally just shorten the last two lines into one:

```
unsigned long elapsedTime = millis() - lastTime;

```

Stepper motors are not needed if you are just doing timed control, but the advantage of stepper motors are you can move them with pin point accuracy based on the number of steps per rotation. If there are 60 steps per rotation then 360 degrees per rotation/ 60 steps per rotation and you get that each step is 6 degrees. So in order to turn the motor 6 degrees you would turn it 6 steps. This also allows you to keep track of angular velocity.

When I control motors I normally create an array of the different parts of the cycle then loop through the array.

---
Tags: avr
---


# Question
Title: Powering Infrared and Sonar sensors using BEC
I'm new to Arduino. I'm using Arduino Mega 2560 board & MATLAB Simulink-Arduino support package and trying to integrate Maxbotix Sonar and Sharp IR sensor for my class project. When I powered single US sensor from Arduino 5V output, the readings are fine. However, when I tried to power IR sensor in parallel with US sensor, IR readings are fine but US readings fluctuate.

So, I tried powering the sensors using BEC (5V-3A). The readings for both sensors are fluctuating(extremely noisy). From the specification mentioned by manufacturers, Maxbotix US sensor draws 2mA of current, whereas IR sensor averagely draws 20mA. Is there any way to solve this problem?

Thank you.

# Answer
> 1 votes
I've managed to solve the problem. When external power supply is used to power multiple sensors, connect the GND of that supply with that of the Arduino GND input. For more details, refer to the link below.

http://www.thebox.myzen.co.uk/Tutorial/Power\_Supplies.html

---
Tags: arduino-mega, sensors
---


# Question
Title: how to know which pin is being used, change pin?
i am having an issue where i am unsure how my device knows what pins its using. Version #1 is a timeclock which is simply declared with no pin numbers. Version #2 is a simple loop with a device on pin A0;

So how can i set / change the pins for the clock to use. Currently it is on A4 & A5.

If i wanted to move the clock to say pins.. A1 and A2, how would i do that?

Thanks

Version #1-------------------------------------------------

```
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

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

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
 //   RTC.adjust(DateTime(__DATE__, __TIME__));
  }

}

void loop () {

    DateTime now = RTC.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    delay(3000);
}

```

Version #2---------------------------------------------------------

```
int powerswitch1 = A0;
void setup()
{
pinMode(powerswitch1, OUTPUT);
}

void loop ()
{

digitalWrite(powerswitch1, HIGH);
delay(500);
digitalWrite(powerswitch1, LOW);
delay(500);
digitalWrite(powerswitch1, HIGH);
delay(500);
}

```

# Answer
Your confusion is over the multiple functions of analog pins A4 and A5.

In addition to being analog pins, they are also the pins configured internally for I2C/TWI serial, which is interfaced with using the Wire library on arduino. Since those are the only two pins Wire can use, there is no need to specify them, the sketch just calls `Wire.begin()` to set everything up.

If you need a second I2C device you can simply connect them both up to A4 and A5 at the same time, the protocol is designed to support that kind of thing. If you need to use A4 and A5 for something else besides I2C, you can't continue to use the hardware I2C library.

It is possible to use a software implementation of I2C/TWI serial on other pins, but usually soft-serial implementation have some drawbacks compared to the hardware version. There is an implementation on the arduino playground here: http://playground.arduino.cc/Main/SoftwareI2CLibrary

That said, the RTC library you are using seems to internally use the Wire library, so it would take some hacking to switch it to a different I2C implementation.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: Should I try to make my sketches as small as possible, even when I have enough room?
There has been a lot of talk about shrinking sketches recently, but if you don't need the room, should it be done? Will it speed up my program?

Take this code:

```
int led = 13;
int val;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  val = digitalRead(10);
}

```

1,396 bytes on Arduino Uno. Now let's shrink it a bit:

```
int led = 13;
int val;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

```

1,270 bytes. A 10% decrease! It could be shrunk even more. **I have the space... is it more efficient (as far as speed) to make it the most compact I can or leave it "uncompressed?"** I would imagine that it would be a little more work (not much) calling `blink();`, therefore slowing down my code. Is this true? Are there other advantages/disadvantages of making it as small as possible (besides storage/distribution of C++ files)?

# Answer
Generally speaking, smaller is better. However, there is a point where too small actually makes the program run slower.

My suggestion is if you are working on a sketch and it is blatantly obvious that you are repeating code over and over again, I would rip that out and put it into a function, not only does it make the program smaller, it makes it easier to read.

There is also some optimization going on behind the scenes as well during compilation, so even though the C/C++ code looks to be large, chances are the compiler/linker are determining that something are repeats and consolidating them... Or at least the AVR compiler I used previously did, cannot remember if Arduino does this.
> 8 votes

# Answer
You second code may be smaller in size but due to the function call overhead the max execution speed is reduced.
Does this matter in your case? No, because you have huge delays anyway, but if the code was an actual series of repeated calculations that should be executed as fast as possible then it would make a difference.

As a general rule, smaller code is not necessarily faster too.

For code optimization (either size or speed) you can refer to this application note from Atmel AVR4027: Tips and Tricks to Optimize Your C Code for 8-bit AVR Microcontrollers

I could repeat everything it says here but I don't think there is a point, you can read the original article directly.

---

Regarding the compiler optimization level. Arduino IDE uses the avr-gcc compiler with a setting for **Os** optimization.
The avr-gcc available optimization levels are (source1 source2)

* **O0 or no -O option**
At this optimization level GCC does not perform any optimization and compiles the source code in the most straightforward way possible. Each command in the source code is converted directly to the corresponding instructions in the executable file, without rearrangement. This is the best option to use when debugging a program and is the default if no optimization level option is specified.
* **O1 or -O**
This level turns on the most common forms of optimization that do not require any speed-space tradeoffs. With this option the resulting executables should be smaller and faster than with -O0. The more expensive optimizations, such as instruction scheduling, are not used at this level. Compiling with the option -O1 can often take less time than compiling with -O0, due to the reduced amounts of data that need to be processed after simple optimizations.
* **O2**
This option turns on further optimizations, in addition to those used by -O1. These additional optimizations include instruction scheduling. Only optimizations that do not require any speed-space tradeoffs are used, so the executable should not increase in size. The compiler will take longer to compile programs and require more memory than with -O1. This option is generally the best choice for deployment of a program, because it provides maximum optimization without increasing the executable size. It is the default optimization level for releases of GNU packages.
* **O3**
This option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels -O2 and -O1. The -O3 optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.
* **Os**
This option selects optimizations which reduce the size of an executable. The aim of this option is to produce the smallest possible executable, for systems constrained by memory or disk space. In some cases a smaller executable will also run faster, due to better cache usage.
> 12 votes

# Answer
Your refactor should be done simply because it's better code, not because it's smaller. The advantage is that it's easier to modify.

If making the code size smaller results in a loss of clarity (not so in your case), then you should probably view it as a premature optimization.
> 2 votes

# Answer
When considering optimization, think carefully about what resource is most valuable.

You can optimize for code size; this will let you put more code onto your processor. What will the rest of the space be used for? If your code doesn't fit onto your arduino, and your alternative is buying a larger chip, then this is worth the effort.

You can optimize for speed - you can run more code in the same amount of time. If you are sampling data once per second, and sleeping the rest of the time, then this won't help.

You can optimize for power usage - very important if you're on a battery, less important if you are on mains. This might also not just be power consumed by the arduino, but also sensors & motors - can they be turned off for a while?

There are two optimizations that a lot of programmers forget - optimizing for development time, and optimizing for readability.

Any optimization for one thing will tend to de-optimize for at least one (often several) other things. If you don't know which optimization is going to be most useful, then go for readability, then development time (because today's readability = tomorrow's development time x 10!)

Usually, the most expensive thing is the development time (i.e. YOUR time, especially if you are on the clock for a customer). Most other optimization has a threshold - so long as you are over (under?) a specific threshold, further optimization doesn't help. Code size and execution speed (except when shared between competing tasks) are like this - if your code fits on the chip, then it is small enough. If it needs to do something else later, you can optimize it then. If your program can do all it needs to (assuming it is real-time; calculating Pi is a different case), then that's as fast as it needs to be.
> 2 votes

# Answer
When your time has more worth more than the gains to be had, stop optimizing.

Are you writing for someone for pay? Then this should be their call. But in this case, readability and clarity of your code is paramount; someday, someone else will have to modify your code in your absence. If you deliver working, high performance code that someone else can't read and get a handle on, you will not have fulfilled your obligation (unless this was specifically agreed to).
> 0 votes

---
Tags: programming, sketch, sketch-size
---


# Question
Title: where to syphon off voltage from a 25 pin serial?
I have a mircocontroller that's looking to be powered by a 5v source.

I am trying to 'cypher off' some of this power from a 25 pin serial port, which is being powered by a constant power source.

Are there any pins that could give me that sort of voltage, or enough to power the board?

Please note, I'm **not an electrical person** at all, and so hope this is actually possible (otherwise my 3 months + program's work doesn't really add to anything).

I've tried a 9v battery, but it didn't seem to hold its charge?

I'm reading these labels going "what the ..." so you can probably tell coding the board wasn't the easiest, either.

**Edit History**

* *I would like to clarify this is an **existing serial lead***
* *I understand this may be deemed verging off topic,* *but due to the need to 'power' a* *microcontroller, I thought this could be answered here*
* *If this isn't possible, (as an alternative, possibly) would a 9V/battery be able to power this board reliably for around 2-3 weeks?*

# Answer
> 0 votes
You should be able to use pin 7 for negative, 9 as positive, this gives you 12 volts.

YOU MUST NOT HOOK THIS UP DIRECTLY to the arduino, connect it to a plug for the power jack (right of the USB connection).

If you are using a USB -\> serial adapter, then the voltage may be 5v, but don't count on it.

Of course, USB is always going to be better!

PS - if you draw more power than the serial port is rated for, you will probably destroy the card. In most cases, this will be the motherboard. You are unlikely to be able to find out what it is rated for (look for Amps or A, or milliAmps mA, or microAmps uA). The Arduino (with NO inputs or outputs, and idle) running from a 9v battery will draw about 50 milliAmps.

# Answer
> 0 votes
In a lot of further research, I have discovered that 'It doesn't really matter' what the serial port diagram says, since in 25 pin serials (and 9 pin D-subs), it all depends on the circuit at the other end, showing which wires are actually '*connected*', or '*used*'.

---

I managed to get *some* current from +pin 6 -pin 5 in which allowed me to draw *some* current, but have chosen to go with a (PP3?) 9v battery instead due to its reliability.

---

So, in conclusion to this question, there isn't a specific answer, since it all depends on how the serial at the other end is wired.

It seems to me that in my case, there were minimal wires actually connected, so I was forced to look for other means of connecting to a 'reliable' power source.

---
Tags: serial, power
---


# Question
Title: Can't store temperature in variable ( for further processing)
I am trying to store temperature data in a variable, so that I can use it for making a JSON object, but the problem is, that when I try to store the temperature in a variable, it prints out the wrong value. I'm using a DHT11 temperature/humidity sensor and a library for calculating the temperature.

```
Serial.print("Temperature (°C): ");
Serial.println((float)DHT11.temperature, DEC);
int temp1 = ((float)DHT11.temperature, DEC);
Serial.println(temp1);

```

These 4 lines is printing out this:

```
Temperature (Â°C): 23.0000000000
10

```

The first one is correct, but the second line should also be saying "23". I have tried only loading the data in once with the library, as in outcommenting one line, but that does not work. It's like I have some syntax wrong, but I can't figure out what.

# Answer
This line:

> ```
> int temp1 = ((float)DHT11.temperature, DEC);
>
> ```

casts `DHT11.temperature` to an `float`, throws away the value, then assigns `DEC` to `temp1`. That is not what you want.

> ```
> int temp1 = DHT11.temperature;
>
> ```
> 3 votes

---
Tags: arduino-uno, variables, temperature-sensor
---


# Question
Title: Connect Arduino to Galaxy S2 using USB OTG
I want to connect an Android Galaxy S2 phone to my UNO Arduino using USB OTG functionality. I can upgrade/root the android to any version I want. My goal is to be able to communicate between the devices (send/receive data).

I've tried to search for whether that's possible but found conflicting answers whether Galaxy S2 and the Arduino UNO would be able to be connected this way.

Anyone knows whether this is possible? If yes - Do I need to do anything special - such as rooting the device, flashing it to a certain rom or something like that?

Thanks in advance!

# Answer
> 1 votes
If you use a bluetooth serial module - e.g. google hc 06 - you can do it wirelessly. I have a had good results with this - you can hook it up to pins 0 & 1, then use the stock arduino serial code. Probably not a good idea to hook up to both the bluetooth module and the USB (e.g. for programming) at the same time, they may interfere with each other.

# Answer
> 1 votes
**Method 1.** Basically you do not need root permission to communicate over USB. I am making app for Android for my project and using this FTDriver

**Method 2.** If you are not programming in JAVA then you can try third party apps like:

Uno doesn't have FT232 chip so I found it a bit harder. So instead I have FT232 chip and use `SoftwareSerial`.

**Method 3.** To communicate with Arduino you can use Bluetooth with HC-06 module. There are lots of third party apps to connect and send/receive data. Bluetooth Terminal

# Answer
> -1 votes
In my opinion, you have to use this shield to do this: http://arduino.cc/en/Main/ArduinoUSBHostShield

We can't plug in to use Flash Memorys into Android Phones micro USB via OTG Cable. I guess, tablets and maybe phablets can do that because these devices have *USB Host Circuits* inside. On the link, there is USB Host library for examples. This shield can attach onto your Arduino Uno.

*Edit: I have already tried to do this by doing right like you. I couldn't find any solution then I get the shield, but I still can not do to make any control from both Arduino Uno and my Android phone. Anyway, I know this is about our phones not to have USB Host Component*

---
Tags: arduino-uno, android
---


title: RF Remote Clone using NRF905

text:
# Question
Title: RF Remote Clone using NRF905
I have come across the various blogs which talks about cloning RF remote using cheap 434 MHz Tx/Rx and RCSwitch library.

I tried using RF 434 MHz ASK (https://www.sparkfun.com/products/10532) module with arduino, but the range I get it very less , just around 5-6 centimeters. Seems these RF 434 MHz modules are not stable. So I am planning to use now another RF Module which uses NRF905. Link - http://www.ebay.com/itm/2pcs-NRF905-wireless-module-PTR8000-wireless-transmission-433-486-915MHz-/270963407796

My query is can I use NFR905 based RF modules which is also 434 Mhz to clone any existing remote working on 434 MHz. Please help

# Answer
> 1 votes
You can connect an external antenna to pin 8 on that module. Just use a piece of wire that is 17.3cm long. But since the range is that bad to start with, probably means it isn't tuned very well. I'd return it, or try fiddling with the pot at the back. Not sure why Sparkfun has these crap transceivers for sale. Transceivers without a crystal are very inaccurate in their frequency.

If you only need to transmit, I'd suggest this products: https://www.sparkfun.com/products/10534 . Those worked great for me, and are currently switching on the power sockets for my lights when it gets dark enough.

# Answer
> 1 votes
> can I use NFR905 based RF modules which is also 434 Mhz to clone any existing remote working on 434 MHz.

The answer is, inevitably, no, you cannot. Each such remote controlled device might have a different digital modulation scheme. Best if you could focus on one specific product and adjust your design to fit it.

Note that the two products you are referring to are both 433Mhz but **differ by many other parameters**, such as:

* Supply voltage (5v vs 1.9v-3.6v)
* Interface (single digital output vs SPI)
* Capabilities (receiver vs transceiver),
* Presence of a crystal
* Power consumption
* Price

This might affect your final design as well, and should be taken into consideration.

For example, from my experience, if you will shrink your project into a ATtiny85 at some stage, you might not have enough I/O pins to satisfy the NRF905, but enough for the Sparkfun's product (or a similar one).

> but the range I get it very less , just around 5-6 centimeters.

The maximum range I got with the Sparkfun's module using a half-wave antenna (34cm) was ~40 **meters** inside a building and about 80 meters in open air. My testings with quarter-wave length was about ~30 meters inside a building.

---
Tags: arduino-uno, rf, remote-control, nrf24l01+, virtualwire
---


# Question
Title: Arduino cannot communicate with PC after running servo
I was messing around with my arduino uno r3 and servo today. The book I got said to run the servo through the arduino. Everything was fine. I started changing the code, and then things started to get bad. I noticed that if I did not put a delay in between the servo movements, the board would freeze, and I would have to get lucky. Well now I just can't communicate with the board. I plug the board in to my pc, windows 7 makes the connection sound, the board turns on the ON light, the L light flashes, then goes steady. In the arduino software, the COM3 port, which is where I'm plugging it in, is not coming up. Only COM1 is there. I'm not sure what to do. The board is still functioning, the servo moves. I tried to plug it in with a different port and with the servo disconnected but it still doesn't want to communicate with my pc. The code I'm using is below

```
#include <Servo.h>

Servo servo1;

void setup()
{
  servo1.attach(9);
}

void loop()
{
  servo1.write(50);
  delay(500);
  servo1.write(90);
  delay(500);
  servo1.write(140);
  delay(1000);

  for(int i = 50;i<140;i+=10){
    servo1.write(i);
    delay(10);
  }
}

```

I would also like to add that I understand that you shouldn't run the servos through an arduino. I was following the book, and began researching when things went down hill.

# Answer
> 2 votes
I've had some problems in the past reprogramming my Arduino Uno if it writes to the serial port - I don't know if the problem is the same, but here's how I got around it:

Option 1: Hold down the reset switch, then plug your Arduino into the USB port. Select the right COM port (if needed), compile your code (something ultra simple, e.g. blink led), and then, JUST BEFORE IT STARTS UPLOADING, release the reset switch. Wash, rinse, repeat, until you get it to work, through blind luck.

Option 2: Get hold of a ICSP (such as the one I got, USBASP made by FreeTronics http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VL8Vv3WjlIc which I am v. happy with), plug it into the serial port, plug the other end onto your Arduino UNO ICSP header (6 pins, opposite end of the board from USB), then select Tools -\> Burn Bootloader. Overwrites any program, works 100% of the time. Now you can unplug your USBASP, and plug your Uno back in and program it normally. This is also a great tool if you end up using AtMega (or AtTiny) chips directly (AtMega is the chip used to do all the work on the Arduino).

To avoid this, I have gotten into the habit of putting a 5 second delay as the first thing in the startup code.

FOR FUTURE GENERATIONS: I got mine here in New Zealand, so that will probably not help most people. FreeTronics makes them, and I am very happy I got their one (they have a "slow clock" jumper that is very convenient when programming Atmel chips not on an Arduino board), I expect that any USBASP would do the trick too - in response to the question, Amazon has a couple under $4, and I expect that the price will not go up.

Search for "USBASP". Make sure you get a ribbon cable. For Arduino Uno, you need a 6-pin ribbon cable. It is also possible to use these cables to communicated directly with a running Arduino over these same pins.

---
Tags: servo
---


# Question
Title: Arduino Uno synthesizer - Line Level (audio) output to mixer/amplifier
Is using PWM tones from Arduino amplified by a HiFi amplifier safe? Can I damage the amplifier or speakers because the PWM signal is not a "real" audio signal? Taken in consideration that I do not clip the signal and using a RC Low Pass Filter to filter out inaudible frequencies and using a LM386 amplifier chip to amplify and control the volume?

I am developing a synth/sampler project based on the Arduino Uno r3. This is my first electronics project ever and because of that reason I have some questions which I can't find a definite answer for on internet.

The synth has two function. It has a tone generator using the ToneAC library. With code I have mimicked LFO and VCO functions, using potentiometers I can adjust the frequency and LFO speed realtime. The other function is that I can trigger samples stored on a SD card using the TMRpcm library. The lowest frequency which can be played is 100hz and the highest 3100hz.

The device will be used in nightclubs on high end sound-systems and PA. I am afraid I will damage the equipment with my device because I do not send a pure audio (AC?) signal.

Currently the flow is like this:

PWM output (pin 9, 10) -\> voltage divider to 2.5v -\> RC Low Pass Filter 15Khz -\> LM386 amp with volume control -\> mono jack output -\> mixing desk -\> amplifier -\> speakers

*(the TMRpcm and ToneAC library share the same pin (9), I have fixed this by disabling the TMRpcm when the ToneAC is playing and vice versa. The mono jack is wired as follow. pin 9 goes to plus side of mono jack output, pin 10 to negative side. The TMRpcm pin 9 also needs to go to plus side of mono jack output, and mono jack negative needs to go to ground. Because I disable the ToneAC at that time I consider port 10 grounded because it not generating any sound so there is no signal/voltage running out of it, aka the IO pin is set to LOW)*

I am hoping that using the voltage divider I am within range of the Audio Line levels of a default mixers Line-IN (like Pioneer, Behringer, etc). The RC Low Pass Filter is used to filter of inaudible frequencies and clean up the sound a bit, the LM386 audio amp is used to amplify the signal and (hopefully) make it a real audio signal.

Because I lack a lot of knowledge in this field and because I do not own a oscilloscope I can't say for sure if my output signal is harmful for the equipment and was hoping to get some guidance on my project on this forum.

# Answer
In theory, the peak signal accepted from your amplifier should be 0.894V p2p if you want to rescpect the common -10dB signal strength/level. I don't know why you would want to have a 5V to 2.5V "voltage divider" in the first place, but in any case if you use that you already limit the current probably enough, it all depends on the resistor values used.

Using the LM386 amplifier is also simply not required at all, since the Arduino is already providing more than enough power. If you want to tune the volume at that stage, simply combine all functions (volume, low pass and current limit) by connecting the 5V PWM output thru a resistor (eg. 4k7) to a POT (eg. 1k) in parallel with the capacitor (eg.2n2) would give you approximately what you want. Then to remove de DC component, add a series capacitor (eg. 1uF) and you're all set. You may still hear a "click" when you connect it to the amplifier though, so keep the faders low when connecting.

Of course you can adapt the values quite liberally, but these values are both safe and should be close to what is needed (cutoff 15kHz, Vpp 0.88V max).
> 3 votes

---
Tags: arduino-uno, audio
---


# Question
Title: Does the map() function works on an ATtiny85?
I have a working project on Arduino Uno.Now I want to shrink my project using an ATtiny85. Before purchasing an waiting for the shipment to arrive, I want to make sure that my whole code will run on ATtiny85.

specialy, will the map() function which is working on an Arduino Uno ( ATMEGA328P-PU ), work with a ATtiny85 Microcontroller?

# Answer
The `map` function uses integer arithmetic, and since the ATmega series and the ATtiny series use the same 8-bit AVR instruction set, there should be no difference when using it, and you are good to go from that aspect.

Consider that there are many other differences regarding I/O pins, storage etc. - that you might want to consider. Here is a good source for a basic comparison between the ATmega based Arduino to ATtiny85.
> 3 votes

---
Tags: attiny, map
---


# Question
Title: Arduino PWM Frequency - Pros and Cons of Modifying
I am interested in using an Arduino Uno to produce an analog signal by running PWM through an RC low-pass filter.

I'll be controlling a highly dynamic object and need a clean voltage signal to avoid instabilities. Per this calculator on RC designs, it's suggested that one strategy to reducing voltage ripple is to increase the PWM frequency.

With PWM configured to a default of 980Hz for pins 5 and 6, and PWM of 490Hz for the remaining pins, I've decided that this will create too much voltage ripple for my filter. I've found resources that describe how to configure the registers to increase the PWM frequency rather drastically.

My question is very simple: Are there any disadvantages to using a higher frequency PWM? Why is the default set to be so slow?

Thank you!

# Answer
> 3 votes
A PWM frequency of 490Hz means a period of approximately 2.041ms. This allows a high period of 2ms, which is the maximum pulse length required by a large number of inexpensive servos. Obviously if your design uses no servos then this is not a consideration.

Timer 0 itself is used for the various Arduino timing functions (`delay()`, `millis()`, etc.), so if you change the frequency used for timer 0 then those functions will no longer have accurate results.

---
Tags: arduino-uno, pwm, analogwrite
---


title: Are Arduino's truly OSH?

text:
# Question
Title: Are Arduino's truly OSH?
I keep reading how Arduinos are "open source", but my understanding of OSH is that all its components must be open source.

Arduino uses an Atmel 8-bit CPU - but Googling this shows the Atmel is proprietary!?

So I ask: how can Arduino be OSH if it's chief component - its Atmel CPU - is proprietary?!?

# Answer
I just scanned over the TAPR and CERN open hardware licenses and I didn't see such a provision. My quick take on OHLs is that they are specifications for building the hardware - and therefore, information - not the hardware itself. And it only makes sense when we consider the incredibly expensive and complicated (from an experimenter's point of view) infrastructure that is a chip foundry necessary to create the kinds of hardware we take for granted and have reduced to commodity parts, CPUs, & MCUs being a prime example.

Thus "Arduino" is an open source specification for building microcontroller boards or board-sets based on ATMEL MCU chips, as well as the products of the Italian company SmartProjects. That is why there are so-called Arduino clones, otherwise, why wouldn't any clone of an Arduino *be* an Arduino?
> 2 votes

---
Tags: hardware
---


title: EFCom GPRS/GSM Shield

text:
# Question
Title: EFCom GPRS/GSM Shield
I have an EFCom GPRS/GSM Shield http://www.elecfreaks.com/wiki/index.php?title=EFCom\_GPRS/GSM\_Shield and I am using it with a mega 2560. The problem is that the code in the wiki page

```
//Serial Relay - Arduino will patch a
//serial link between the computer and the GPRS Shield
//at 19200 bps 8-N-1
//Computer is connected to Hardware UART
//GPRS Shield is connected to the Software UART

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3);
void setup() {
  mySerial.begin(19200);               // the GPRS baud rate
  Serial.begin(19200);                 // the GPRS baud rate
}

void loop() {
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

```

makes use of software serial but mega 2560 cannot use software serial on pin 2, as in the arduino reference, thus I changed the pins to 50 and 51 and used external female-male headers to connect s\_tx to pin 50 "rx" , and s\_rx to pin 51 "tx", still no response with the AT command...

code after update is :

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(50, 51);
void setup() {
  mySerial.begin(19200);               // the GPRS baud rate
  Serial.begin(19200);                 // the GPRS baud rate
}

void loop() {
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

```

Note that I am using the Arduino IDE serial monitor.

# Answer
Try to connect "Pin RX on Mega to Pin RX on Shield" an "Pin TX on Mega to Pin TX on Shield":

* Pin 50 (Rx) on Mega \<==\> Pin 2 GSM Rx on Shield
* Pin 51 (Tx) on Mega \<==\> Pin 3 GSM Tx on Shield

I use an Geeetech Shield with a Mega 2560 and connect RX to Rx and TX to TX. Works fine.

Another solution is to use Serial1 instead of using SoftwareSerial ...

First connect:

* Pin 19 (Rx1) on Mega \<==\> Pin 2 GSM Rx on Shield
* Pin 18 (Tx1) on Mega \<==\> Pin 3 GSM Tx on Shield

```
    //Serial Relay
    unsigned char buffer[64];  // buffer array for data receive over serial port
    int count=0;               // counter for buffer array

void setup()
{
  Serial1.begin(19200);
  Serial.begin(19200);
}

void loop()
{
  if (Serial1.available())
  {
    while(Serial1.available())
    {
      buffer[count++]=Serial1.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);
    clearBufferArray();
    count = 0;
  }
  if (Serial.available())
    Serial1.write(Serial.read());
}

void clearBufferArray()
{
  for (int i=0; i<count;i++)
  {
    buffer[i]=NULL;
  }
}

```

You can use a Arduino IDE's Serial Monitor, Serial Terminals(sscom32) or Bray++ Terminal to send AT commands to the Shield, communicate with it.

I hope this information is helpful.
> 1 votes

---
Tags: arduino-mega, shields, gsm
---


# Question
Title: Can Arduino's open design be "scaled" to 64-bit CPUs?
If Arduino is OSH that simply uses 8-bit Atmel AVR MCU as a design component, then can Arduino somehow be tweaked to work with a 64-bit CPU/MCU? If so, what might this entail?

# Answer
It has already been ported to a 32-bit Arm - the Arduino Due - 84mhz, Cortex M3.

To port it to a 64-bit CPU, someone would need to create a design for the PCB, and set up an appropriate build/compile system for it.

Having said that, a 32-bit CPU is an awful lot of power for this sort of thing - I suspect that if a 32-bit Arm isn't enough, then what you're really looking for is a full-blown PC. A Cortex M3 can handle 4GB of memory, and can run a version of Linux (uCLinux, since the M3 does not have a memory management unit, MMU, and the standard Linux kernel needs this). The Due would be unable to run even uCLinux, due to limited memory.

In fact, the Raspberry Pi is also a (700mhz Cortex A8) 32-bit CPU; I imagine that a little bit of tweaking could make the Arduino IDE compile & upload for the Raspberry Pi. This would fall into the category of "Because I can".

Note: The Raspberry Pi is not opensource, I know. Neither is the Arm in the Arduino Due, nor the AtMega that is at the heart of the Arduino Uno.
> 1 votes

---
Tags: atmega328, hardware, avr
---


# Question
Title: SIM900 GRPS Shield Power down over issue AT+CIICR cmd(Bring Wireless Coms)
I'm trying to get the TinySine SIM900 GPRS Shield working to get data over the GPRS network, using Arduino MEGA.

I'm Able to register my SIM with this Shield and even , but as soon as I sent the command AT+CIICR to Bring up the Wireless Coms, the Shiled powers down, all LEDs are OFF except the Red one.

What is the source of the Problem?

Thanks

# Answer
The SIM9000 shield requires up to 2 Amperes to operate its wireless functions. Thus it must be powered from an external 9 Volt power supply, and the supply should be able to supply at least 2 Amperes, preferably more.

The shield will thus not work if powered through the Arduino, or using a low current external supply. The current draw for initial setup is low, hence registration of the SIM might be fine. Enabling wireless pushes the current draw beyond what your supply can cope with. This is shutting your setup down.

Replace (or use) a 2 Amperes or better 9 Volt DC power supply, feed this power to the shield, not the Arduino, and attempt your code again.

Note that there are some changes required in using an Arduino Mega instead of the Uno with the TinySine GPRS shield, which are described in the help files and on some example videos on YouTube.
> 1 votes

---
Tags: arduino-mega, gsm
---


# Question
Title: Where Can I Find a 12v Solder-less Breadboard Power Supply?
I am trying to find a 12 V input and 12 V output breadboard power supply but I can't find one. I am making an Arduino-controlled lock but the Arduino cannot power the lock strike by itself so I need to use a separate power supply. The link to make things clearer: http://www.instructables.com/id/Arduino-RFID-Door-Lock/#step0

# Answer
There is nothing special about a "breadboard power adapter" that isn't served by a normal regulated supply. Simply use wires or a barrel jack or some other connector to connect any regulated supply to the breadboard as desired.
> 3 votes

# Answer
They sell 5V/3.3V breadboard supplies on eBay for $3-$5 shipped from China. Buy one and rewire/modify it to bypass the voltage regulator
> 0 votes

---
Tags: power
---


# Question
Title: How to use ROHM LB202VL display (on BP-006LH-GC board) with Arduino?
I got this 8-unit, 7-segment, 2-digit display board with 24 pins and I am wondering how I can interface with this from my Arduino Uno.

The board is labeled ROHM BP-006LH-GC and it has 8 units of the LB202VL LED display. Please see these photos of the board:

I found the datasheet for the LB202VL unit and I have been trying to make an independent unit on the board to work but I haven't been successful in setting its display.

The datasheet for the LB202VL unit can be found here: http://pdf.datasheetarchive.com/datasheetsmain/Datasheets-27/DSA-525461.pdf

Can anybody help me explain how I can work with this and set the display from my Arduino? After having attempted a few times I feel a little lost with this so any help would be greatly appreciated!

# Answer
> 1 votes
I have a similar display, and I found the wiring by inspection and trial and error:

The display consist of 8 pairs of digits (LB-202VL, common cathode).

If contact points are numbered from 1 to 24 from left to right then the common cathodes for the digits D1-D16 and the segments D.P. and 'a' - 'g' are noted below. If you i.e. connect 1 to GND and 7 to + then segment 'c' of the first digit will be on. You have to multiplex the digits in order to use it.

1. D1
2. D2
3. D3
4. D4
5. D.P.
6. D5
7. c
8. D6
9. e
10. D7
11. a
12. D8
13. g
14. D9
15. d
16. D10
17. f
18. D11
19. b
20. D12
21. D13
22. D14
23. D15
24. D16

---
Tags: arduino-uno, led, display
---


# Question
Title: Increasing payload size above 32 bytes using nRF24L01+
I tried to modify the example in the following page, by replacing the given string with a 56 bytes one after making all the suitable changes to read(), write() and max\_payload\_size(increased to 64 bytes), payload\_size() parameters/methods in the RF24 library.

http://shanes.net/another-nrf24l01-sketch-string-sendreceive/

The problem is the receiver truncates the string to 32 characters. Is 32 bytes a hard limitation for payload with the nrf24l01+ radio? If so how to I modify the receiver in above example problem to receive the entire string?

# Answer
> 7 votes
If you look at the specification or datasheet for the nRF24l01+, you will see that the 32 byte payload is the maximum that the device can handle.

For example:

If you need to transmit anything larger than 32 bytes, you will need to develop a protocol that splits up your data into chunks of 32 bytes or less and sends the data in several packets.

The actual protocol you design is up to you, but a simple technique might be using the first packet to send a count of the number of data packets to expect and then simply send those packets, each with a part of your data and reassemble it at the receiving end.

You may need to design something more robust so you don't get confused by lost packets or bad data. The larger your payload, the more chance of transmission errors, so it might be an idea to experiemnt with the payload size to get the best throughput for your particular application.

---
Tags: arduino-uno, nrf24l01+
---


title: Connecting multiple DHT 11 sensors

text:
# Question
Title: Connecting multiple DHT 11 sensors
I want to collect data (both Humidity & Temperature) from 80 sensors. let's say I have 80 "DHT 11 Humidity & Temperature" sensors (for ex. in a warehouse) and one Arduino Uno R3 pack. It's clear that arduino has no so many pins to connect. I'm sorry that I don't know if it's possible. If so, what can I use to achieve this? Thank you all for your suggestions.

# Answer
Analog multiplexers are one way, but they tend to have a significant resistance when on, and this could cause the protocol not to work.
For 80 channels you need 7 bits addressing. Say you have an 8-input multiplexer, then a 3-bit address indicates which of the 8 inputs is selected. Use 10 of these, all with the three address lines connected, and you have 10 outputs from 80 inputs. Next, use a 16-input multiplexer to select which of the 10 inputs you want to use. For this multiplexer you need 4 address lines. Together with the other 3 address lines you have 7 address lines, enough to select 1 of up to 128 sensors. But I repeat, this approach may not work if the multiplexer's resistance is too high.

A more robust (albeit more expensive) is to use analog switches to connect/disconnect each sensor. Analog switches (Analog Devices has a lot of them) have on-resistances down to \< 1 ohm, so the sure should be OK for the application.
To control the long series of switches you could use a daisy chain of 74HC595 shift registers, which only requires a couple of I/Os on your controller, but gives you virtually unlimited outputs.
> 0 votes

---
Tags: sensors, temperature-sensor
---


# Question
Title: Does Leonardo need a separate power supply?
I'm currently using an Arduino Uno (R3), but want to switch to Leonardo for the USB-ability. The Uno can work from the USB's 5V. Looking at the Leonardo's schematic it seems the only input to the voltage regulator is from the power connector. This makes sense as it's a 5V regulator which needs \> 5V in. But I don't see the MOSFET which connects the USB's 5V to the board's 5V, like there's one on the UNO.

So, does the Leonardo need the separate power input connected?

# Answer
Power steering is performed by the assembly labelled "+5V AUTO SELECTOR" at the bottom of the page. The voltage at VIN is halved and then compared with the board's 3.3V output in order to determine whether or not to enable USB power via T1.
> 4 votes

---
Tags: power, arduino-leonardo
---


# Question
Title: Arduino Uno R3 not recognized by computer, TX and RX not blinking, neither are lit. Is it dead?
I was trying to make my arduino uno r3 to work on my Linux machine (including the IDE), but it wouldn't. At first I thought it was a software problem. Added myself to different groups and did everything, people discussed on the forums. It didn't work. It wasn't recognized by the computer at all. I reinstalled. Nothing again. Thought it was a hardware problem of my computer. Tried with dad's (Windows 7 machine). Didn't work. Then I saw that the two leds (TX and RX) are not blinking, neither are lit. I started doing a research on the internet but everybody suggests doing the loopback test from the IDE. My Arduino Uno R3 is not recognized by the computer, therefore the IDE. Is there any way to check if it's dead or if it's a minor problem?

Edit: I read a lot on the case last night and I reach to the conclusion that my ATmega16u2 (the usb-serial chip, I'm sure it is 16u2 and not 8u2, it's written on the chip itself) might be dead. Tried to reflash the firmware but cannot get it in DFU mode (as it says in this article click here). dfu-programmer (the Linux application) throws the following error: `dfu-programmer: no device present`. What to do?

# Answer
There is a chance that your bootloader is not working anymore. You can burn a new bootloader to the device with another Uno, there are nice guides on the Arduino-Website.
> 1 votes

# Answer
Before you can access serial TX/RX on Arduino make sure USB to serial converter on the board is working. To check it (on Linux) do the following:

1. Open the terminal, type 'dmesg' and press 'enter'. You will see some output with timestamps (number in square brackets). Note the timestamp of the last line. Run dmesg several times to make sure nothing writes to it and you still see the last timestamp.
2. Plug your board into USB port and run dmesg once again. You should see something like the output below. The first line is the last line of dmesg prior to plugging in the Arduino, the second line is actual detection. The board I used in this example is 2560, UNO will give you similar output. If you can see this output your board is recognized just fine. If you can't see it then either the USB to serial chip (just another AVR MCU) on the Arduino or USB host in your PC or both are defective.

```
    [279152.351690] systemd-logind[867]: New session c51 of user lightdm.
    [280362.732094] usb 3-2: new full-speed USB device number 3 using uhci_hcd
    [280362.931266] usb 3-2: New USB device found, idVendor=2341, idProduct=0010
    [280362.931275] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [280362.931282] usb 3-2: Product: Arduino Mega 2560
    [280362.931288] usb 3-2: Manufacturer: Arduino (www.arduino.cc)
    [280362.931293] usb 3-2: SerialNumber: 64938323331351213172
    [280362.986579] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
    [280362.988470] usbcore: registered new interface driver cdc_acm
    [280362.988473] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
    [280362.732094] usb 3-2: new full-speed USB device number 3 using uhci_hcd
    [280362.931266] usb 3-2: New USB device found, idVendor=2341, idProduct=0010
    [280362.931275] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [280362.931282] usb 3-2: Product: Arduino Mega 2560
    [280362.931288] usb 3-2: Manufacturer: Arduino (www.arduino.cc)
    [280362.931293] usb 3-2: SerialNumber: 64938323331351213172
    [280362.986579] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
    [280362.988470] usbcore: registered new interface driver cdc_acm
    [280362.988473] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

```
> 0 votes

# Answer
1. Delete your Arduino IDE, but store your libraries if you need in future.
2. Download Arduino ERW 1.0.5 from here: http://forum.arduino.cc/index.php?topic=118440
3. Try your steps again with your connections belong to your schematic.
> 0 votes

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


# Question
Title: Simultaneous input output in arduino mega
I need to read 5 analog pins simultaneously , is it possible?

note that:
analogRead(1);
analogRead(2);
analogRead(3);
will not work this case

# Answer
No, it is not. The ADC in the MCU is only capable of sampling a single analog channel at a time.

If you require sampling more than one channel at a time then you will need to use one or more external ADCs that are capable of sampling multiple channels, or multiple ADCs each dedicated to a single channel.
> 3 votes

---
Tags: pins
---


# Question
Title: Increasing analogread speed on the Arduino Uno
I want to transfer data from my smartphon to the Arduino by using the audio jack of my smartphone. For this I need verry high reading frequencys.

I have used

```
bitClear(ADCSRA,ADPS0);
bitSet(ADCSRA,ADPS1);
bitClear(ADCSRA,ADPS2);

```

to boost analogread to ~10microseconds, which would be enough. But somehow I am still wasting 5.4 ms at the beginning of the transmission.

The only thing between signal start and first analogread is a start of a for loop:

```
while(analogRead(A0)<50) (true); //wait for start of transmission
for(i = 0; i<500;i++){
data[i]=analogRead(A0);
}

```

But does starting a for loop take 5.4 ms? Do you have any ideas?

# Answer
It sounds like you could benefit from interrupt handled free running sampling, doing that should get you sampling rates up to the maximum listed on the 328's datasheet, 76.9 kSPs. Although, that's at a reduced resolution. This site explains better, under the section "Free running sampling".
> 2 votes

# Answer
I did some further analysis on the signal and the problem was not the Arduino. It did everything quick and correct. The problem was my smartphone. I used androids AudioTrack class and somehow it did cut off parts of the signal. This could be "fixed" by increasing the length of the signal. I just added 0's at the beginning and end.
> 1 votes

---
Tags: analogread
---


title: Interfacing Hex keypad with arduino

text:
# Question
Title: Interfacing Hex keypad with arduino
I was trying to interface my hex keypad with Arduino. I declared rows as input and columns as output. When I initialize three of the four columns as HIGH and one as LOW, and detect the button pressed as LOW in the corresponding row, it works fine. That is, it detects the button when its corresponding row and column is LOW. But, when I reverse the condition, i.e. when I try to detect the button pressed when its corresponding row and column is high while others are low, it does not work as expected.

I really want to know why is this happening?

The code that works:-

```
int row[]={6,7,8,9};
int col[]={10,11,12,13};
int i,j;
int col_scan;
void setup()
{
   Serial.begin(9600);
   for(i=0;i<=3;i++)
   {
      pinMode(row[i],OUTPUT);
      pinMode(col[i],INPUT);
      digitalWrite(col[i],HIGH);
   } }
void loop()
{
   for(i=0; i<=3; i++)
   {
      digitalWrite(row[0],HIGH);
      digitalWrite(row[1],HIGH);
      digitalWrite(row[2],HIGH);
      digitalWrite(row[3],HIGH);
      digitalWrite(row[i],LOW);
      for(j=0; j<=3; j++)
      {
     col_scan=digitalRead(col[j]);
     if(col_scan==LOW)
     {
        keypress(i,j);
        delay(300);
     }}
   }}
void keypress(int i, int j)
{
   if(i==0&&j==0)
      Serial.println("1");
   if(i==0&&j==1)
      Serial.println("2");
   if(i==0&&j==2)
      Serial.println("3");
   if(i==0&&j==3)
      Serial.println("A");
   if(i==1&&j==0)
      Serial.println("4");
   if(i==1&&j==1)
      Serial.println("5");
   if(i==1&&j==2)
      Serial.println("6");
   if(i==1&&j==3)
      Serial.println("B");
   if(i==2&&j==0)
      Serial.println("7");
   if(i==2&&j==1)
      Serial.println("8");
   if(i==2&&j==2)
      Serial.println("9");
   if(i==2&&j==3)
      Serial.println("C");
   if(i==3&&j==0)
      Serial.println("*");
   if(i==3&&j==1)
      Serial.println("0");
   if(i==3&&j==2)
      Serial.println("#");
   if(i==3&&j==3)
      Serial.println("D");
}

```

the code that doesn't work:-

```
int row[]={6,7,8,9};
int col[]={10,11,12,13};
int i,j;
int col_scan;
void setup()
{
   Serial.begin(9600);
   for(i=0;i<=3;i++)
   {
      pinMode(row[i],OUTPUT);
      pinMode(col[i],INPUT);
      digitalWrite(col[i],LOW);
   } }
void loop()
{
   for(i=0; i<=3; i++)
   {
      digitalWrite(row[0],LOW);
      digitalWrite(row[1],LOW);
      digitalWrite(row[2],LOW);
      digitalWrite(row[3],LOW);
      digitalWrite(row[i],HIGH);
      for(j=0; j<=3; j++)
      {
     col_scan=digitalRead(col[j]);
     if(col_scan==HIGH)
     {
        keypress(i,j);
        delay(300);
     }}
   }}
void keypress(int i, int j)
{
   if(i==0&&j==0)
      Serial.println("1");
   if(i==0&&j==1)
      Serial.println("2");
   if(i==0&&j==2)
      Serial.println("3");
   if(i==0&&j==3)
      Serial.println("A");
   if(i==1&&j==0)
      Serial.println("4");
   if(i==1&&j==1)
      Serial.println("5");
   if(i==1&&j==2)
      Serial.println("6");
   if(i==1&&j==3)
      Serial.println("B");
   if(i==2&&j==0)
      Serial.println("7");
   if(i==2&&j==1)
      Serial.println("8");
   if(i==2&&j==2)
      Serial.println("9");
   if(i==2&&j==3)
      Serial.println("C");
   if(i==3&&j==0)
      Serial.println("*");
   if(i==3&&j==1)
      Serial.println("0");
   if(i==3&&j==2)
      Serial.println("#");
   if(i==3&&j==3)
      Serial.println("D");
}

```

# Answer
To use unipolar switches as inputs, you need pulling resistors to give the input pin a defined value when the switch is open.

The ATmega has software configurable internal pullups. Even if these are not configured, implementation detail may (or may not) yield a very weak *unreliable* pullup effect.

There is no configurable pulldown on the ATmega. To operate in that direction (with a switch to high) you would need external pulldown resistors.

A few matrix keyboards include diodes, to combat some of the confusion which results when multiple keys are pressed in a simple matrix.

Also, you should add a tiny delay between driving and reading, in order to allow for capacitive delay.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How do I replace a burnt atmega328 with a new atmega328(bootloaded) in arduino?
I have an arduino UNO with atmega 328 whose microcontroller got burnt. I bought a new atmega328. I have another working arduino with atmega8. I followed the instructions in http://arduino.cc/en/Tutorial/ArduinoToBreadboard but I got a little confused.

I burnt the bootloader into my new atmega328 using atmega8 arduino as described in the link above. Now, can I replace my old atmega328 with this new bootloaded atmega328 to upload sketches to it? Or should I follow the steps described in the link to upload sketches?

# Answer
> 3 votes
Once the bootloader has been burned to it, the chip can replace the one that is currently on the Arduino board. Simply follow normal DIP removal and insertion procedures to replace it.

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


# Question
Title: How do I replace a burnt atmega328 with a new atmega328(bootloaded) in arduino?
I have an arduino UNO with atmega 328 whose microcontroller got burnt. I bought a new atmega328. I have another working arduino with atmega8. I followed the instructions in http://arduino.cc/en/Tutorial/ArduinoToBreadboard but I got a little confused.

I burnt the bootloader into my new atmega328 using atmega8 arduino as described in the link above. Now, can I replace my old atmega328 with this new bootloaded atmega328 to upload sketches to it? Or should I follow the steps described in the link to upload sketches?

# Answer
> 2 votes
Once the bootloader has been burned to it, the chip can replace the one that is currently on the Arduino board. Simply follow normal DIP removal and insertion procedures to replace it.

# Answer
> 0 votes
You can use the 328p as usual (for an Arduino), once the bootloader is burned.

Background: You just used your Atmega8 as an ISP (In-System-Programmer) to get a bootloader onto your new 328p. The bootloader now enables the 328p to be programmed via serial port.

---
Tags: arduino-uno, bootloader, atmega328, safety
---


# Question
Title: 'OUTPUT' was not declared in this scope - ATtiny85 with Arduino Uno r3 as ISP
I'm trying to follow this this tutorial to program an ATtiny85 micro-controller using my Arduino Uno r3 as the ISP.

I am up to the final step on the tutorial, but get an error when attempting to compile my sketch:

```
'OUTPUT' was not declared in this scope

```

I have tried multiple "Blink" scripts, but none have seemed to work.

My full error log:

```
Blink.ino:10:21: error: Arduino.h: No such file or directory
Blink.ino: In function 'void setup()':
Blink:15: error: 'OUTPUT' was not declared in this scope
Blink:15: error: 'pinMode' was not declared in this scope
Blink.ino: In function 'void loop()':
Blink:20: error: 'HIGH' was not declared in this scope
Blink:20: error: 'digitalWrite' was not declared in this scope
Blink:21: error: 'delay' was not declared in this scope
Blink:22: error: 'LOW' was not declared in this scope

```

I have also tried including Arduino.h, no help, and changing "OUTPUT" to "0x01", as it is defined to said value in Arduino.h, but instead got this error:

```
error: 'pinMode' was not declared in this scope

```

Any ideas as to what is happening?

# Answer
Create an Arduino.h in ...\Arduino\hardware\attiny45\_85\cores\attiny45\_85 containing

```
#include <WProgram.h>

```

From here https://electronics.stackexchange.com/questions/87328/arduino-as-isp-for-attiny
> 3 votes

# Answer
Try moving the "Cores" folder from the avi directory to the attiny director. The path was wrong for me and I was getting the same error. Had the same issue with the bootloader file. Moved it out of the avi folder as well and all worked ok then.
> 1 votes

---
Tags: arduino-uno, attiny, arduinoisp
---


# Question
Title: Arduino on battery getting unstable if temperature falls
i am building an outdoor sensor with a combination of a custom Arduino board and a battery (+solar charging). I experience strange behavior when the temperature falls below a certain value (i can reproduce it by putting it in the freezer), regardless which type of battery i am using. The custom Arduino runs without power-regulation, straight from the 3.7volts the battery can provide. How can i prevent this to happen? I guess a little heating would be not really a solution as i am trying to consume as less energy as possible. Would a (step up) regulator possibly help? Any other ideas?

---Update--- Thanks to your comments here i figured out, that the AVR 328p should not be operated below a voltage of 3.7v if run at 16Mhz. As i am running with a 3.7v LiPo Battery that could easily explain my problem i guess. My first try to decrease the processor speed to 8Mhz with a Prescaler worked, but the GSM Fona does not seem to like it. So i would like to try something in between like 10Mhz or 12Mhz. As the prescaler does not support this, my question is: can i just use another crystal or would i have to modify something in the code/bootloader as well?

# Answer
To answer your modified question:

Running the ATmega328p at 16Mhz with 3.7v is out of spec - see this EESE answer for reference or the ATmega datasheet - so the obvious solution would be to lower its speed to 8Mhz.

But since you also mentioned that there is an additional GSM breakout board involved (Adafruit Fona), which expects UART (in auto-baud mode) Rx/Tx connection, it might not be that trivial. Further exploration of the Fona library's source code reveals that it has several hard-coded delays (see `Adafruit_FONA.cpp::begin`, for example), but its core seems to be implemented inside the `Adafruit_FONA::readline` method, which uses an underlying `Stream`, which in turns comes from a Software/Hardware serial object, as shown in the `FONAtest.ino` example that comes with the library.

From my experience, Software/Hardware serial should work fine on 8Mhz, except maybe when using high baud rates, which is solvable. The hard-coded delays doesn't look like they should cause actual damage except for delay, but you could cut them in half just to see if you can make the library work.

Additional aspect that you should consider is the comment from Adafruit's Fona product page, regarding pin **Vio**:

> This is the pin that you MUST drive with an external voltage from 3V-5V to set the logic level converter

So, despite that from the datasheet, the Fona seems to have a voltage regulator, you might still want to consider adding a decoupling capacitor between Vcc and Gnd of your battery, to mitigate transient current draws from any component in your circuit.
> 3 votes

# Answer
It's most likely that the cold weather is messing with your batteries. I don't know what battery types you've tried, but this site says that Lithium batteries (Not Li Ion, but standard single use, expensive, lithiums) hold up well in very cold and very hot environments. For rechargeable batteries the site recommends NiMH batteries. Of course, we all know that lead acid batteries hold up well in cold (Or else our cars wouldn't start!), so those are also a viable option. Lead acids can be purchased in somewhat small forms, but they may still be too big for your purposes.

For the other part of your question, yes a regulator will help. It's rarely acceptable to run directly off a battery without a regulator. Since your application is low power you'll want to use an efficient switching regulator (Search for modules, not individual chips). Remember that a battery's output changes based on its charge level, temperature, current draw, and other things I'm likely forgetting. Using a regulator mitigates these effects as regulators are less affected by temperature and current draw than the battery that supplies it (Hopefully).

So to summarize: Use Lithium batteries, or NiMH if you need to recharge, or Lead Acid if you need a ton of capacity and size isn't a limit. Then get a switching regulator module. Best of luck with your project!
> -1 votes

# Answer
When using battery, always use a step-up converter, something like LTC3525 or NCP1402. A direct connection of unregulated battery voltage to an analog input can give you a good information on the remaining capacity while the step-up converter still provides stable 3.3V for operation.
> -1 votes

---
Tags: power, battery
---


# Question
Title: Using NodeJS, socket.io and Adafruit HUZZAH CC3000 breakout board to control Arduino wirelessly?
I'm looking to build my a wirelessly controlled lamp and have a few questions. Would I be able to use the Adafruit HUZZAH CC3000 breakout board to receive commands from a website and control a connected lamp?

I just set up a NodeJS server with webpage on my PC and using socket.io and Firmata I was able to communicate with the Arduino using the webpage over a serial connection. Could I set up similar implementation except instead of communicating over serial I'd communicate using Wifi? Would I need to host a web server on the Wifi board itself to communicate with the Arduino or is there some way to just use the wifi board as a communication between external site and Firmata?

# Answer
I happen to have received the CC3000 shield yesterday and have been playing with it today...

**What do you mean by "receive commands from a website"?**

If you mean "can it serve a simple website and act upon HTTP requests" (e.g. requests to http://arduino.local/on would turn a lamp off and http://arduino.local/off would turn if off), then yes it can. You make the HTTP requests using javascript's XMLHTTPRequest if you want to be able to communicate from within a web page without having to re-render a page.

There is an example sketch of an HTTP server included in the CC3000 library that would get you started. Note that the example HTTP server sketch can only handle one HTTP request/response at a time.

You will obviously also need some way of controlling a relay of you want to control a lamp.

**Update:** Since you updated your question to include how you are currently communicating:

I'm not familiar with socket.io or Firmata, but I'm guessing socket.io is a way of getting your web client (browser) to talk directly Firmata which talks to your Arduino over the USB-Serial connection? If so, then I'm not sure if it's possible to use the Firmata protocol over wireless, but it is possible for the CC3000 to act as a generic TCP server and act on data that it receives wirelessly, so it might be possible to communicate between socket.io and the TCP server. The EchoServer sketch shows how to set up a TCP server to receive raw data.

If you're only turning a lamp on/off you basically only need to control 1 pin. Isn't Firmata a bit overkill for that? Be careful about sketch size. I'm not sure how big Firmata compiles to, but the wireless library with some kind or server is over 22,000 byes (of a possible 32,000) on an Uno, so you might struggle to fit both on.
> 2 votes

# Answer
Have you heard of aREST.io? There is a wifi library that supports the CC3000 (http://arest.io/wifi/) that sounds like it might do a similar thing to Firmata
> 1 votes

---
Tags: shields, wifi, remote-control
---