# Question
Title: How to use Timer1 (AT328Mega) to measure the time between rising edges of two input signals
I'd like to use Timer1 to measure the time between rising edges of two input signals. Specifically, use Tn to start the timer counter and IPCn to latch the elapsed time since the rising edge of the Tn input signal. The goal is to measure the time between the rising edges of two input signals. Is there a Timer1 library out there that alread does this? Code suggestions welcomed.

# Answer
It is not perfect for your simpler task, but here is a link to a sketch that I have used to record pulses, using the Timer1 Input Capture.

In short setup the Interrupt

```
void initTimer(void) {

  // Input Capture setup
  // ICNC1: Enable Input Capture Noise Canceler
  // ICES1: =1 for trigger on rising edge
  // CS10: =1 set prescaler to 1x system clock (F_CPU)
  TCCR1A = 0;
  TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10);
  TCCR1C = 0;

  //catchFallingEdge(); // initialize to catch
  { TCCR1B &= ~(1<<ICES1); TIFR1 |= (1<<ICF1); rising = 0; }

  // Interrupt setup
  // ICIE1: Input capture
  // TOIE1: Timer1 overflow
  TIFR1 = (1<<ICF1) | (1<<TOV1);        // clear pending
  TIMSK1 = (1<<ICIE1) | (1<<TOIE1); // and enable

  // Set up the Input Capture pin, ICP1, which corresponds to Arduino D8
  pinMode(8, INPUT);
  digitalWrite(8, 0);       // leave floating to count 60 Hz etc.
  //digitalWrite(8, 1);         // or enable the pullup
}

```

Then service it

```
ISR(TIMER1_CAPT_vect) {
  union twobyte {
    uint32_t word;
    uint8_t  byte[2];
  } timevalue;

  timevalue.byte[0] = ICR1L;        // grab captured timer value
  timevalue.byte[1] = ICR1H;        // grab captured timer value

  // watch for the other edge to catch the half-pulse width
  //rising ? catchFallingEdge() : catchRisingEdge();
  if (rising) {
    TCCR1B &= ~(1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 0;
  }
  else {
    TCCR1B |= (1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 1;
  }
}

```
> 2 votes

# Answer
For more help and info, and many examples of various detailed aspects of timers, check out Nick Gammon's articles here: http://www.gammon.com.au/interrupts and here: http://www.gammon.com.au/timers

Under the first link, do a search for **"The sketch below times intervals between RISING interrupts,"** for example, to find one code segment.

**Now, important question: what is the minimum time you need to measure between events?** Are we talking milliseconds, microseconds, or nanoseconds? For the former, you can use pin polling, external interrupts, or pin change interrupts, and the millis() or micros() Arduino functions to grab timestamps. For microseconds resolution, it depends. Even the micros() function only has a 4us resolution, so you'd have to custom-configure the timer if you want better than 4us resolution time-stamps, or you could use the timer2\_counter library (http://electricrcaircraftguy.blogspot.com/2014/02/Timer2Counter-more-precise-Arduino-micros-function.html), or your own custom timer solution, for 0.5us resolution timestamps.

For nanosecond resolution (down to 62.5ns time steps), youd prob. need to use Timer1's input capture, as the other answer shows. You can also do a search for **"Timing an interval using the input capture unit"** under the 2nd link above, for another code segment on that.
> 0 votes

---
Tags: arduino-uno
---


title: USB MIDI HID with the ATmega32u4?

text:
# Question
Title: USB MIDI HID with the ATmega32u4?
There are existing projects that allow the Uno and other devices using the ATmega8u2 to operate as a USB MIDI HID, such as MocoLUFA. Unfortunately, as far as I am aware, these require uploading new firmware that isn't compatible with programming via the Arduino UI.

Are there any similar projects for the ATmega32u4 (Leonardo, Micro)?

Is it possible to use an Arduino as a USB MIDI HID, while still being able to program it as normal?

# Answer
The teensy series from pjrc.com allows USB MIDI natively (full USB speed!). It works well and does not require any firmware tomfoolery. It can also do HID keyboard/mouse/joystick natively as well.

There's the 2.0, which is 32u4, and the 2.0++ which has more pins and memory. If you want to step off the Atmel reservation the teensy 3.0 and 3.1 have more speed and memory; in a couple of weeks they are coming out with a Teensy LC which is a 3 with less bells and whistles for cheaper.
> 5 votes

---
Tags: arduino-leonardo, firmware, atmega32u4, midi
---


title: Arduino shield stacking

text:
# Question
Title: Arduino shield stacking
I have an Arduino GSM Shield mounted on an Arduino Uno. Can I stack this GPS shield above Arduino GSM shield? Will there be any pin configuration problem?

In GSM Shield hardware pin’s configuraton are as below:

```
0 - Not connected
1 - Not connected
2 - GSM Rx
3 - GSM Tx
7 - Modem reset

```

If there is any problem, how can it be solved? I would be happy if there are any alternatives for the GPS shield.

---

### Addendum

The schematic of the Arduino GSM shield:

The schematic of the SparkFun GPS shield:

# Answer
<sup>*Photo by John Boxall*</sup>

## Which pins do they use?

To determine if two shields are compatible, you have to read the specifications of both shields.

The best source for this information is the data sheets supplied with the shields. However there is also this Shield List

## Can you reassign pins?

Some shields provide a means to alter which pins are used for communications. This can take the form of a switch or a jumper - either pull-off or solder-bridge type. (the GPS shield in the question has jumpers).

Where the shields do not support pin-reassignment or provides insufficient flexibility, to work-around incompatibilities you can use an in-between shield designed for the purpose.

here is one example:

> You hear it all the time in the Arduino community, “will this shield work with my other shield?.” I think we’ve all been disappointed to find that two of our favorite shields compete for control of a digital pin here or a serial pin there. While there are sometimes some clever workarounds from elegant code modifications to aggressive ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution thus far: The Go-Between Shield.

## Are any alternatives for the foo shield

I notice that Arduino.cc now point people to the list referenced above. They used to have their own list.

Product recommendations are off-topic here but, obviously, you can search
> 6 votes

# Answer
From the shield description, the TX and RX of the GPS are mapped on pins 2 & 3, like your GSM, so you'll have to change that.

I'm using Adafruit GPS + flash card shield, which is a bit cheaper (and uses pins 7&8).
> 1 votes

# Answer
This answer does not directly address the pin conflict issue, but rather skirts around it.

I have been looking into this same issue for over a month now and have come to the conclusion that the best option is to either purchase, for around $30:

or make, for around $20 (+$60 for the modules)

a shield that uses the SIM908. The SIM908 comes with both GPRS/GSM functionality, and GPS functionality, whereas the SIM900 only has GPRS/GSM. Now, there is no longer an issue with pin conflicts, as instead of two separate shields, only one is required.

The only disadvantage is that if you already have a GPRS/GSM shield, then that purchase will become redundant.

As an aside there is an alternative of a *3G* (**WCDMA** and **HSPA**) and GPS, using both assisted-mobile (A-GPS) and mobile-based (S-GPS) modes, combined shield, from Cooking Hacks. A bit more pricey though, at $160.
> 0 votes

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


# Question
Title: Sketch stops printing after writing a few times
I am trying to build a random horoscope printer. I have a series of strings in an array which I am storing in program memory. I then pick a random number and print that index concatenated with a title. But it often (but not always) only runs 4 or 5 times.

```
#include <avr/pgmspace.h>

const char string_0[] PROGMEM = "You have a great need for other people to like and admire you. ";
const char string_1[] PROGMEM = "You have a tendency to be critical of yourself. ";
const char string_2[] PROGMEM = "You have a great deal of unused capacity which you have not turned to your advantage. ";
const char string_3[] PROGMEM = "While you have some personality weaknesses, you are generally able to compensate for them. ";
const char string_4[] PROGMEM = "Your sexual adjustment has presented problems for you. ";
const char string_5[] PROGMEM = "Disciplined and self-controlled outside, you tend to be worrisome and insecure inside. ";
const char string_6[] PROGMEM = "At times you have serious doubts as to whether you have made the right decision or done the right thing. ";
const char string_7[] PROGMEM = "You prefer a certain amount of change and variety and become dissatisfied when hemmed in by restrictions and limitations. ";
const char string_8[] PROGMEM =  "You pride yourself as an independent thinker and do not accept others' statements without satisfactory proof. ";
const char string_9[] PROGMEM = "You have found it unwise to be too frank in revealing yourself to others. ";
const char string_10[] PROGMEM = "At times you are extroverted, affable, sociable, while at other times you are introverted, wary, reserved. ";
const char string_11[] PROGMEM = "Some of your aspirations tend to be pretty unrealistic. ";
const char string_12[] PROGMEM = "Security is one of your major goals in life. ";

const char* const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5, string_6, string_7, string_8, string_9, string_10, string_11, string_12};

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(2));
}

void loop() {
    Serial.println("WE GOING TO LOOP NOW");
    char buffer[50];
    int rand = random(0,12);
    Serial.println(rand);
    strcpy_P(buffer, (char*)pgm_read_word(&(string_table[rand]))); // Necessary casts and dereferencing, just copy.
    char text[15] = "Your horoscope";
    String output;
    output = strcat(text, buffer);
    Serial.println(output);
    delay(1000);
}

```

I also sometimes don't seem to get very clean results, but I'm not sure why. I.e. printing WWWW... and missing the first part of the string in the serial monitor.

```
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GOING TO LOOP NOW
1
Your horoscopeYou have a tendency to be critical of yourself.
WE GOING TO LOOP NOW
3
or them. While you have some personality weaknesses, you are generally able to compensate for them.
WE GOING TO LOOP NOW
4
Your horoscopeYour sexual adjustment has presented problems for you.
WE GOING TO LOOP NOW
2
ge. You have a great deal of unused capacity which you have not turned to your advantage.

```

# Answer
What you see is undefined behavior. You define your buffer to have a length of 50 bytes:

> char buffer\[50\];

This is too short for most of the strings you want copy into it and you will thus overwrite other variables.

The simplest solution is to increase the buffer size so that the longest string fits (e.g. 150). You will see that it then works as you expect. Take a look at http://linux.dd.com.au/wiki/Arduino\_Static\_Strings for hints how to avoid wasting RAM for the buffer.
> 1 votes

---
Tags: progmem
---


# Question
Title: Use an ethernet shield and RFID rc522 together on a mega?
I am using an Arduino Mega and I would like to connect a rc52 RFID reader and a network shield. My problem is that both are set to use the same set of pins: 50 - 53. Can I redefine the pins used so that I can use both at the same time?

# Answer
Yes, I do think so. according to my Question with RFID and display it turned out that those pins are for serial communiacation. So I think it should work. I can verify that it will work if you do use the ICSP headers MOSI/MISO/SCLK pins. Connecting those three with the RC552 as well as GND and 3V3. Also connect two other pins to SS and RST. This pins can be adjusted in the sketch on the Arduino.
> 1 votes

---
Tags: arduino-mega, ethernet, rfid
---


# Question
Title: How to get the signal strength of the network connected with the ESP8266
I am using ESP8266 module with Arduino Uno.I don't know how to get the signal strength of the network with which ESP8266 is connected.Please help..

# Answer
The page http://tomeko.net/other/ESP8266/ names the following command:

> AT+CWLAP // list available access points

According to the example given there, this returns a list of items looking like this:

> +CWLAP:(3,"UPC784xxx",-75,"70:54:d2:xx:xx:xx",1)

where *"APs are sorted by channel and values are: (security, "name", **signal strength**, MAC, channel) where for security: 0 = open, 1 = WEP, 3 = WPA, 4 = WPA2"*.

Thus you can use `AT+CWJAP?` to obtain the name of the network you're connected to and get the signal strength from the respective item in the list provided by `AT+CWLAP`.

See http://wiki.iteadstudio.com/ESP8266\_Serial\_WIFI\_Module for a reference of commands.
> 3 votes

---
Tags: wifi, esp8266
---


# Question
Title: Can I connect an RFID reader to the ICSP header?
I am connecting an RFID reader to my Arduino mega. The directions that I have found say that I need to use pins 50-53. I also noticed that the ICSP header contains (what looks like) a secondary connection to these pins:

http://arduino.cc/en/Reference/SPI

Can I connect my RFID reader to the ICSP header:

# Answer
Yes you can. However the SS isn't present on that header. You can however use any pin you want for SS (if the library you use supports it, that is)
> 1 votes

---
Tags: arduino-mega, rfid, icsp
---


# Question
Title: Can you connect an output pin from one Arduino to the input pin of another?
I have a system that uses two Arduino boards. One is used to control several different functions, and the other is dedicated to driving a 45 second countdown display (comprised of two large 7 segment displays.) All this second Arduino needs is a single signal to tell it when to start. I would like to simply connect an output pin (on #1) to an input pin (on #2) and and send a single pulse to get the clock started. Fo something this simple, I wanted to avoid using I2C. Can I do this? If so, is there anything else I need to be aware of (like connecting ground to ground?)

# Answer
Yes, you can. That is indeed the most easy way of communication.

And like you said, you have to connect the grounds of both arduino's.

Optionally you could add a pull-up of pull-down resistor, so the countdown doesn't accidentally start if the first arduino is still starting up, or is disconnected.
> 1 votes

---
Tags: communication
---


title: snprintf crashing my program

text:
# Question
Title: snprintf crashing my program
I have to admit that I can't really use this function.

I'm trying to format some json but it crashing all the time my arduino:

```
char response[300];
tmp = "123";
snprintf(response, 300, "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]", tmp);

```

How should I use this function properly?

# Answer
> 2 votes
```
char response[300];
tmp = "123";
snprintf(response, 300,
    "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},"
    "{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]",
    tmp, tmp, tmp, tmp, tmp, tmp);

```

In other words, you should add, after the format string, as many extra parameters as there are %s in the format string.

PS: This looks like JSON, but it is not really valid JSON. The format below should give valid JSON:

```
"[{\"Name\":\"Furnace\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}},"
"{\"Name\":\"Room\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}}]",

```

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


# Question
Title: Which battery should I use to power arduino+motor shield + two 200 RPM (3.6V/1.5A)motors
I am using two motors ( from old two drill machines - same kind, these are 3.6v motors ), connected to arduino + arduino motor shield seeed studio v2.

When I measured the both motors (indvidually) using a multimeter in series with your motor and an about 3.6V power supply, I found that the both are varying from 1.46A-1.47A, (I supposed it as 1.5A)

I tried to use 18v/1.2a battery that was laying at home (from old machine ) what I have noticed is that motors are running for 3-5 seconds than stop, one of the red lights start blinking in the motor shield, then it stops for 3-5 seconds then it works again and loop.

Notes: \- The motors are working when I connect them directly to 4.5 or 6v battery. But when I try to assemle everything , it doesn't work (I am adding this just to say that motors are in good health).

* I tried 14v battery I noticed the same thing.
* The drill machine is small one (as big as a human hand). Motors from electric drills are designed as high-speed high-torque motors, but I don't think it's too high in my case to be a huge problem. It's 200 RPM DC motor
* I spent a week looking for answer before posting this thread, I tried every single solution I came across on the web.

What are things that I should consider here, any thoughts.

What did I miss? And what kind of battery should I use ??

# Answer
I have run into similar weirdness myself, and the solution that worked for me is to have separate batteries for the Arduino and the motors. This is more important if your motors run at a different voltage (e.g. 6v or 12v motors), but is useful in any case. This means that, when the motors draw to much from the batteries, the motors will slow down. If the same battery is used for the motors as for the Arduino, then the voltage drop from the motors will also apply to the Arduino; if the voltage drops in the Arduino, it will turn off (and turn back on when the voltage is restored). This is likely what you are seeing.
> 1 votes

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


title: Touch the Neopixels

text:
# Question
Title: Touch the Neopixels
I want to create a game using the individual LED "pixels" in a Neopixels 8x8 panel as a game pieces. Any ideas how I could add a touch event to each pixel?

# Answer
> 1 votes
Use a trellis.

Or put a resistive touch panel on top of the neopixels. You can connect those using 2 analog and 2 digital pins.

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


# Question
Title: Arduino Sainsmart uno communication problem
I'm trying to communicate with my arduino uno but it seems to have troubles to understand characters. For example, printing things with Serial display weird things, changes characters, removes some.

For exemple printing "test !" every two seconds results in that :

Every characters have been removed except "!"...

Is my arduino broken ? Thanks in advance

# Answer
> 1 votes
You are doing 2 things wrong in your program:

First is using serial.write(), which writes bytes rather than ASCII.

Second is you are declaring a string literal as a char instead, you must declare a string using double quotation marks (which is ") so that your program should read:

```
Serial.print("Test!");

```

When you declare 'Test !' you are doing it wrong, and it will only take the last char in the string, which is '!' - using single quote marks is for a single char declaration, like '!' or 'T', and you can make an array of chars into a string if you wanted, like this:

```
char array[] = {'T', 'E', 'S', 'T', '!' };
Serial.write(array, 5);

```

but why would you when the earlier one works better?

---
Tags: serial
---


title: RSSI stop sketch on a gboard (atmega)

text:
# Question
Title: RSSI stop sketch on a gboard (atmega)
I have this function in my code and works fine (it returns a valid value, I put this value into a int variable outside function), but when end the function (or continue the code), my sketch stop/die...

```
///FUNCION PARA RSSI XBEE///
byte rss() {  ///PARA RSSI
union {byte B; char C;} atCmd[3];
AtCommandRequest atCmdReq;
AtCommandResponse atResp;
byte respLen, *resp, dBm;
strcpy(&atCmd[0].C, "DB");
atCmdReq = AtCommandRequest(&atCmd[0].B);
atResp = AtCommandResponse();
xbee.send(atCmdReq);
if (xbee.readPacket(5000)) {
   if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
       xbee.getResponse().getAtCommandResponse(atResp);
       if (atResp.isOk()) {
           respLen = atResp.getValueLength();
           if (respLen == 1) {
               resp = atResp.getValue();
               dBm = resp[0];
                  return dBm;
           }
           else {
             //  Serial.println("Unexpected response");
           }
       }
       else {
         //  Serial.println("ERROR");
       }
   }
   else {
     //  Serial.println("Unknown response");
   }
}
else {
 //  Serial.println("No response");
}
}///fin rss()

```

¿Any tips?

# Answer
Your function is only returning a value when everything works OK. If an error occurs, the problem is reported to serial but it doesn't return anything. It seems likely that this could cause stack corruption which could make the program stop.

A simple solution would be to put `return 0;` (or some other number) just before the end of the function.
> 1 votes

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


# Question
Title: Arduino TCP communication with Android phone
I am trying to communicate Arduino Uno with an android phone. What I trying to is:

1. Android device post a string to Arduino
2. Arduino post a integer to Android

So far I can post message from Android, received in Arduino board, but I **can not post a integer to Android, nothing receive at Android**

**Arduino Code** (Which can receive character "a", "b", "c", "d", and for case "z", I would like to send back the distance which is an `int`) :

```
void loop()
{
  distance = Dist.getDistanceCentimeter();
  if(distance<=5 & distance>1)
  {
    back();
    delay(100);
    ting();
    distance=0;
  }
  if(Serial.available())
  {
    lkf = Serial.read();
  switch(lkf)
  {
  case 'a':
     front();
     servoX.write(90);
     lkf=0;
     break;
   case 'b':
     back();
     lkf=0;
     break;
   case 'c':
     left();
     lkf=0;
     break;
   case 'd':
     right();
     lkf=0;
     break;
  case 'z':
    Serial.write(distance);
    break;
    }
  }
 }

```

**Android Code:**

**In Main Activity**

```
@Override
protected TCPClient doInBackground(String... message) {

    //create TCPClient object
    mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
        @Override
        //check whether server return message
        public void messageReceived(String message) {
            f_sensor.setText(message);
            Log.d("test1","msg rece" + message);
            //publishProgress(message);
        }
    });
    mTcpClient.run();

    return null;
}

```

**TCP Cilent**

```
public class TCPClient {

    private String serverMessage;
    public static final String SERVERIP = "192.168.8.1"; //your computer IP address
    public static final int SERVERPORT = 2001;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    PrintWriter out;
    BufferedReader in;

    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }

    public void stopClient(){
        mRun = false;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVERIP);

            Log.e("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVERPORT);

            try {

                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                Log.e("TCP Client", "C: Sent.");

                Log.e("TCP Client", "C: Done.");

                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }

                Log.d("test1",serverMessage);
                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");

            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);

        }

    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

```

# Answer
> 0 votes
Using `serial.println` instead of `serial.write` fixes the issue.

---
Tags: arduino-uno, serial, programming, networking, tcpip
---


# Question
Title: How to add Ultrasonic Sensor to the board?
I am making an RC car , have combined the **Arduino UNO R3** with the **AR 293d**, and pluged in the HC-SR04 sensor to the SRO4 hole at the left top corner in the below graph. However, besides one sensor I **would like to add three more HC-SR04 sensor**.

Reference: http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

The problems are

1) is the board sufficient to plug three more sensor ?

2) or what extra board I need if not sufficient and how to combine those board

2) also, can I plug in other hole?

Thanks for helping

**Update: breadboard connection**

So I have to get a stuff like this?

http://www.tandyonline.co.uk/small-solderless-breadboard.html

and one more question, sorry for begin newbie, there are many holes on breadboard, which hole I should connect those three sensor on it, and the hold I should connect the breadboard with the AR-293D board?

And for programming, is there any way to get the pin at the breadboard as I have read some program before, the pin is assign with a number?

Thanks again for helping.

# Answer
> 3 votes
1) Not really. You have so little space and you have to selder them. Try using wires

2) If you want it to be flexible use a sandard solderless breadoard on the center of the car and then with male-female jumperwires try connecting them.

3) The board has traces. That means some holes have a very specific purpose.

## Updated:

On every breadboard the holes are connected verticaly. For example, in the image from your breadboard you posted 1A, 1B, 1C, 1D and 1E are connected together. If you would like to have all of the 3 sensors better use wires and then atach them on to your breadboard.

Here is a picture: https://www.dropbox.com/s/3ij4w6eytio8p08/Screen%2016-25-31.png?dl=0

---
Tags: arduino-uno, serial, sensors, pins, arduino-ide
---


title: ATMega328P-PU and 328P-AU

text:
# Question
Title: ATMega328P-PU and 328P-AU
im planing to make my very own arduino design based on the Arduino PRO mini. I picked this board instead of the UNO mostly because it's way more simpler compared with the UNO since the USB-to-Serial part is missing. As many of you know the MINI uses the 328P-AU which is the SMD version of the 328P however since the AU version is too small for me i would like to use the PU (UNO's chip) instead. From the datasheets the only difference is a small change in the pins position. And the one million dollar question is: Is there any difference on those 2 chips? If i try to use the same design just with the PU model is it gonna work?

# Answer
The `-AU` and `-PU` suffixes on the part name indicate different packages. The former is used for the "32A" package (32-lead TQFP), and the latter is used for the "28P3" package (28-lead DIP). In plain English, the `-AU` is a surface-mount part, and the `-PU` is a breadboard-friendly chip.

As far as functionality, there is virtually no difference. The 32A package exposes pins for ADC6 and ADC7, which are not available on the 28P3 package, but they are otherwise identical. (Note that these pins are *only* used for the ADCs; they are not a member of any port, and thus cannot be used for digital I/O.)
> 10 votes

# Answer
There is no difference as far as Arduino is concerned. I think the AU has a couple extra pins (analog ins), that you might want to route to header locations in a surface mount design, but if your design is based on an Uno, them you can also just leave those pins disconnected with no impact.
> 5 votes

# Answer
I would go with the PU version because you can work on a breadboard with it for testing. If you are going to make a surface mount this to a PCB then use the AU. Regarding the actual difference forgetting about form factor, there is none.
> 0 votes

---
Tags: pins, atmega328, system-design
---


# Question
Title: For the digital output pins, how is LOW different than no connection?
I am working with relays and I noticed that connecting the trigger pin to ground (or a digital pin set to LOW) is not the same as having the trigger connected to anything. For the digital output pins, how is LOW different than no connection? Is there actually a current flowing into the LOW pin, or is there a tiny current flowing into the relay?

Is Ground and LOW the same voltage?

# Answer
> 3 votes
*(Edit for clarification: I've assumed in this answer that you're asking about the difference between connecting the relay to ground/LOW vs. connecting the relay to nothing at all. I've also assumed by the word "trigger" that your relay has some kind of digital actuation built-in, such as a transistor, or that it's simply a Solid State Relay.)*

If something is unconnected, it is described as 'floating'. This means there could be random voltage spikes in it caused by nearby electromagnetic fields, making it appear to be switching on/off.

Connecting something to ground or LOW can stop this from happening by drawing away any induced currents.

# Answer
> 0 votes
Ground and LOW are very, very close in voltage. They are the same when no current is being sunk into the output (LOW sinks current from higher voltages, HIGH sources current to lower voltages), but the voltage rises as the current does (the output has a resistance of about 25ohm).

---
Tags: digital
---


title: Necessary sampling rate

text:
# Question
Title: Necessary sampling rate
I'm using an Arduino pro mini to receive the analog signals from three sensors. I was wondering what sampling rate I should sample at in order to properly represent these signals. I know it should be twice the highest analog frequency, but I'm not sure what frequency theses sensors operate in. They're an ECG, a 3 axis accelerometer, and a stretch resistor respectively. To my knowledge, Arduino defaults at a sampling rate of 10kHz, which I believe should be more than enough to quantize the sensor signals. I'm then sending these signals out using bluetooth mate to an android phone. Is there a specific baudrate I should send the data at?

Here is the initialization of my code:

```
void setup()
{
  Serial.begin(9600);
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
  setTime(0);
}

```

Thanks so much

# Answer
The sampling frequency you are referring to (twice the highest frequency) is for capturing waves, but is not really a concern for the sensors you are using and the types of data they are used to measure.

If you wanted to analyse the magnitude of a 40kHz vibration in a structure, you should worry about sampling rates on your accelerometer; however, if you want to measure the accelerometers current angle to the ground (assuming its not accelerating), you only need to take one sample.

With the ECG, there will be a signal among all the analog voltages you read of a heartbeat (I'm assuming its hooked up to a person). This signal will never get much over 200 beats per minute, or 3.3 Hz. To capture a 3.3Hz signal you need a minimum sampling rate of 6.6Hz, which as still incredibly slow. The same goes for capturing a gait with your accelerometer.

If you capture the analog voltage of your sensors output with analogRead 100 times a second, you should have a very clear and well defined view of the very low frequency signals you are trying to track, and should not have any issues with transferring that much information over serial.

5, 16 bit values can theoretically be sent at 120Hz over 9600 baud, and its very easy to use faster speeds then that if you want more information.
> 1 votes

# Answer
Since I think BrettAM already gave a pretty good answer, I'm going to expound just a little upon that.

First off: I think you're misunderstanding sample rate. The sample rate here is simply the number of analog readings per second that you are doing of a given signal.

If you want to know the **maximum** sample rate of the Arduino, you simply have to take a ton of samples as fast as you can and see how many you were able to take in a given second. For the Arduino with default settings, that's ~9600 per second *maximum*. If you just take 1 single sample though, your sample rate is......I don't know.....how often do you do this!? If you take 1 sample and then stop your sketch for an hour, your sample rate for that one sample was 1 sample per hour. Now, what are you sampling? If what your're sampling is *changing* faster than one noticeable change (ADC resolution step) per hour, then you need to sample faster than once per hour. If your signal (what you're sampling) is changing at 100 times per second (100Hz), however, then you need to sample at *at least* 200 Hz to even detect it's changing at 100Hz, and at *approximately 1000Hz or higher* to actually plot what that 100Hz signal looks like. Note: sampling at 2x the rate of the sampl**ed** signal is the minimum sample rate required to detect the frequency of the sampl**ed** signal, and is called the Nyquist Frequency. Sampling at 10x the sampl**ed** signal is the generally-accepted rule-of-thumb for minimum sample rate required to capture the *waveform,* or *shape* of the sampl**ed** signal.

Now, let's look into data smoothing. If you just take a single sample, it might bounce around. How do you stop this? One method, is to take many samples and average the result. A library I wrote does this, among many other things, so I'll present it here.

Taking many samples in a row then using the average of the samples in any calculations helps to remove the noise component from your signal. I have written an oversampling library that among other things, does just that. An (outdated..will be updated eventually) page on it is here: Using the Arduino Uno’s built-in 10-bit to 21-bit ADC (Analog to Digital Converter).

The current version of the code is V2.1 alpha, and the download link is currently highlighted in yellow at the link above.

In case you need to take faster samples, you can also speed up the ADC sample rate to 50+ kHz, using my library...as opposed to settling on the default 9600Hz of the Arduino.

Play around with sampling and smoothing and stuff. One technique is to speed up the ADC (so you don't waste too much time sampling), then take the avg. of many samples in order to help remove noise from your sensors. This may be unnecessary, if noise is minimal or changes over time on the signal are slow, but for the sake of learning I'll present this.

Here's an example sketch:

```
//include the library
#include <eRCaGuy_NewAnalogRead.h>

//Global Vars
byte pin = A0;
byte bitsOfResolution = 10; //commanded oversampled resolution
unsigned long numSamplesToAvg = 50; //number of samples AT THE OVERSAMPLED RESOLUTION that you want to take and average

void setup()
{
  //Configure the adc how you want it
  adc.setADCSpeed(ADC_PRESCALER_16_CLOCK_1MHZ); //this speeds up the ADC clock by a factor of 8
}

void loop()
{
  //local variables
  unsigned long analogReading;

  //take a reading on the analog pin
 analogReading = adc.newAnalogRead(pin,bitsOfResolution,numSamplesToAvg);
}

```

You'll see that I am speeding up the ADC and taking and averaging 50 samples to smooth the data. I have yet to test the speed, but I estimate this could prob. run at 500Hz or so max sample rate (returning an average value each time)...assuming that's all you did.

Doing this and taking a single sample is fine for what you need I believe.

Now, for baud rate. Baud rate is essentially "bits of data sent per second." It's how fast your communication signal is. Lower baud rates are generally less susceptible to electrical noise, and the data is less likely to get corrupted, but higher baud rates send the data values much more quickly and waste less of your code time sitting around transferring data. I recommend you speed it up to maximum, unless you have data transfer problems or dropouts, in which case you should slow it down a bit.

NOTE: for more detailed examples on the library download it and look in the examples folder.
> 1 votes

---
Tags: programming, sensors, bluetooth, arduino-pro-mini, signal-processing
---


title: Powering USB device from arduino uno?

text:
# Question
Title: Powering USB device from arduino uno?
I'm wanting to power a USB device from an Arduino Uno. Forgetting about the two data pins, it just requires power. Using a power meter, I can detect the 5v pin at about 4.95 volts, however I don't have access to any resistors at the moment so cannot test the amperage because it just shorts.

The USB device I want to power requires ~300mA (can't remember specifically). First of all, does the Arduino get 100mA or 500mA when getting power from the USB? Is this changeable depending on the setting on the USB Host (High 500mA, or Low 100mA)?

Secondly, how much would actually be usable? I assume the Arduino itself would require some of that current? Even more if a program where running on it at the same time? (I have no idea how computers utilize power) I would like to just hook up my usb device to ground and 5V with whatever resistors (and any other electrical components) in between to bring it down from 500mA to the required ~300mA.

# Answer
> 0 votes
The Arduino receives 500mA max from USB power. That is per the USB specification, and the Arduino has a 500mA resettable fuse on the USB power to protect your computer's USB port from 'accidents'.

As to the question of whether it is configurable between 500mA/100mA, generally no it's not. I believe that part of the USB negotiation that occurs when the Arduino connects to your PC is that the Arduino describes itself to the computer, and it reports that it is a 500mA device. Bottom line is, you won't need to do anything special in this regard.

Now, how much of the power is needed for the Arduino, and how much is left over - well that depends on what else the Arduino is doing and what else it's powering (LEDs, etc.). If the Arduino is not doing much else, than 200mA should be plenty of headroom for it.

If you power the Arduino through the PWR Jack (or the Vin), then the voltage should be a minimum of 7V. That is because it is feeding into a 5v regulator, which has some voltage drop, so it needs about 7V to be able to consistently supply 5V output. If you power the Arduino manually (through the 5V pin), you want to give it 5V. Anything less than 5V would be considered overclocking. (The ATMEGA328P needs 5V to operate at 16mHz, but can run at lower voltages when clocked at lower speeds.)

Also, keep in mind that the USB port on the Arduino is a USB 'client', not a USB host or USB OTG. Therefore, the port can not be used to supply outbound power. You can power your extra device from the Arduino's 5V and GND pins.

# Answer
> 0 votes
You'd have to test this but there's a chance you could supply the Arduino using a DC power supply on it's 5V pin. In this case DO NOT TURN YPUR SUPPLY HIGHER THAN 5V, as I don't believe there is any protection and will send the full voltage to the USB.

A safer option would be the Vin pin. Normally you'd want to put 7-12 Volts to this pin but you may want to start at 5V and work your way up just to be safe.

Someone please corrects if I am wrong, but if you never apply more than an external 5V your worst case scenario would be burning out the Arduino but not the USB device.

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


# Question
Title: which is the most efficient way to save power with battery using Arduino UNO?
I am working with a ArduinoUNO - 2100 mA battery, and a solar Charger shield. I use a temperature reader that sends info **every half hour with GPS-GSM shield** called LONET (http://www.seeedstudio.com/wiki/LoNet\_-\_GSM/GPRS/GPS\_Breakout for more info).

I want to save all the energy i can, i am trying to put Arduino UNO and LONET on Sleep mode.

LONE has its own mode via “AT+CSCLK=1”.

But for Arduino UNO i haven seen a library called Narcoleptic (https://code.google.com/p/narcoleptic/ for more info) wich can solve the problem.

My question is:

Is there any other method that can help me to save Battery with Arduino uno? is it a good approach to use Narcoleptic or there is another method to do it?

Thanks for your time/help and sorry for my English.

Any feedback could be welcome.

# Answer
There is an even greater article on this topic: http://www.gammon.com.au/power

It shows how to reduce your power usage for the Uno from about 50mA to 350nA (0.000350mA) - at this point, you need to factor in the natural drain of batteries.

Also, I have had good success with a project that was activated by a pushbutton, by using a latch - the push button turned the power on; once the power is on, it latched. Then the Arduino can switch itself off, using one of it's pins. As far as I can tell from a simulator, there is no leakage (while it is off, to within the accuracy of the simulator, assuming a perfectly spherical transistor in a vacuum ;) ).

Just in case anyone is interested, my latch circuit can be seen at: https://i.stack.imgur.com/Uf9sX.png \- the two resistors and the switch at the bottom represent the Arduino - +5V coming in the top, GND at the bottom, and one of the pin to switch it off is the switch - this pin should be INPUT to keep the power on; when you are ready to switch of, set it to output -\> high. You should get switched off immediately. The switch at the top will switch it on. In the startup part of your sketch, set the pin to INPUT first.
> 5 votes

# Answer
There's a great article on that topic: https://www.openhomeautomation.net/arduino-battery/
> 2 votes

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


# Question
Title: Arduino Uno with CC3000 WiFi Shield cannot be initialized
I am working on an Arduino Uno and CC3000 WiFi shield. I interfaced it over my Arduino and added the SparkFun library `SFE_CC3000_Library`. Then I opened the TestBoard example, but it hangs on setup in the first command `wifi.init()`.

How can I solve this problem, and how can I enable debug mode?

Here's the code

```
#include <SPI.h>
#include <SFE_CC3000.h>
#include <utility/netapp.h>

#define DEBUG     1
// Pins
#define CC3000_INT      2   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       7   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// Constants
#define FW_VER_LEN      2   // Length of firmware version in bytes
#define MAC_ADDR_LEN    6   // Length of MAC address in bytes

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);

void setup() {

  int i;
  unsigned char fw_ver[FW_VER_LEN];
  unsigned char mac_addr[MAC_ADDR_LEN];

  // Initialize Serial port
  Serial.begin(115200);
  Serial.println();
  Serial.println("----------------------------");
  Serial.println("SparkFun CC3000 - Board Test");
  Serial.println("----------------------------");

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() ) {
    digitalWrite(13, HIGH);
    Serial.println("CC3000 initialization complete");
  } else {
    Serial.println("Something went wrong during CC3000 init!");
  }

  // Read and display CC3000 firmware version
  if ( wifi.getFirmwareVersion(fw_ver) ) {
    Serial.print("Firmware version: ");
    Serial.print(fw_ver[0], DEC);
    Serial.print(".");
    Serial.print(fw_ver[1], DEC);
    Serial.println();
  } else {
    Serial.println("Could not read firmware version from CC3000");
  }

  // Read and display CC3000 MAC address
  if ( wifi.getMacAddress(mac_addr) ) {
    Serial.print("MAC address: ");
    for ( i = 0; i < MAC_ADDR_LEN; i++ ) {
      if ( mac_addr[i] < 0x10 ) {
        Serial.print("0");
      }
      Serial.print(mac_addr[i], HEX);
      if ( i < MAC_ADDR_LEN - 1 ) {
        Serial.print(":");
      }
    }
    Serial.println();
  } else {
    Serial.println("Could not read MAC address from CC3000");
  }

  // Done!
  Serial.println("Finished board test");

}

void loop() {

  // Do nothing
  delay(1000);
  Serial.println("Loop_Problem");

    }

```

# Answer
Solved it, the problem was because the SparkFun library was not working with my shield. I replaced it using the `Adafruit_CC3000_Library` and now it works fine.
> 2 votes

# Answer
I was having the same problem with the ethernet shield (and i still have it). In my case it was caused by the network router. When my modem/router couldn't connect to the net (bad weather etc...) the shield couldn't take an IP and the initialaization was failing every time just because i was disconnected from the internet. The library works almost the same way. Basicaly you have to make sure it can connect.
> -1 votes

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


# Question
Title: How to upload program to board using Arduino sketch ver 1.6?
I am having problems uploading my program. I have been using the verify button aka the "checkmark" to upload my programs. I assumed that this was the correct button but now I am having problems uploading. When I attempt to use the "upload" button I get the error "can not open device". What am I doing wrong? How can I fix this error code?

# Answer
> 2 votes
The checkmark button is used to compile your program (which "verifies" your code), but does not upload it to the board. The "arrow" button is used to compile and upload your program.

If you cannot connect to the device, make sure the correct COM port is selected on the Tools-\>Ports menu, and make sure you have the correct board selected on Tools-\>Board (usually an Arduino UNO).

If you have not installed the drivers yet, you will not have a port present for your Arduino. If that is the case, here is a great tutorial that will help you get everything installed and set up correctly: https://learn.adafruit.com/lesson-0-getting-started

---
Tags: uploading, sketch
---


title: Program attiny13 with Arduino uno 1.6

text:
# Question
Title: Program attiny13 with Arduino uno 1.6
I am looking for the boards.txt, platform.txt and core files needed for the programming of the ATtiny13 with the Arduino Uno. Those I find on the internet probably only works with Arduino 1.0 and not with 1.6.

# Answer
You can use the library for IDE 1.6 https://github.com/damellis/attiny/
> 1 votes

---
Tags: core-libraries
---


# Question
Title: Connecting light and temperature sensors and LEDs to an Arduino
Fairly new to arduino, what is the best and simplest way to connect an LM35 temperature sensor, a GL5528 photoresistor and some LEDs as well as the required resistors to an arduino for recording values? Any tutorials with wiring diagrams for something similar would be helpful.

# Answer
The LM35 is a very common temperature sensor. It has 3 pins - Vs, Vout, and Gnd. Connect Vs to the Arduino's Vs pin. Connect the Gnd pin to one of the Arduino's GND pins. The Vout pin should be connected to an Analog input pin. If you google your board, you should find the pinout on Arduino's website. The LM35 pin diagram and information on how to calculate the temperature from voltage is found in the LM35's Datasheet. Here is LadyAda's Temerature Sensor tutorial (note: the tutorial specifies the TMP36, however the two sensors are comparable). Here is an instructable for the LM35 (includes diagrams and source code).

The GL5528 is a photoresistor. That means its resistance changes proportional to how much light strikes its sensor surface. Because of this trait, we can build a Voltage Divider. This will allow us to read in values (again, analog values). AdaFruit's tutorial is very comprehensive and includes diagrams.

LEDs are generally considered output displays (we program to use LEDs as a visual display of state). A good starting place for Arduino LEDs is the Blink Example. we connect an LED and resistor in series with an Arduino output pin and GND or 5v. This allows us to 'write' to the Arduino pin HIGH or LOW, turning the LED on or off.

I found these results by googling 'Arduino LM35', 'Arduino GL5528', and 'Arduino LED' respectively.
> 1 votes

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


title: Arduino or Raspberry Pi for my project

text:
# Question
Title: Arduino or Raspberry Pi for my project
A brief description of what I'm doing here. I wanna make a pet project, basically a device (be it Arduino or raspberry pi) that I can connect to via bluetooth / wifi (both preferably), that will be connected to a stereo system and allow me to play music. I essentially want to make a wireless sound system in my house.

My question is, is raspberry pi more adequate for my needs? Or would arduino get the job done? I know that raspberry pis are essentially mini computers, so I feel that the raspberry pi would be too much, since all I really need to do is design a bluetooth / wifi interface and send the signal to the aux cable connected to the stereo.

Any help would be really useful here. I've never worked with either/or, and this is my first project with Arduino / Raspberry pi (hello world). Thanks in advance.

EDIT: In response to comments below, a greater idea of what I want to do:

I want to design an item that will appear on local wifi as a sound device. i.e. on an imac / macbook I'd be able to right click on the speaker icon in the upper right and select it there). From there, I'm hoping to stream audio to the device, and have it play to a stereo that the arduino / raspberry pi would be connected to. I'd love to make this universal (i.e. possible to connect via your android phone / a windows machine), but I can imagine that part being a lot more difficult. I'd also like to add bluetooth functionality at some point, but that'd be in the future. Hopefully this gives everybody more of an idea of what I'd like to achieve here! I appreciate all the help so far.

# Answer
> 2 votes
As mentioned in the comments, a Raspberry Pi would be superior here.

The standard AVR (not Due/Galileo/Yun) Arduino is superior to the Pi in only one area: IO. It has a 5V logic that's more compatible than the Pi's 3.3V (although you can use a *logic level shifter*). The Arduino also features more PWM pins and an ADC, along with interrupts. An Arduino also is a lot simpler to use for basic projects, but it becomes impractical when you need more computing power.

A Pi excels at the data-crunching side of things. It can handle a lot more data than the Arduino could ever dream of, and then some! Just to put things in perspective, the Pi has a clock speed of 700 MHz by default and the Arduino Uno has one of 16 MHz (with a less powerful architecture).

For your purpose, the Pi's audio jack and ethernet port are unmatched on the Arduino. *Sure*, you can get shields that replicate these behaviors, but the Pi's built in functionality doesn't cost extra and it's more powerful.

# Answer
> -1 votes
While it might be an interesting project, the overall quality of the sound generated by such do-it-yourself contraption, is likely to be highly disappointing, because of the not-stellar quality of the final analog stage in the audio output.

---
Tags: bluetooth, wifi
---


# Question
Title: Can I have help interperting this code? char variable somehow storing big numbers
I have this GSM module I got for my arduino project and I am trying to access the call feature, but the function makes no sense.

```
  boolean Adafruit_FONA::callPhone(char *number) {
  char sendbuff[35] = "ATD";
  strncpy(sendbuff+3, number, min(30, strlen(number)));
  uint8_t x = strlen(sendbuff);
  sendbuff[x] = ';';
  sendbuff[x+1] = 0;
  //Serial.println(sendbuff);

  return sendCheckReply(sendbuff, "OK");
  }

```

This is the function however how is char being used to display a phone number in the parameter?

# Answer
> 3 votes
It's passed as a `char*`. This can be derived from either a string literal (e.g. `"212555121"`) or from a `String` via its `c_str()` method.

# Answer
> 2 votes
Keeping it simple:

`char *number;` a variable pointing to a character (or string of them).
`char sendbuff[35];` 35 characters in a row, making a string.
The first 3 chars at locatiion sendbuff are initialised to "A", "T", & "D", then the string at "number" is copied to it (to a maximum of 30 characters, by taking the lesser of the length of "number" or 30. This is important to avoid over-running the space allocated.
This string of characters gets sent out; & a check is made for an "O" & a "K"

If you don't 'get' pointers, you need to look it up, as it's pretty central stuff.

---
Tags: c++, data-type
---


# Question
Title: Difficult between atmega328 & atmega2560 when coding & compiling in a pure c
I have an arduino uno with atmega328p controller.

I found the code to deal with some specific uart protocol, named mdb: https://github.com/Bouni/MateDealer/tree/master/arduino

But it's compiled just for atmega2560 controller: https://github.com/Bouni/MateDealer/blob/master/arduino/makefile#L42

If I replace it by `atmega328p` or `atmega328`, I get the error:

```
asiniy@misha:~/projects/MateDealer/arduino$ make all

-------- begin --------
avr-gcc (GCC) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Compiling: main.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/main.o.d main.c -o main.o

Compiling: usart.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=usart.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/usart.o.d usart.c -o usart.o
usart.c:25:40: error: ‘UBRR1H’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                        ^
usart.c:25:49: error: ‘UBRR1L’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                 ^
usart.c:25:58: error: ‘UCSR1B’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                          ^
usart.c:25:67: error: ‘UCSR1C’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                                   ^
In file included from usart.c:14:0:
usart.c: In function ‘USART0_RX_vect’:
usart.c:185:5: warning: ‘USART0_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_RX_vect){
     ^
usart.c: In function ‘USART1_RX_vect’:
usart.c:197:5: warning: ‘USART1_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_RX_vect){
     ^
usart.c:203:12: error: ‘UDR1’ undeclared (first use in this function)
     data = UDR1;
            ^
usart.c:203:12: note: each undeclared identifier is reported only once for each function it appears in
In file included from usart.c:14:0:
usart.c: In function ‘USART0_UDRE_vect’:
usart.c:233:5: warning: ‘USART0_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_UDRE_vect){
     ^
usart.c: In function ‘USART1_UDRE_vect’:
usart.c:253:5: warning: ‘USART1_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_UDRE_vect){
     ^
usart.c:261:31: error: ‘TXB81’ undeclared (first use in this function)
                 UCSR1B |= (1<<TXB81);
                               ^
usart.c:266:9: error: ‘UDR1’ undeclared (first use in this function)
         UDR1 = data;
         ^
usart.c:269:20: error: ‘UDRIE1’ undeclared (first use in this function)
     UCSR1B &= ~(1<<UDRIE1);
                    ^
make: *** [usart.o] Error 1

```

I've tried to play with compilers (default is gnu99) and so on, but with no success. Why I have this trouble? How can I compile this code for upload it to arduino?

# Answer
> 2 votes
I'm the author of the MateDealer project and I never had the intention to port it to other boards than the Arduino Mega2560!

Ignacio Vazquez-Abrams is absolutely right, the Arduino Mega2560 is the only board with more than 1 serial port (Yes there is the Due and the Leonardo, but those would require major changes to the code).

The fastest way to get the code running is by using a Mega2560, but be warned, the code might be bugy as hell ;-)

# Answer
> 1 votes
The '328 only has a single USART. You will need to remove all references to USARTs beyond the first as well as the numeric suffix from the USART register names in order to get it to compile.

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


title: Connecting PC speaker to Arduino

text:
# Question
Title: Connecting PC speaker to Arduino
I've looted this speaker from my old PC and trying to understand how to connect it to Arduino to produce simple sound notification (and not fry anything in the process).

As far as I understand this is a piezo speaker, there is no markings on it. Here is how it looks:

How do I connect\control it?

Should I connect it to PWM pin? If so, what are the safe values to output on PWM pin?

Should I use resistor when connecting speaker? What resistor should I use?

# Answer
No need for a resistor. Just connect black to ground, and red to a IO pin. Use the tone function to specify a frequency.
> 2 votes

---
Tags: pwm, audio
---


title: Stop servo when enter 0

text:
# Question
Title: Stop servo when enter 0
I am trying to stop servo motor from rotating when I enter 0 in serial. The code is below. Can someone please help?

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int state;
int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin (9600);
}

void loop()
{
  if (Serial.available () > 0)
  {
    state = Serial.read ();
    if (state == '1')
    {
      for (pos = 0; pos <= 180; pos += 1)
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);
      }
      for (pos = 180; pos >= 0; pos -= 1)
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);      // waits 15ms for the servo to reach the position
      }
      if (Serial.available () > 0)
      {
        state = Serial.read ();
        if (state == '0')
        {
          myservo.write ('90');
          delay (300);
        }
      }
    }
  }
}

```

# Answer
> 1 votes
From the code you posted it looks like you have the right idea but you've nested the 'IF' statements causing the check for '0' to only happen if you send two bytes and it will only go to 90deg when you send '10'. The loop section should look more like:

```
if(Serial.available()){
    state = Serial.read();
    if(state == '1'){
           Make motor move;
    }else if(state == '0'){
           Make motor stop;
    }//end of elseif
}//end of if

```

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


title: 5V FTDI cable for Arduimu V3

text:
# Question
Title: 5V FTDI cable for Arduimu V3
I just recently bought an Arduimu v3. Rather annoyingly they did not supply an FTDI cable. I'm going for an FTDI cable where the I/O pins are configured to operate at 5v. I assume this is the right but I don't want to fry this board. Is this cable OK?

# Answer
A 5V cable would be fine, or for about the same price, I would recommend an Adafruit FTDI Friend which is configurable between 5V and 3.3V.
> 0 votes

# Answer
Yes, as long as the board is 5V
> 0 votes

---
Tags: ftdi
---


title: Use object of other class within class

text:
# Question
Title: Use object of other class within class
I am writing a class for a project which will take care of handling any LCD updates for my project. The way I want to handle this is to initialize the LCD object in my main file, and then pass the LCD object on to my own class when initializing it. The LCD object should be declared a private object in my class so several member functions can access it.

The problem is I can't find how to initialize the object correctly in the .h file. Below is what I currently have, but when I try to build it, I get:

```
LCDController.h:_Clcd1' should be initialized
LCDController.h:_Clcd2' should be initialized

```

main .ino file:

```
void setup()
{
  //LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
  LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
  LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

  LCDController.init(lcd, lcd2);
}

```

LCDController.h file:

```
// LCDController.h

#ifndef _LCDCONTROLLER_h
#define _LCDCONTROLLER_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif
#include <LiquidCrystal.h>
class LCDControllerClass
{
 protected:

 public:
    void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2);
private:
   void _UpdateLCD(int iLine, int iPosition, String cText);
   LiquidCrystal& _Clcd1;
   LiquidCrystal& _Clcd2;
};

extern LCDControllerClass LCDController;

#endif

```

LCDController.cpp file:

```
#include "LCDController.h"
#include <LiquidCrystal.h>

void LCDControllerClass::init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1.begin(40, 2);
   _Clcd1.clear();

   _Clcd2 = Clcd2;
   _Clcd2.begin(40, 2);
   _Clcd2.clear();

}

```

# Answer
> 4 votes
In C++, a class that holds reference members (in your sample, `LiquidCrystal& _Clcd1;` and `LiquidCrystal& _Clcd2;`) must ensure these references are initialized at construction time, not later.

This means your `void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2);` method is not the right way to initialize `_Clcd1` and `_Clcd2` because it will be called **after construction time**.

You have 2 ways to solve this issue,t hat I will detail further below.

**HOWEVER**, before we discuss the solutions, you must be aware that your sample code has **a huge defect in `setup()` method code**!

```
void setup()
{
    //LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
    LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

    LCDController.init(lcd, lcd2);
}

```

Here, you create `lcd` and `lcd2` in your `setup` method, but their life ends at the end of `setup()`, because they have been allocated **on the stack**. Using these outside `setup()` will most likely cause your program to crash as soon as your `loop()` tries to access `lcd` or `lcd2`, indirectly through `LCDController` method calls.

To remove this defect, you must declare these variables outside `setup`:

```
//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

void setup()
{
    LCDController.init(lcd, lcd2);
}

```

Now you can use them anywhere in your program, you are sure they are present and "alive".

Now we can go to the solutions of the original compilation problem.

# 1. Initialize references at construction by adding a constructor

```
class LCDControllerClass
{
    public:
    LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
    : _Clcd1(Clcd1), _Clcd2(Clcd2) {}
    ...
};

```

You can still keep an `void init()` method to complete the initialization if you don't want it to occur right at construction time, or you can fully integrate the current `init()` content into the constructor and re,voe `init()` altogether:

```
class LCDControllerClass
{
    public:
    LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
    : _Clcd1(Clcd1), _Clcd2(Clcd2)
    {
        _Clcd1.begin(40, 2);
        _Clcd1.clear();

        _Clcd2.begin(40, 2);
        _Clcd2.clear();
    }
    ...
};

```

In anycase, you will have to change the way you instantiate your `LCDControllerClass LCDController` which you did not show in your sample code, that would be something like this:

```
LiquidCrystal lcd(...);
LiquidCrystal lcd2(...);
LCDControllerClass LCDController(lcd, lcd2);

```

That obviously requires that you can instantitate `lcd` and `lcd2` **before** creating `LCDController`. If that is not possible for you, then you'll have to use the second way.

# 2. Replace references with pointers

As mentioned before, in a class reference members MUST be initialized at construction time (moreover, they cannot be changed afterwards, to point somewhere else). This is not the case for pointers however:

```
class LCDControllerClass
{
    public:
    void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);

    private:
    void _UpdateLCD(int iLine, int iPosition, String cText);
    LiquidCrystal* _Clcd1;
    LiquidCrystal* _Clcd2;
};

void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1->begin(40, 2);
   _Clcd1->clear();

   _Clcd2 = Clcd2;
   _Clcd2->begin(40, 2);
   _Clcd2->clear();
}

```

Note that now, you need to use the arrow notation `->` to access `_Clcd1` and `_Clcd2` members (dot notation cannot work for pointers).

The rest of the code should be slightly modified to reflect this change:

```
//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

void setup()
{
    LCDController.init(&lcd, &lcd2);
}

```

Note that we now have to pass **the address** of `lcd` and `lcd2` to `init()`, by using `&` before their names.

---
Tags: programming, c++, lcd, class
---


# Question
Title: I²C between ATTiny85 (8MHz) and Arduino Uno
I keep receiving the following error in myATTiny85-Slave code below:

> sketch\_mar12a.ino: In function 'void setup()':
>
> sketch\_mar12a:19: error: 'class USI\_TWI\_S' has no member named 'onRequest'

I have downloaded **TinyWireS** and *TinyWireS.h* clearly has a public function **onRequest**. I opened the .ZIP file (downloaded from https://github.com/rambo/TinyWire) and drag-dropped TinyWireS folder into the Arduino libraries folder. This is how I install ALL libraries.

**I am using Arduino 1.0.6**

What am I doing wrong?

## ATTiny85-Slave Code:

```
#include "TinyWireS.h"                  // wrapper class for I2C slave routines
#define I2C_SLAVE_ADDR  0x26            // i2c slave address (38)

byte t=10;

void setup()
{
   TinyWireS.begin(I2C_SLAVE_ADDR);      // init I2C Slave mode
   TinyWireS.onRequest(requestEvent);
}

void loop()
{
}

void requestEvent()
{
   TinyWireS.send(t);
}

```

## Arduino Uno-Master Code:

```
 #include <Wire.h>
 #define I2C_SLAVE_ADDR  0x26            // i2c slave address (38)

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

 void loop()
 {
      byte num;

     // read 1 byte, from address 0x26
     Wire.requestFrom(I2C_SLAVE_ADDR, 1);

     while(Wire.available()) {
          num = Wire.read();
     }

     Serial.print("num = ");
     Serial.println(num,DEC);
 }

```

# Answer
> 0 votes
I was able to compile your code "ATTiny85-Slave Code" without problems.

You can try to extract the contents of the ZIP archive (i.e. the library) directly to the directory where your sketch is stored. `#include "TinyWireS.h"` should then pick up that version.

You should also switch on verbose output for the compilation to have a look at the directory in which the code is compiled. Here you would find (at least in my older Arduino IDE version) copies of the included files. (`/tmp/build...` on Linux systems.) You can then make sure the proper version of the files is used.

You can also search your drives for other copies of `TinyWireS.h`.

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


# Question
Title: Regarding the USB port, what is the difference between Uno/Mega and the older boards?
I would like to know what the exact difference is between the Uno and Mega boards and the older boards (Duemilanove, Diecimila, etc.). Why do I need to install a FTDI driver for the older boards, and not for the Uno/Mega boards? I was in a class the other day, using the Nano, and the lecturer recommended the FTDI drivers. The Nano is a newer type board, so why does that require a driver? I've just discovered that the Nano is old tech from 2008, after reading Are there any reasons to pick Nano over Micro?

What is it about the Uno and Mega boards that don't require the FTDI to be separately installed?

I see that the Getting Started w/ Arduino on Mac OS X page states that the older boards use the FTDI chip. Does that imply that the Uno/Mega boards do not? If they do not, then what do they use?

I have a vague notion that some USB sticks, keyboards, mouse and other various USB devices may contain a driver within the circuitry/firmware(?) of the device, which when connected to a PC for the first time, can be used to install the driver without the PC needing to access the web for the driver. Is this what the difference is between the UNO/Mega and the older devices? If so, is it possible to modify, or flash the firmware of the older boards so that they can connect without the need for an FTDI driver?

# Answer
The older Arduino boards used an FTDI FT232R chip to handle the USB port. This chip is a special purpose, USB to serial UART interface.

In the current Arduino boards, the USB to serial conversion is handled by dedicated Atmel Atmega8u2 processor. This is a processor that is similar to the main ATmega328p processor, but the added benefit of having built-in USB capabilities.

So, why the change? Well, first, it's cheaper than the FTDI chip, and second, it can do much more. Being that it's an actual microprocessor, you can actually reprogram this chip to behave like different USB devices. For example, you can reprogram it to make your Arduino look like a keyboard, a joystick, a thumb drive, a MIDI instrument - anything that you can do via USB. The FTDI chip does not have this capability, and so it can only ever look like a serial COM port to your PC.

Why have 2 microprocessors on the Arduino? By having a dedicated processor to handle the USB communication, it keeps the main processor free to run your sketches. Plus, the Arduino team felt that this design keeps the Arduino more "hackable".

Wouldn't it be cheaper to make a board using just the one processor that has built-in USB? Yes! That is exactly what the Arduino Leonardo is. It uses the Atmega32U2, the big brother to the Atmega8U2.
> 4 votes

---
Tags: usb, ftdi
---


title: Ethernet Shield on Arduino Mini

text:
# Question
Title: Ethernet Shield on Arduino Mini
I would like to connect my custom-made Arduino with an Ethernet shield but I'm not so sure I can.

## The problem

My board is using the design from the Arduino Mini which lacks the `ATmega16U2` which does the USB-to-serial conversion and adds the `ICSP` pins. I think you get the point... I have only the `ATmega328P` on the board. Nothing else.

Is it even possible to work my way around it without adding the `ATmega16U2`? I can't find the chip anywhere on Ebay.

# Answer
> 2 votes
You can just connect the pins used on the shield the the corresponding pins on your custom board. Check the Schematic to see what pins are used for what (and which can be left unconnected)

The only thing you need to lookout for is, that the ethernets shield seems to require 3.3v (the shield has it's own 3.3v regulator, so you only need to connect 5v)

That 16u2 doesn't do anything but usb-to-serial. It's not needed for the ethernet shield.

The ISP header is just 5v, GND, and the 3 SPI pins and reset. But those SPI pins are also broken out to the pins 11, 12 and 13.

---
Tags: shields, ethernet, atmega328
---


# Question
Title: What info should I look for when choosing a solid state relay for arduino?
I want to control a phone using an arduino board by connecting each pin of the arduino to a button on the phone using relays to simulate a button being pressed or release by switching a relay (on/off). I am using relays because from what I have seen (Use Arduino to Switch Power On and Off!) relays are controlled swiches and I am using SSR because I want to use the less space possible.

I'm trying to buy a relay at mouser.com but I don't know what are the values I should look for, for those parameters (Control Voltage Range, Load Voltage Rating, Load Current Rating, Input Current).

# Answer
I would tread carefully. A solid-state relay may or may not be suitable for the relatively low-level signals present across the phone buttons. Check the datasheet, buy just one, and try it out.

But do you need to control a physical phone? An Arduino can connect to a standard modem which has inbuilt commands to dial numbers and generally supervise a phone line.
> 1 votes

# Answer
An SSR is not a good choice for your application. The common use of an SSR is for switching on and off an **AC** load. If the data sheet mentions SCR or Triac, then it is meant for only switching AC and will not function for controlling DC. So keep this in mind when looking for components: if it says "24-220 VAC" on the data sheet that does not mean it will work for DC.

A second common use of SSR and microcontrollers is the opto-coupled input type. That input method provides a safe scheme for a low voltage low current control signal to switch a large load.

For a button on a phone, you are switching a near zero current DC load. You should be able to control that with a transistor, but that would require some reverse engineering of how the phone keypads where being scanned. You would need to trace out what the voltage was, how much voltage drop could be accommodated.

A certain easy method is to use a small reed relay. Parts are available that have a coil that only draws ~10 mA so can be driven directly from an output pin. The relays are packaged in a DIP so easy to prototype on a breadboard. Many list the coil resistance and voltage for specs, for example a 5V and 500 ohm resistance coil would draw 10 mA. You will find many for 1 - 2 $US.

When working with a relay, you need to take care of the back EMF (aka flyback voltage) that occurs when you turn off. That is handled with a single diode which you will see in every schematic for driving a relay. For a beginner, an alternate/sure success route is to use a driver chip such as a ULN2003 that will drive inductive loads such as small relays.
> 1 votes

# Answer
If you're only controlling a button, the load current and load voltage are pretty much irrelevant since I'd be surprised if you even used 5% of it's rating in either category. I can't tell you how much you'll need here since I don't know the voltage that the relay will be operated on and the resistance of the path for the load.

What you do need to look at is the voltage and current of the input/control/logic signal. It should allow a 5V control voltage and the current draw for that logic signal should be no more than 40mA, although it's ideal to stick to a lower number (say, 30mA).

However, manually picking out a relay manually isn't ideal for a beginner since it requires a bit of extra components to properly run. A relay module **(Amazon)** allows you just hook up your wires to the jumpers and terminals of the relay module without any extra soldering (as far as I know they aren't breadboard compatible, thus requiring a custom PCB or having it "flop") or parts.
> 0 votes

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


# Question
Title: Can I control my Arduino using just a 2.4GHz Wireless Transceiver and a wireless Xbox 360 controller?
I want to control my Arduino using my wireless Xbox 360 controller. I've been looking up tutorials, and they all seem to recommend using a USB shield and the Xbox 360 wireless receiver.

I don't own either of those things, but I do own a 2.4 GHz wireless transceiver. Can I use it to listen to what buttons are being pressed on the controller? For example, if I press the A button on the controller, can I make an LED turn on?

# Answer
Short answer is no, unless you have the machine and tools to do reverse engineering on the xbox controller proprietary 2.4Ghz protocol and you must have xbox 360 itself to see what goes on between Xbox 360 and the xBox controller. The time and money spent on these tools(hardware and software) aren't worth it.

The easiest way to do this is to buy the xbox controller receiver, Arduino USB shield and you can easily use your xbox 360 controller with your Arduino.
> 3 votes

# Answer
I don't know much about the engineering that goes into these kind of radios, but just being 2.4Ghz does not make them potentially compatible. xbox 360 controllers coexist with wifi and bluetooth without interfering, but they are all in the 2.4Ghz spectrum.

The xbox 360 controllers have some kind of proprietary frequency hopping system to avoid interference that you would first have find and reverse engineer before you could even get to the part about decoding the data, and your 2.4Ghz receiver probably can't match the 360 controllers even if you did know the pattern.

I'm relativly confident that it is practically impossible for that receiver to read 360 controller signals.
> 2 votes

# Answer
From the hardware side it should be possible but from the software it may not be easy.

Unless you find some documentation on the protocol that is used for communication between controller and receiver, you will need to decode the protocol (handshaking, commands, idle signals etc.) yourself. Depending on the complexity of the protocol that could be rather frustrating.

I would recommend to do some research on the Internet first and see if there is material describing the protocol so you don't have to start from scratch.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to dynamically switch between between 2 objects?
I have a 40x4 LCD which internally consists of 2 40x2 LCDs. To control this LCD I have to create 2 `LiquidCrystal` objects and than later on in code decide which one to use depending on which of the 4 lines I want to change.

Due to the size of my project, I split all the LCD handling off to a separate class. To make my code as readable and easy as possible, I want to create a member method of this class, to which I can just pass line number 1-4, and have this method take care of deciding which `LiquidCrystal` object to use.

LCDController.h:

```
#include <LiquidCrystal.h>
class LCDControllerClass
{
 protected:

 public:
        void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);
 private:
   void _UpdateLCD(int _iLine, int _iPosition, String _strText, int _iFieldLength);
   LiquidCrystal* _Clcd1;
   LiquidCrystal* _Clcd2;
};
extern LCDControllerClass LCDController;

```

My 2 `LiquidCrystal` objects are initialized in my main .ino file like so (before the `setup()` loop) :

```
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

```

These two objects are then passed as pointers to my `LCDControllerClass` like so:

```
LCDController.init(&lcd, &lcd2);

```

The `init()` member method of my `LCDControllerClass` then puts these pointers in private variables like so:

```
void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1->begin(40, 2);
   _Clcd1->clear();

   _Clcd2 = Clcd2;
   _Clcd2->begin(40, 2);
   _Clcd2->clear();
}

```

Then I have another private member method which should take care of updating the correct LCD object:

```
void LCDControllerClass::_UpdateLCD(int _iLine, int _iPosition, String _strText, int _iFieldLength)
{
   LiquidCrystal* CActiveLCD;
   if (_iLine > 2)
   {
      //DisplayLine is higher than 2, this means we need to update the 2nd LCD
      LiquidCrystal** CActiveLCD = &_Clcd2;
      _iLine = _iLine - 2; //Convert line number to correct line number for 2nd display
   }
   else
   {
      //LiquidCrystal** CActiveLCD = &_Clcd1;
   }
   /* we have to convert this number
      to a real display line (0-1) by substracting 1 again
   */
   _iLine = _iLine - 1;

   CActiveLCD->setCursor(_iPosition, _iLine);
   CActiveLCD->print(_strText);
}

```

Now in this last member mehthor my code goes into the woods for some reason. The LCD is not updated at all and it seems the arduino is freezing as well since I put a small `Serial.print()` test in the main loop and it's not printing anything...

What is the correct way to pass the correct `LiquidCrystal` object to the `CActiveLCD` object?

# Answer
> 2 votes
The problem is that you're declaring multiple pointer variables called `CActiveLCD` in the `_UpdateLCD()` function. You do it once at the start of the function like this:

```
LiquidCrystal* CActiveLCD;

```

You then declare a new and **totally separate** pointer inside the `if` block like this:

```
LiquidCrystal** CActiveLCD = &_Clcd2;

```

This is called masking. The original pointer you declared at the start of the function still exists, but you can't access it because it's temporarily replaced by the new one. When the `if` block finishes, that new pointer is destroyed (it goes out of scope) and the old one is available again.

All of that means you never actually store a value in the original pointer variable. The result is that it contains an arbitrary memory address, so attempting to use it at the end of the function results in undefined behaviour.

When you are assigning to the pointer inside your `if` block, you need to do it like this:

```
CActiveLCD = _Clcd2;

```

Notice that this doesn't declare a new `CActiveLCD` pointer. It simply copies `_Clcd2` into the existing one. Additionally, it's important not to use the address-of operator here (`&`). Adding that in this context gives you a pointer-to-a-pointer. It is technically legitimate in C++, and sometimes does serve a useful purpose, but it's not what you want to do here.

As a side note, when declaring a pointer variable it's usually a good idea to initialise it to something. If you're not assigning an actual address to it right away then initialise it to `0`, like this:

```
LiquidCrystal* CActiveLCD = 0;

```

This means you can check the pointer later on before using it. If it's `0` then you know it's not got a valid address yet so it's not safe to use. This isn't always strictly necessary, but it can help avoid some frustrating bugs.

---
Tags: c++, class
---


# Question
Title: Which Arduino is compatible for atmega164pa
I am working on a project using 5 pins of ADC, 5 pins for PWM, and LCD. I need to use Atmega164pa. I would like to know how I can transfer it to Arduino. Is there any Arduino compatible with this chip?

# Answer
> 1 votes
There is an Arduino core for the '1284A, but it can be adapted to the '164A.

---
Tags: avr
---


# Question
Title: Arduino YUN server crashes after few hours!
I have made a simple server using the YUN SERVER and CLIENT Libraries./ The server runs on a loop and waits for a client to connect. After connection it sends the client a simple message and then disconnects the client.

```
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

#define PORT 6666
YunServer server(PORT);
int pin =13;

void setup() {
  Serial.begin(115200);
  Bridge.begin();
  server.noListenOnLocalhost();
  server.begin();
}
void loop() {
  YunClient client = server.accept();
  if(client.connected())
  {
    digitalWrite(pin,HIGH);
    //startup
    startup_msg(client);
  }
  else
    digitalWrite(pin,LOW);
    delay(500);
}
void startup_msg(YunClient client)
{
    client.print("SAndTerm");
    client.stop();
}

```

Well this code runs smoothly for few hours. But after that, it stops responding to any client request. I guess the server crashes. I have to restart the YUN to get it working again.

Is there anyway I can run this without it getting to crash? Well I want it to be running just like a normal server would.

# Answer
> 0 votes
Updating your YUN might solve this problem. It is recommended to update it after you buy it because they usually come with old firmware. Make sure its up to date. Here a link on how to do this

Another thing to try is to add `delay(50);` at the end of the `loop()` function. It prevents the processor from doing lots of work.

---
Tags: arduino-yun, web-server
---


# Question
Title: What happens if an interrupt is triggered while sending data via serial?
I would like to use an inertial sensor to measure acceleration and send the results to an Android app using a serial communication with a **bluetooth Mate Gold** module. The sensor provides a data ready interrupt which notifies **Arduino-Mega** that a new value is stored in a register of the module. The output data rate can be modified during the configuration of the sensor. I want the information to be sent at a 10 Hz rate to the bluetooth module.

Is an interrupt at 400Hz capable of compromising the integrity of a 50 bytes long message sent at 10 Hz with a baudrate of 9600? If yes, which approach would you recommend to correctly send the data?

**Edit**: I'm using the following formula to compute the amount of time required to send N chars.

```
bytes x bits_per_character / bits_per_second
N x (8+2) / 9600 = N/960 secs

```

For N = 52:

```
52/960 = 0.054 secs = 54 ms

```

So theoretically, I can send a 54 char-long message at 18Hz with a baudrate of 9600.

**Edit2** I can use the hardware serial or the Software Serial interface.

# Answer
> 5 votes
If you are on the ardruino platform, and are using the hardware serial port, you basically don't have to do anything.

The `Serial` library interface already uses a outgoing data-buffer (it's varies between versions, 1.5.5 has it set to 64 bytes. The arduino people keep changing it's size for no reason), where the call to `Serial.print()` or `Serial.write()` only places the bytes in question into the outgoing buffer, and the buffer is then emptied asynchronously in the background by the TX-ready (`UDRE`) interrupt (which is then disabled when the buffer is emptied).

Basically, all you have to do is ensure that you're not placing data into the transmit buffer from both an interrupt and the main `loop()`, because it's then possible for the message from the interrupt to be inserted into the middle of the message from the main loop thread.

This can be easily enough done by either guarding the call to `Serial.print()` with `cli()` `sei()` interrupt guards in the main `loop()` section (or the useless arduino analog: `noInterrupts()` and `interrupts()`, which are just named proxies for `cli()` `sei()`, which exists for no good reason), or simply not printing from an interrupt (which is a good idea anyways, string formatting can be slow).

# Answer
> 2 votes
You want to send a 50 byte (or 52 byte?) sequence every 100 ms (10 Hz).

For hardware serial, that will go into a buffer which is emptied via serial interrupts; it should be emptied well before the next 100 ms tic (as you have calculated).

You will get about 40 sensor interrupts during that 100 ms. With hardware serial, that need not be a problem - **so long as you don't send bytes from within a sensor interrupt**. If your sensor interrupt just accumulates results and the main loop (non-interrupt) uses those results to periodically send the 50 byte message, you should be good.

Suppose you were averaging each of the sensor readings. In the sensor interrupt you might add 1 to the count and add the reading to a sum value. In the main loop, test if it has it has been 100 msec since the last send, and if so turn off interrupts, divide the sum by the count and store that average in a new variable, zero the sum and count, turn on interrupts. Then use the computed average to format and send the 50 byte package.

That's just an example. The main thing is to make the sensor interrupt quick and simple; and to format and send the packet in the main loop (inhibiting interrupts temporarily while fetching and clearing the variables which get updated during the sensor interrupt).

Be sure to use "volatile" for the variables used by both the sensor interrupt and the main loop.

The serial should take care of itself if you use hardware serial, and might even be OK for software serial. In the latter case, a sensor interrupt in the middle of sending the bits of a single character/byte would mess up the bit timing, but software serial should inhibit interrupts during that time - so your sensor interrupt might be delayed up to a millisecond.

# Answer
> 1 votes
What you are looking for is a way to safely interleave transmitting characters while at same time responding to the interrupts. You can wrap the sending of bytes with

```
noInterrupts();
swSerial.write("somethinglongyaddayadda"); // takes 50-60 ms
interrupts();

```

That will protect the write() operation from being interrupted and ruined by you sensor interrupt handler. But as you note, that will block the ability to process the the sensor every 2.5 ms. During the noInterrupts() period you would miss readings.

To achieve the interleave of both operations, you should transmit the message one character at a time. Implement a transmit queue to hold the outbound string. When it has characters, send them 1 at a time, wrapping each interrupt protection:

```
...inside loop...
if(txQueue is not empty) {
  // do not need noInterrupts() or cli() as these are inside write();
  swSerial.write(one character from Q); // takes ~1 ms
  txPointerHead += 1;
}
// at this point the interrupts are enabled
// and the sensor will be processed if available
// if the interrupt occurred in the middle of the above,
// the level is still set and the interrupt handler will be invoked

```

The 1 ms is ideal and not accounting for overhead, but it is unlikely the 1 character write time could stretch out to 2.5 ms. As long as the write time stays under 2.5 ms, you will never drop a sensor reading.

Note that this interleave means that the characters will have larger inter-character delay. The serial ports will not care about that. But if the processing of the sensor data takes too much time, you will not be able to keep up with your 10 messages per second goal.

Some options I see to improve:

1. Use a higher baud rate. The baudrate of the serial port is not related to the bluetooth data rate, so you might as well use the 115.2k. That will reduce the blocking time. The baud rate doesn't even need to be the same on both ends. The BT module isn't a simple modem; it is packetizing characters wrapping them in encryption and transmitting. The receiver unbundles the packets and pushes out its serial port at the receivers baud rate.
2. Use hardware serial. Using a hardware serial port greatly reduces the time because all write() does is put one character into a register. The time for that is microsecond domain. After the byte is put in the transmit register, the UART handles the clocking of the bits so the microcontroller is free to do other tasks.

---
Tags: serial, arduino-mega, sensors, interrupt
---


# Question
Title: "write" function in sd card is not working
I have recently started working with arduino UNO and the "write" function in sd Card library is not working. Below is my code. I have tried with "println" which is working fine. Any help regarding this is welcome.

```
void loop()
{
     byte b=10;
     File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile)
    {
        dataFile.write(b);
     }
}

```

# Answer
The problem is that `print()` and `write()` behave differently when you give them numerical data, such as a byte.

When you pass your byte to `print()`, it converts it to text which is convenient for humans to read. For example:

```
byte b = 10;
dataFile.print(b);

```

This will result in the following ASCII characters being written to the file:

```
10

```

That's actually two bytes: one byte with the value 49, which represents ASCII character `1`, followed by a byte with the value 48 representing character `0`.

However, `write()` does **not** convert numbers into text. It writes them in their raw binary form. For example:

```
byte b = 10;
dataFile.write(b);

```

When you do this, it doesn't write a "1" and a "0" to the file. It literally writes a binary byte with the value 10. When you try to open this as a text file, your computer interprets that byte as a single ASCII character. It so happens that ASCII value 10 is the newline character, meaning your file basically contains a blank line.

For comparison, try this instead:

```
byte b = 65;
dataFile.write(b);

```

ASCII value 65 corresponds to the letter `A` (uppercase), so that's what you should see in the file.

The `write()` functions are useful for writing raw data to file in the most efficient form for another machine to read (as opposed to being human-readable). This is why they allow you to write arrays -- it acts like one big block of raw data with a fixed format.

In your case, `print()` is more appropriate. That means for outputting arrays of numbers, you will need to use loops. That functionality isn't built-in to the `print()` functions because different projects might need different formatting. For example, some people might want one number per line, whereas others might want numbers separated by commas, and so on.
> 0 votes

# Answer
It is typical of file devices that an output file must be closed when the application is through writing to it - `datafile.close()`, using your variable names. Their drivers or libraries typically buffer output data in memory and may not write it to the device until the buffer fills or the application flushes the buffers or closes the file.

See the read/write SD card example at the Arduino site. Especially note the uses of the calls to:

```
begin
open
print or write, ...
close

```

Failing to close an output fail might leave unwritten data in memory buffers rather than flushing the last few bytes (**all** of the data, in the case of your one-byte-write example).

It is also possible that there is another fault - incorrect mapping of I/O pins to the card reader/writer, incorrect wiring, faulty device or card, but I think the programming sequence is the most likely culprit.
> 0 votes

---
Tags: arduino-uno, sd-card
---


title: arduino wifi shield not present error

text:
# Question
Title: arduino wifi shield not present error
I'm using an HLK-RM04 WIFI shield and arduino uno R3 board. whenever I mount my shield on the uno board and connect it to the pc using a usb only the power led(red) of my wifi shield glows. I tried to upload the example code on wifi(provided by arduino)but whenever I run the code it shows "wifi shield not present". Looking into the previous discussions on this website I even tried to connect my arduino with usb+9v supply. In that case my trackpad of the laptop ceases to work. whenever I power my system(arduino+shield) using a 9v external supply all the 3 leds(power,link,wan led) on my wifi shield glow but still the same error of "wifi shield not present" persists.

What is going wrong?

Has anyone configured an HLK-rm04 wifi shield with uno r3 before?

Thanks

# Answer
> 0 votes
I DON'T have experience with the shield you are mentioning, but it sounds to me that no data is being sent from the WiFi shield to the Arduino. I suggest you do a bit of debugging with:

1) Print Statements 2) A multimeter (better yet, an oscilloscope) 3) Check that the pins you are connecting the shield to are not blown

# Answer
> 0 votes
Might be because of a non-compatible version of the Arduino IDE? (latest version isn't always the fittest, apparently).

I found evidence for this weird behavior in various forums around the web - even when using the Uno R3 board with its official WiFi shield, I had to go back to version 1.0.3 of the Arduino IDE (and to flush its compatible firmware version for the WiFi shield) in order to get the sample code to work. Later versions just didn't work!

---
Tags: wifi
---


# Question
Title: Can anyone suggest me a software timer library that does not use polling but timer ISR instead?
There are many software timer libraries available in Arduino.
A library called SimpleTimer http://playground.arduino.cc/Code/SimpleTimer is really good with many functions, but it uses polling.
If anyone is familiar with a really good library that uses Timer ISR of Atmega instead of polling, please suggest me as i am using ultrasonic sensors and i can't afford polling.

# Answer
> 1 votes
Yeah, I have the same problem. The only solution I found is to rewrite a lot of the code. Still ongoing, though.

For you, Timer1 is probably the best candidate, unless you have already some use for it, like in my case.

A quick hack is to free Timer0: it is currently (ab)used by the wire library, which provides the typical arduino timing. But you can remove/rename the file wiring.cpp to something that will not be identified as source (ex: wiring.\_cpp) and comment out the init() function call from the main() function in the main.c file.

Normal Arduino stile time functions will not work, of course.

Unfortunatelly Arduino SW really lacks the structured design that would allow it to be useful in more complex cases and most of the libraries make exclusive use of resources that could be shared, timer being the most prominent example.

Port ISRs is another.

Btw, if you happen to use a SW serial library, it's already game over, as it busy loops inbetween bits, in interrupt context (!), rather than using a timer.

---
Tags: library, timers
---