message:
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();

    }

body:
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.


sender: user

message:
Error with Arduino/Processing Serial Communication

I am relatively new to both Arduino and Processing and I have been working on a code that utilizes serial communication between the two. My Arduino code is reading and printing values from a piezo sensor and then sending the values to Processing, which sketches certain shapes based on the values. The code has worked previously, but for some reason it is no longer working. Everything compiles, but when I run the Processing code the sketch window is empty and remains empty. A few times the "error, disabling serialEvent()" showed up, but I just unplugged my Arduino board, closed out the programs, and restarted everything. The error no longer shows up, but my Processing sketch is still not displaying on the screen. Can someone please let me know what is wrong with my code? I really appreciate the help.

**Arduino Code:**

    int ledPin = 13;
    int knockSensor = A0;
    byte val = 0;
    int statePin = LOW;
    int THRESHOLD = 5;
    int sensorReading = 0;

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

    void loop() {
     sensorReading = analogRead(knockSensor);

      if(sensorReading > 0){
       Serial.println(sensorReading, DEC);
       delay(100);
      }
    }

**Processing Code:**

    import processing.serial.*;

    Serial port;

    int centerX = 550;
    int centerY = 400;

    float val;
    float ellipseX;
    float ellipseY;
    float ellipseW;
    float ellipseH;
    float ellipseXX;
    float ellipseYY;
    float ellipseWW;
    float ellipseHH;
    float lineX;
    float lineY;
    float lineXX;
    float lineYY;

    void setup(){
      background(255);
      size(1100,800);
      frameRate(10);
      smooth();

      String portname = "/dev/tty.usbmodem1411";

      //String portname = Serial.list()[0];
      port = new Serial(this, portname, 9600);
      println(Serial.list());
      //port.bufferUntil('\n');
    }

    void drawEllipse(float val)
    {
      if(val > 0 && val < 50)
      {
        ellipseX = random(540,560);
        ellipseY = random(390,410);
        ellipseW = val + 10;
        ellipseH = val + 10;

        stroke(0);
        fill(random(255), random(200,255));
      }
    }

    void drawLines(float val)
    {
      if(val > 50 && val < 70)
      {
        lineX = random(500, 600);
        lineY = random(360, 440);
        lineXX = random(500, 600);
        lineYY = random(360, 440);

        stroke(0);
      }
    }

    void drawEllipse2(float val)
    {
      if(val > 70 && val < 120)
      {
        ellipseXX = random(460, 640);
        ellipseYY = random(330, 470);
        ellipseWW = val + random(20);
        ellipseHH = val + 10;

        stroke(0);
        fill(random(50, 100), random(50, 100), random(50, 100), random(220, 255));
      }
    }

    void serialEvent(Serial port)
    {
      String inString = port.readStringUntil('\n');

      if (inString != null)
      {
          val = Float.parseFloat(inString);
      }

      drawEllipse(val);
      drawLines(val);
      drawEllipse2(val);
      println(val);
    }

sender: assistant

body:
It seems like you need to do some basic debugging:

 - Put a println() in setup. If this does not appear, you have a major problem talking to the Arduino board.
 - Put a println() statement in the loop() that prints out the sensor reading. That should separate hardware problems from software defects.


message:
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. <strike>The Nano is a newer type board, so why does that require a driver?</strike> I've just discovered that the Nano is old tech from 2008, after reading [Are there any reasons to pick Nano over Micro?][1]

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][2] 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?

  [1]: https://arduino.stackexchange.com/questions/4480/are-there-any-reasons-to-pick-nano-over-micro/4489#4489
  [2]: http://www.arduino.cc/en/Guide/MacOSX

body:
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](http://www.atmel.com/devices/ATMEGA8U2.aspx) 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.


message:
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](https://i.stack.imgur.com/qhGKS.jpg) and the [Xbox 360 wireless receiver](https://i.stack.imgur.com/6l1Ys.jpg).

I don't own either of those things, but I do own a [2.4 GHz wireless transceiver](http://www.amazon.com/nRF24L01-Wireless-Transceiver-Arduino-Compatible/dp/B00E594ZX0). 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?

body:
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.


body:
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.


body:
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.


message:
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.

body:
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][1]

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.

  [1]: http://arduino.cc/en/Tutorial/YunSysupgrade


message:
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.

body:
You can just connect the pins used on the shield the the corresponding pins on your custom board. Check the [Schematic](http://arduino.cc/en/uploads/Main/arduino-ethernet-shield-06-schematic.pdf) to see what pins are used for what (and which can be left unconnected)

<strike>The only thing you need to lookout for is, that the ethernets shield seems to require 3.3v</strike> (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.


message:
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?

body:
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.


message:
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?

body: There is an Arduino core for the '1284A, but it can be adapted to the '164A.


message:
Possible to store variables directly in EEPROM?

Is it possible to store a variable directly in EEPROM and retrieve it *without* needing to use a library?

I'm building a project that can change the colour of an RGB LED and I want to store the colour in a non-volatile memory space, but I was wondering if I could avoid using one of the EEPROM libraries and have a global variable stored in nonvolatile memory, but still accessed directly, without needing to call a function.

body:
Writing and reading EEPROM is possible to do without a library. Take a look at the [datasheet of the ATmega328P][1] to find an example: On page 25 / 26 there are example codes for reading and writing both in assembler and C. They do wrap it in a function but as I said in a comment if you only have place in your code where you would like to access EEPROM you can put the code there without duplication. These functions write and read one byte at a time, so if you want to store larger datatypes (a 16-bit integer for example) you already need to call the routines more than once.

Note that the EEPROM has a limited life cycle of at least 100,000 write/erase cycles (cells must be erased before they can be written, reads are unlimited) and it is considerably slower than SRAM (typ. 3.3 ms for writing a byte). You also need to make sure no interrupts interfere with the write process.

However, in the sense of the question it seems this is not what you want: You cannot just create a global variable and have it magically being written to EEPROM.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf "datasheet of the ATmega 328p"


body:
EEPROM can store one byte at a location. To store Integer variable, it requires two consecutive location. For Double, it requires four consecutive memory location. I have written function to store and read, int & double to and from built-in EEPROM. As per your question, you can modify it as per your need.

> Actually this answer was copied from [another thread][1].

    /*
      StackExchange Question: "How to Store 2 analogRead values and read using EEPROM for Arduino uno?"
      Question Id: 15910 (https://arduino.stackexchange.com/questions/15910/how-to-store-2-analogread-values-and-read-using-eeprom-for-arduino-uno)
      Author: Anurag S. Vasanwala (AnuragVasanwala@gmail.com)

      Tested on Arduino Version 1.6.7

      Description:  This sketch helps to store and read, Integer & Double to and from built-in EEPROM.
      Objectives:
        + Write Integer @ Specified Address (Fn: EEPROM_Write_Int)
          + Conversion from Integer to Byte Array
          + Store Bytes
        + Read Integer from Specified Address (Fn: EEPROM_Read_Int)
          + Read Bytes
          + Conversion from Byte Array to Integer
        + Write Double @ Specified Address (Fn: EEPROM_Write_Double)
          + Conversion from Double to Byte Array
          + Store Bytes
        + Read Double from Specified Address (Fn: EEPROM_Read_Double)
          + Read Bytes
          + Conversion from Byte Array to Double
     */
    #include <EEPROM.h>

    // MACRO : Combines FROM_BYTES into TO_OBJECT of datatype "DATATYPE"
    #define CombineBytes(FROM_BYTES, DATATYPE, TO_OBJECT) \
      TO_OBJECT = *((DATATYPE *)FROM_BYTES);

    // MACRO : Splits FROM_DATA of DATATYPE into equivalent byte array TO_BYTES
    #define GetBytes(FROM_DATA, DATATYPE, TO_BYTES) \
      *((DATATYPE *)TO_BYTES) = FROM_DATA;

    // Writes Integer's equivalent bytes to Address and Address + 1
    void EEPROM_Write_Int(unsigned int Address, int Data)
    {
      // Get the size of datatype to write number of bytes
      const byte SizeOf_DataType = sizeof(int);

      // Create tem buffer to get Bytes of Datatype
      byte Temp_Buffer[SizeOf_DataType];

      // Call macro to store byte array into Temp_Buffer from Data
      GetBytes(Data, int, Temp_Buffer);

      // Write number of bytes to memory location specified in Address and so on
      for(byte Index = 0; Index < SizeOf_DataType; Index++)
      {
        EEPROM.write(Address + Index, Temp_Buffer[Index]);
      }
    }

    // Reads two bytes from Address and Address + 1 and returns equivalent int
    int EEPROM_Read_Int(unsigned int Address)
    {
      // Get the size of datatype to write number of bytes
      const byte SizeOf_DataType = sizeof(int);

      // Create tem buffer to get Bytes of Datatype
      byte Temp_Buffer[SizeOf_DataType];

      int Result;

      // Read number of bytes from memory location
      for(byte Index = 0; Index < SizeOf_DataType; Index++)
      {
        Temp_Buffer[Index] = EEPROM.read(Address + Index);
      }

      // Call macro to combine bytes into equivalent to int
      CombineBytes(Temp_Buffer, int, Result);

      return Result;
    }

    // Writes Double's equivalent bytes to Address, Address + 1, Address + 2 and Address + 3
    void EEPROM_Write_Double(unsigned int Address, double Data)
    {
      // Get the size of datatype to write number of bytes
      const byte SizeOf_DataType = sizeof(double);

      // Create tem buffer to get Bytes of Datatype
      byte Temp_Buffer[SizeOf_DataType];

      // Call macro to store byte array into Temp_Buffer from Data
      GetBytes(Data, double, Temp_Buffer);

      // Write number of bytes to memory location specified in Address and so on
      for(byte Index = 0; Index < SizeOf_DataType; Index++)
      {
        EEPROM.write(Address + Index, Temp_Buffer[Index]);
      }
    }

    // Reads four bytes from Address, Address + 1, Address + 2 and Address + 3 and returns equivalent double
    double EEPROM_Read_Double(unsigned int Address)
    {
      // Get the size of datatype to write number of bytes
      const byte SizeOf_DataType = sizeof(double);

      // Create tem buffer to get Bytes of Datatype
      byte Temp_Buffer[SizeOf_DataType];

      double Result;

      // Read number of bytes from memory location
      for(byte Index = 0; Index < SizeOf_DataType; Index++)
      {
        Temp_Buffer[Index] = EEPROM.read(Address + Index);
      }

      // Call macro to combine bytes into equivalent to double
      CombineBytes(Temp_Buffer, double, Result);

      return Result;
    }

    void setup()
    {
      // Initialize Serial @ 9600 baud
      Serial.begin(9600);

      // Print size of datatype just for reference
      /* Serial.print("Size of byte = ");
      Serial.println(sizeof(byte));
      Serial.print("Size of int = ");
      Serial.println(sizeof(int));
      Serial.print("Size of float = ");
      Serial.println(sizeof(float));
      Serial.print("Size of double = ");
      Serial.println(sizeof(double)); */

      int myInt1 = -290;
      int myInt2;
      double myDbl1 = 23.41;
      double myDbl2;

      // Write myInt1 @ 100 memory location; It requires 2 consequtive memory location to store integer
      EEPROM_Write_Int(100, myInt1);

      // Read integer located @ memory location 100 and assign it to myInt2
      myInt2 = EEPROM_Read_Int(100);
      Serial.println(myInt2);

      // Write myInt1 @ 200 memory location; it requires 4 consequtive memory location to store double
      EEPROM_Write_Double(200, myDbl1);

      // Read double located @ memory location 200 and assign it to myDbl2
      myDbl2 = EEPROM_Read_Double(200);
      Serial.println(myDbl2);
    }

    void loop()
    {

    }

> This code is successfully tested on Arduino Version "1.6.7".

  [1]: https://arduino.stackexchange.com/questions/15910/how-to-store-2-analogread-values-and-read-using-eeprom-for-arduino-uno/20401#20401


body:
You can have a global variable in EEPROM if the EEPROM is [memory
mapped](https://en.wikipedia.org/wiki/Memory-mapped_I/O). Memory-mapping
the EEPROM [is possible on ATxmega
chips](http://atmel.force.com/support/articles/en_US/FAQ/Memory-mapping-of-EEPROM-in-XMEGA-devices).
Notice that writes go to a temporary buffer, not the EEPROM itself,
until you explicitly issue a write command.

Most Arduinos, however, use ATmega chips, which do not have this
feature. I am not aware of any xmega-based Arduino or clone.


message:
EEPROM endurance and page size

I would like to estimate the effective (minimum) endurance of the EEPROM of the Arduino in terms of single-byte writes.

The [datasheet of the ATmega][1] used on many Arduino boards says (page 20):

> The ATmega48A/PA/88A/PA/168A/PA/328/P contains 256/512/512/1Kbytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles.

[1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf "datasheet of the ATmega 328p"

Consider the ATmega328P with 1 kB of EEPROM. As I can write single bytes, if I loop through the EEPROM, writing every byte position the same number of times, that would make 1024 * 100,000 writes (assuming the nominal endurance).

But as far as I know not single bytes are erased before a write, but pages / cells. On page 285 / table 28.12 of the datasheet, the page size is specified to be 4 bytes. Does that mean the specified minimum endurance amounts to 1024 * 100,000 / 4 single-byte writes?

body:
## Testing a single byte write

I ran some test code overnight to try to get to the bottom of this. Somewhat surprisingly perhaps, I got up to over 11 million writes before a read-back failed:

    Current count = 11514199
    Writes per minute: 17550
    ....................
    Current count = 11538199
    Writes per minute: 17550
    ....................
    Current count = 11562199
    Writes per minute: 17549
    ...................
    Failed readback!
    Expected: FF
    Got: 7F
    Current count = 11585314
    Halted.

So, 11.5 M writes. Still, as pointed out on the [AVR Freaks thread](http://www.avrfreaks.net/comment/529996#comment-529996), the guarantee of 100,000 writes to EEPROM gives you a data retention time of 20 years. Possibly if you exceed that limit, the data retention time will go down. It isn't particularly practical for me to test whether or not the EEPROM will still be valid after 20 years. ;)

Interestingly, the next day (as I write this) the EEPROM seems to have recovered and is now still writing and reading back OK. So it would appear that after 11 M writes you may *sometimes* get a bad read-back.

On the AVR Freaks thread they seemed to get somewhere between 5 M and 8 M writes before failure.

---

A number of hours later (2.4 hours), the same byte failed again, after a further 2,559,219 writes!

    Current count = 14033314
    Writes per minute: 17549
    ....................
    Current count = 14057314
    Writes per minute: 17549
    ....................
    Current count = 14081314
    Writes per minute: 17549
    ....................
    Current count = 14105314
    Writes per minute: 17549
    ....................
    Current count = 14129314
    Writes per minute: 17549
    ............
    Failed readback!
    Expected: FF
    Got: 7F
    Current count = 14144533
    Halted.

---

Somewhat more quickly the third failure after a further 149,703 writes:

    Current count = 14312533
    Writes per minute: 17550
    ....
    Failed readback!
    Expected: FF
    Got: 7F
    Current count = 14318236
    Halted.

---

And another failure (in 2.3 minutes) after a further 41757 writes:

    Starting.
    Current count = 14318236
    Waiting for pin 2 to go LOW.
    Started.
    ....................
    Current count = 14342236
    Writes per minute: 17551
    ..............
    Failed readback!
    Expected: FF
    Got: 7F
    Current count = 14359993
    Halted.

---

## Testing the adjacent byte

Now that I got a failure fairly quickly on the somewhat overworked byte, I adjusted the code to write to the next one up (1021) which would be in the same 4-byte "page".

Four hours later, the adjacent byte has been written to 4.36 million times without any errors, so this would appear to support the idea that each byte of EEPROM can be written individually without affecting its neighbours.

**Next morning**

The adjacent byte (address 1021) finally failed after 12,161,565 writes. So the proposition that each byte can be individually addressed, and has an individual lifetime, seems to be supported.

    Current count = 12120000
    Writes per minute: 17562
    ....................
    Current count = 12144000
    Writes per minute: 17562
    ..............
    Failed readback!
    Expected: FF
    Got: 7F
    Current count = 12161565
    Halted.

---

<!-- language-all: lang-C++ -->

## Code

### Main sketch

    // EEPROM tester

    // Author: Nick Gammon
    // Date: 22 August 2015

    // Connect a jumper from GND to pin D2 when ready to run.
    // Remove the jumper for a clean wrap-up (saving the current count into EEPROM)

    // Single flash, repeated every half second: ready to go
    // Two flashes, stopped on request
    // Three flashes, error
    // Occasional flash: working

    #include <EEPROMAnything.h>
    #include <EEPROM.h>

    const unsigned int WRITE_COUNT_ADDRESS = 1010;
    const unsigned int TEST_ADDRESS = 1020;
    const unsigned int ITERATIONS = 200;
    const unsigned long MAX_DOTS = 20;
    const byte TESTS [] = { 0x55, 0x00, 0xFF, 0x66, 0xAA, 0x11 };
    const byte ACTIVATE_PIN = 2;
    const byte LED = 13;

    unsigned long dots = 0;
    unsigned long writeCount;
    unsigned long startTime;
    unsigned long initialCount;

    void showCount ()
      {
      Serial.print ("Current count = ");
      Serial.println (writeCount);
      } // end of showCount

    // flash the LED the required number of times
    void flashLED (const int times,
                   const unsigned long interval = 100,
                   const unsigned long delayTime = 500)
      {
      for (int i = 0; i < times; i++)
        {
        digitalWrite (LED, HIGH);
        delay (interval);
        digitalWrite (LED, LOW);
        delay (interval);
        }  // end of for each iteration
      delay (delayTime);  // delay between iterations
      }  // end of flashLED

    // check our memory agrees with what we expect
    void checkMemory (const byte target)
      {
      byte found = EEPROM.read (TEST_ADDRESS);
      if (found != target)
        {
        Serial.println ();
        Serial.println ("Failed readback!");
        Serial.print ("Expected: ");
        Serial.println ((int) target, HEX);
        Serial.print ("Got: ");
        Serial.println ((int) found, HEX);
        showCount ();
        EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
        Serial.print ("Halted.");
        Serial.flush ();
        while (true)
          flashLED (3);  // three flashes
        }
      }   // end of checkMemory

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

      // get write count from previous run
      EEPROM_readAnything (WRITE_COUNT_ADDRESS, writeCount);
      initialCount = writeCount;

      // if all 1 bits, variable was never initialized
      if (writeCount == 0xFFFFFFFF)
        writeCount = 0;

      // tell them we are starting
      Serial.println ("Starting.");
      pinMode (2, INPUT_PULLUP);
      pinMode (LED, OUTPUT);
      showCount ();

      // wait for them to unplug pin 2
      Serial.println ("Waiting for pin 2 to go LOW.");
      while (digitalRead (ACTIVATE_PIN) == HIGH)
        flashLED (1);  // one flash

      Serial.println ("Started.");
      startTime = millis ();
      }  // end of setup

    void loop ()
      {

      // write to EEPROM, checking each write
      for (unsigned int i = 0; i < ITERATIONS; i++)
        {
        for (unsigned int j = 0; j < sizeof (TESTS); j++)
          {
          EEPROM.write (TEST_ADDRESS, TESTS [j]);
          writeCount++;
          checkMemory (TESTS [j]);
          }  // end of doing each test pattern
        }  // end of loop of x ITERATIONS

      // save the current write count so we can pick up the count next time
      EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
      Serial.print (".");
      dots++;

      // confirming we are working
      flashLED (1, 10, 0);  // flash once, for 10 ms, no extra delay

      // newline, show counter
      if (dots >= MAX_DOTS)
        {
        Serial.println ();
        dots = 0;
        showCount ();
        unsigned long writes = writeCount - initialCount;
        unsigned long timeTaken = millis () - startTime;
        float writesPerMinute = float (writes) / float (timeTaken) * 60.0 * 1000.0;
        Serial.print ("Writes per minute: ");
        Serial.println ((int) writesPerMinute);
        }  // end of needing a newline and counter output

      // check if user wants us to stop by disconnecting the jumper from Gnd to D2
      if (digitalRead (ACTIVATE_PIN) == HIGH)
        {
        Serial.println ();
        Serial.println ("Stop request detected.");
        showCount ();
        Serial.print ("Halted.");
        Serial.flush ();
        while (true)
          flashLED (2);  // two flashes
        }
      }  // end of loop

### EEPROMAnything.h

    #include <Arduino.h>  // for type definitions
    #include <EEPROM.h>

    template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
    {
        const byte* p = (const byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         EEPROM.write(ee++, *p++);
        return i;
    }

    template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
    {
        byte* p = (byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         *p++ = EEPROM.read(ee++);
        return i;
    }

---

The code is designed to wait until you connect pin 2 (digital pin 2) to ground before starting. This is to stop it executing immediately after being uploaded, before you start the serial monitor. So, upload the code, open the serial monitor, and then connect Gnd to pin D2, and watch the results.

---

## Error correction

If the concern is that the EEPROM reads may deteriorate, once could use [Reed Solomon](https://en.wikipedia.org/wiki/Reed–Solomon_error_correction) error correction to recover. That is the method used for correcting bad reads on compact disks, and also QR codes. It can recover from a number of errors (you choose the level of error correction you want - the more error correction, the more memory it takes).

My tests so far have shown that failure involves single bits (as did the AVR Freaks tests) so this may well be a way of extending EEPROM life and reliability.

Testing of some Reed Solomon code that I found, would appear to indicate that adding the encoding and decoding would take around 4800 bytes of program memory, plus around 600 bytes of RAM (512 bytes needed for the internal tables, plus some extra work space). In addition you need 256 bytes of RAM for the code block. Those figures could be reduced by using less bits per "symbol". For example, if you stored 4-bit symbols (such as BCD numbers) then the memory requirements would reduce somewhat.


body:
In the arduino forum
http://forum.arduino.cc/index.php?topic=293472.0
someone states that is 1 byte size (each "page") - each write writes and spends a cycle for a single byte.
There it also says that SPI access to eeprom uses a 4 bytes page size.
I did not went further reading since my doubt was same as here, writing a byte to arduino eeprom.


message:
"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);
         }
    }

body:
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][1] 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.

  [1]: http://arduino.cc/en/Tutorial/ReadWrite


body:
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.


message:
16Hertz Uno R3 Board vs Arduino Uno R3 Board

I bought a [16Hertz Uno R3 Board][1]. When I installed the driver and the Arduino IDE,  in the IDE`s menu I saw:

> Tools -> Board -> Arduino Uno

was selected by default which is great, but...

> Tools -> Port -> COM3(Arduino Mega or Mega 2560)

was selected by default which I think might be some kind of misunderstanding...

When I chose:

> Tools -> Board -> Arduino Mega or Mega 2560

On that tools menu appeared new menu "Processor" with two options:

> Tools -> Processor -> ATmega2560 (Mega 2560)

which was selected by default and there was another option

> Tools -> Processor -> ATmega1280

When I restore Tools -> Board settings back to "Arduino Uno" the "Processor" menu with the two options disappeared and Tools -> Port setting did not changed!

If you take my board and look at the Microcontroller there is written:

> ATMEGA328P-PU

Also on that board is written:

> 16HzUNO

I need to know:

 1. What does 16Hz mean? Does it mean the clock or frequency of this
    Microcontroller? I think it does not, if I try to find out details of my Microcontroller on the [rs-online site][2], there is written:

>  ATMEGA328P-PU, 8 bit AVR Microcontroller 20MHz 1 kB, 32 kB Flash, 2
> kB RAM, I2C 28-Pin PDIP

 2. Why was there "COM3(Arduino Mega or Mega 2560)" written on the
    Port's menu?
 3. Is my 16Hz Uno R3 and the Arduino Uno R3 board the same? Which one
    is better? When one of those is better?
 4. Does the standard Arduino Uno R3 board have the same ATMEGA328P-PU
    Microcontroller?

  [1]: http://www.16hertz.com/product/uno-r3-kit-ultimate-arduino-compatible/
  [2]: http://ie.rs-online.com/web/p/microcontrollers/6962260/

body:
1. Every Arduino is using a quartz crystal in order to get the frequency needed. ATmega328 can handle up to 20 MHz

2. ??

3. Yes. You can't run the microcontroller by itself. It has an internal oscillator but none is using it. So basically you will have a 16 MHz crystal.

4. Pretty much the Arduino Uno, Nano, Mini and few others have the ATmega328P.
Note that the `-PU` `-AU` at the end defines the package. So they're the same.

Arduino Mega, Leonardo, Micro, Due use other chips.


body:
You need to have a look at the [Arduino comparison table][1]. This shows that *all* Arduino Uno boards run at 16 MHz. It seems that you have fallen for the marketing on the [page for the Uno kit][2] that you provided.

Also, which version of the IDE are you running? You should upgrade to the latest version, which is currently, at the time of writing, version 1.6.1.

To answer your questions in turn:

 1. "**16Hz**" is the *brand name* and has nothing whatsoever to do
    with the speed, which is actually 16 **Mega** Hertz. "Clock" and
    "Frequency" refer to the same thing. 16 MHz is the clock frequency
    of the board, and is the speed at which the **ATmega328** runs at.
    The RS Online link does indeed state 20 MHz, but that is merely the
    *maximum* speed at which the **ATmega328** can run at. The Uno under clocks it at 16 MHz.
 2. The **Ports** menu will show you a number of possible devices, **Arduino Uno** should be one of them (which is the one you should select) and three items below that will be **Arduino Mega or Mega 2560** (which you should ignore, you do not have a Mega board1). Unfortunately the Arduino site only shows the Mac menu, even on [the Windows guide][3]

 >[![Mac Arduino Tools menu][4]][4]

  which is no help to you, assuming that you are running the Arduino IDE on Windows. You should actually see this in the **Board** menu:

 >[![Windows Arduino Tools Board menu][6]][6]

 and this in the **Port** menu:

 >[![Windows Arduino Tools Port menu][7]][7]

 As you can see, there should be no mention of the microcontroller in the **Port** menu.

 3. The 16Hz branded Uno and the Arduino Uno are to all intents and purposes the same and as I state in the first line, the 16 MHz Uno is *exactly* the same as a regular Uno, it is just marketing.
 4. Both the 16Hz and the Arduino Uno have a **ATmega328** and the Mega board has a **ATmega2560**. Again, check the [Arduino comparison table][8] to see the variety of the boards and their respective microcontrollers.

I hope that answers your questions.

----
1 If you *do* chose the **Arduino Mega or Mega 2560** option, in the **Board** menu, then indeed there will be an additional **Processor** menu. However, this is irrelevant in your case, as you do not have a Mega board, and so you need to chose the Uno in the **Board** menu. If you do so, then the **Processor** menu will disappear, as it is not needed for the Uno.

  [1]: http://arduino.cc/en/Products.Compare
  [2]: https://web.archive.org/web/20150104015236/http://www.16hertz.com/product/uno-r3-kit-ultimate-arduino-compatible/
  [3]: http://www.arduino.cc/en/Guide/Windows#toc7
  [4]: https://i.stack.imgur.com/ikeJV.png
  [6]: https://i.stack.imgur.com/qttd5.png
  [7]: https://i.stack.imgur.com/BrjgA.png
  [8]: http://arduino.cc/en/Products.Compare


body:
Just a theory for 2:

The text that shows up in the Tools > Port list after the COMx

eg `Tools -> Port -> COM3(Arduino Mega or Mega 2560)`

is simply what the IDE thinks the board is based on the USB ID (VID/PID) of the board's USB interface chip. For some clones, this is blank because they don't even use the same chip as an authentic Uno. In your case, I would suspect that they have used the USB chip from a Mega board on your Uno board.

So the IDE thinks a Mega is attached because it is seeing a USB chip from a Mega, even though it is an Uno (clone).


message:
Arduino unstable analog reading when using power supply

As soon as I unplug my Arduino from USB and only use the VIN pin with my 9 V power supply, the analog readings from my Arduino start to get unstable, which means the value fluctuates much more than with USB connected. When I reconnect USB again, the readings are stable again.

I'm trying to build a load scale using a load cell, an INA125P and the Arduino, using this setup here: [Instrument Amplifier Calibration][1].

Therefore I need stable readings. For example, I wrote some code to convert the `analogRead()` value to grams. While USB and VIN (9 V) connected, I get a stable reading of about 8.3 to 8.7 grams when I put a weight of 8.5 grams on the scale. As soon as I unplug USB, the LCD shows values from 7.8 grams up to 9 grams.

Unfortunately, I don't have any other power supply which I could use to test. I've already tried to use a 9 V battery with the same results. Do I maybe need some additional de-coupling capacitors?

  [1]: https://learn.adafruit.com/smart-cocktail-shaker/calibration

body:
I would say that this may be related to the analog reference. Try [AnalogReference][1] and see if it helps.

  [1]: https://www.arduino.cc/en/Reference/AnalogReference


body:
Does your arduino have a switch-mode regulator when converting 9V to 5V? If that's the case, then you must have some voltage ripple on your 5V power line. I'm guessing you are probably using analogRead which uses that 5V reference. If there is a ripple in your reference voltage, you will get a ripple in your readings.

Can you use the internal 1.1V reference of Atmega328p chip? That reference voltage is (as far as I know) the most stable you can provide for ADC.

If that doesn't work, then you need to find a very stable 5V adapter for your 9V sources.


body:
Load cell signals are very small and without proper shielding are be susceptible to noise. The USB power connector is likely earth grounded (the clue was battery operation is noisy, exact opposite of expectations!) I suggest testing this hypothesis:

1. Check with ohm meter if exposed metal on USB connector is connected to earth (chassis on your PC is usually earth connected).
2. Touch an earth grounded conductor to the signal ground of the load cell amplifier and see of the readings become more accurate.

The final solution is to use properly shielded signal wires between the load cell and the amplifier. Also the signal wires between load cell and amplifier should be a 'twisted pair' to further reduce noise.


body:
Without much information (software, schematic, hardware, measurements ...) It is hard to tell.

My guess would be that you used vcc as a dc reference and the circuit draws too much current from the battery than it can deliver so bcc dips, leading to a rise and instability in the reading.

Good luck debugging it.


body: I solved a similar issue by adding a pin from supply to AREF and it's now stable. This fixed a frustrating pH meter issue on my Mega that every time I plugged USB in it would be right, but as soon as I dropped the USB cable it changed the readings.


message:
Ethernet shield not getting IP

I am just running the below DHCPAddressPrinter sketch in Arduino example to setup EthernetShield with MAC and IP

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = {
      0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
    };

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      // this check is only needed on the Leonardo:
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for (;;)
          ;
      }
      // print your local IP address:
      Serial.print("My IP address: ");
      for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
      }
      Serial.println();
    }

    void loop() {

     }

**After uploading the sketch to arduino,below is the output shown in console**

    Sketch uses 13,614 bytes (42%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 539 bytes (26%) of dynamic memory, leaving 1,509 bytes for local variables. Maximum is 2,048 bytes.

**And there is nothing shown in Serial monitor**
This is the image of Ethernetshield's some leds glowing after connecting to Router.
My router is Binatone Wireless ADSL2+ Router.

![enter image description here][1]
![enter image description here][2]

**I checked arp -a**,

    C:\Users\Radhamani>arp -a

    Interface: 192.168.1.6 --- 0x3
      Internet Address      Physical Address      Type
      192.168.1.1           6c-fd-b9-24-c6-fe     dynamic
      192.168.1.255         ff-ff-ff-ff-ff-ff     static
      224.0.0.22            01-00-5e-00-00-16     static
      224.0.0.251           01-00-5e-00-00-fb     static
      224.0.0.252           01-00-5e-00-00-fc     static
      239.255.255.250       01-00-5e-7f-ff-fa     static
      255.255.255.255       ff-ff-ff-ff-ff-ff     static

    Interface: 192.168.198.1 --- 0xe
      Internet Address      Physical Address      Type
      192.168.198.255       ff-ff-ff-ff-ff-ff     static
      224.0.0.22            01-00-5e-00-00-16     static
      224.0.0.251           01-00-5e-00-00-fb     static
      224.0.0.252           01-00-5e-00-00-fc     static
      239.255.255.250       01-00-5e-7f-ff-fa     static

    Interface: 192.168.234.1 --- 0xf
      Internet Address      Physical Address      Type
      192.168.234.255       ff-ff-ff-ff-ff-ff     static
      224.0.0.22            01-00-5e-00-00-16     static
      224.0.0.251           01-00-5e-00-00-fb     static
      224.0.0.252           01-00-5e-00-00-fc     static
      239.255.255.250       01-00-5e-7f-ff-fa     static

**Complete result of ipconfig:**

    Wireless LAN adapter Wi-Fi:
       Connection-specific DNS Suffix  . :
       Link-local IPv6 Address . . . . . : fe80::901:3297:48ad:9e7d%3
       IPv4 Address. . . . . . . . . . . : 192.168.1.6
       Subnet Mask . . . . . . . . . . . : 255.255.255.0
       Default Gateway . . . . . . . . . : 192.168.1.1
    Ethernet adapter VMware Network Adapter VMnet1:
       Connection-specific DNS Suffix  . :
       Link-local IPv6 Address . . . . . : fe80::c954:40b2:c8c1:de0
       IPv4 Address. . . . . . . . . . . : 192.168.198.1
       Subnet Mask . . . . . . . . . . . : 255.255.255.0
       Default Gateway . . . . . . . . . :
    Ethernet adapter VMware Network Adapter VMnet8:
       Connection-specific DNS Suffix  . :
       Link-local IPv6 Address . . . . . : fe80::2837:7e01:c799:d627
       IPv4 Address. . . . . . . . . . . : 192.168.234.1
       Subnet Mask . . . . . . . . . . . : 255.255.255.0
       Default Gateway . . . . . . . . . :

Serial.println in the program is not printing anything.Looks like Ethernet shield is not getting IP.I am not sure where I am wrong.Please help me to fix this issue

  [1]: https://i.stack.imgur.com/Cp90K.jpg
  [2]: https://i.stack.imgur.com/U7mgM.jpg

body:
Based on the image .. i see that the programmer pins at the back of the shield and the arduino aren't connected properly.. That might be the error or at least happened with me.
Apart from that, certain network need to identify the mac address from a look up table and if the shield mac address matches, then only network transactions are allowed.
Also i suggest you to drop the virtual machine mac address and networking protocols and try upon the base OS which you have on your computer.


body:
The SD might need disconnecting. Add below to setup().

    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);

Also check the pin assignment for the W5100 (in the Ethernet library).

Cheers!


body: check the DHCP service of your router is active or not :)


body:
I had the same problem and it had two causes:

1) I couldn't fully insert pins of my shield into the board (ArduinoMega), because if its USB connector. So I connected them with cables. To check for this error, use this code to initialize your Ethernet shield:

       Ethernet.begin(mac, ip);
       if (Ethernet.begin(mac) == 0) {
         Serial.println("Failed to configure Ethernet using DHCP");
         Ethernet.begin(mac, ip);

         if (Ethernet.hardwareStatus() == EthernetNoHardware) {
           Serial.println("Ethernet shield was not found.");
         } else if (Ethernet.linkStatus() == LinkOFF) {
           Serial.println("Ethernet cable is not connected.");
         }
       }

If this is the case, it will print "Ethernet shield was not found."

2) I'm using this Chinese W510 shield too (the same as on the photo above). Apparently, there's a known bug. Here is the solution: https://forum.arduino.cc/index.php?topic=351477.45

In short: You have to solder 2 resistors between pins 1-2 and 3-6 of the shield's Ethernet connector. No need to unsolder anything.

Works great!


message:
Receive multiple data from arduino using String builder

I am working on a small project where I have to read data from different hardware and display it on android app. I am using arduino Uno to get the values from a sensor and a motor and I use a bluetooth module to send the data to the android device. I know how to read data from motor only but not from motor AND sensor. The data displayed on the arduino can be assumed as follows:

Motor: 132

Sensor: 258

Motor: 259

Sensor: 992

So first, we will read the value of the motor then the sensor then the motor and so on. Here is part of the code where I used handler and string builder to read data from the motor. How to modify the code in order to read from BOTH the motor and sensor and keep the updating the values?

Code:

    Handler mHandler = new Handler()
        {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case 1:
                        byte[] readBuf = (byte[]) msg.obj;
                        String strIncom = new String(readBuf, 0, msg.arg1);
                        sb.append(strIncom);
                        int endOfLineIndex = sb.indexOf("\r\n");
                        if (endOfLineIndex > 0) {
                            String sbprint = sb.substring(0, endOfLineIndex);
                            sb.delete(0, sb.length());
                            motor.setText(sbprint);          // update TextView
                        }

                        break;
                }
            };
        };

body:
You can convert each value to string before sending to bluetooth using `string.contain("string")`, like this:

    if (sbprint.contains("C"){
        temptv.setText(sbprint);}
    if (sbprint.contains("H")){
        humidtytv.setText(sbprint);}


message:
Arduino on attiny85 driving 4-digit 7-segment using two 74HC595N shift register not alternating fast enough

I am using a port of the Arduino libraries on an AtTiny85 (1MHz) to drive a 4-digit 7-segment LED (common cathode, 12-pin). I'm just counting from 0 to 9 and alternating between the first two digits (pin 12 and 9) as a test. I am driving from two 74HC595N shift registers in series, the first of which will trigger S9018 NPN BJT transistors to turn on/off the digit I want and the other to light the segments.

The code seems to work fine, functionally, to alternate the two digits, but they don't alternate fast enough to make the LED show two solid digits, instead you can clearly see them flashing/alternating. Not sure what the bottleneck is but here's the code (please ignore my wiring for the 7 segments)

<!-- language: c -->

    // CONFIGURATION
    // Pins
    const int latchPin = 2;
    const int clockPin = 4;
    const int dataPin = 3;

    // Timers
    const long output_interval = 10000; // Time to change each output
    const int T_digit = 2; //period on one digit (4 digit 7-segment only)
    const int duty_digit = 1; // duty cyle of a digit shown

    // States
    unsigned long outputT_last = 0; // Holds the last time output change was checked
    unsigned long outputT_now = 0;
    bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led

    // States
    byte leds = 0;
    byte digits = 0;

    int output_count=0;

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

    void loop()
    {
      checkOutput();
    }

    void updateShiftRegister()
    {
      digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
      if(fourDigit7Segment_enable){
        int digitON = (int)(outputT_now - outputT_last);
        digits = 0;
        if(digitON%T_digit < duty_digit){
          //bitwrite led 0
          bitWrite(digits, 0, 1);
        }
        else{
          //bitwrite led 1
          bitWrite(digits, 1, 1);
        }
        //shift out digit control first in LSB
        shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
      }
      shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
      digitalWrite(latchPin, HIGH); // Trigger with rising edge
    }

    void clearMemory(){
      leds = 0;
      updateShiftRegister();
    }

    void checkOutput(){
      outputT_now = millis();
      float timeleft = (int)((outputT_now - outputT_last)/1000);
      if (outputT_now - outputT_last >= output_interval){
        outputT_last = outputT_now; // output_interval set to 10000, because LED counts 0 to 9, and then needs to reset
      }
        // clearMemory(); // Uncomment this if you want 1 LED lit at time, all others turned off
        leds = sevenSegment1D(timeleft);
        updateShiftRegister();
        // output_count++;
      // }
      // Check if we reach the end, then do 1 more iteration for 0x0 (all turned off)
      // if(output_count > 8){
        // output_count=0;
        // clearMemory();
      // }
    }

    byte sevenSegment1D(int i){
      switch (i) {
          case 0:
            return 0x7E; //01111110
            break;
          case 1:
            return 0x48; //01001000
            break;
          case 2:
            return 0x3D; //00111101
            break;
          case 3:
            return 0x6D; //01101101
            break;
          case 4:
            return 0x4B; //01001011
            break;
          case 5:
            return 0x67; //01100111
            break;
          case 6:
            return 0x77; //01110111
            break;
          case 7:
            return 0x4C; //01001100
            break;
          case 8:
            return 0x7F; //01111111
            break;
          case 9:
            return 0x6F; //01101111
            break;
          default:
            return 0x0; //Arduino doesn't handle bytes in binary
      }
    }

I tried to mod a float but it seems to require an int, so that's why I stopped at 2%1. I also converted the code from a single-digit 7-segment LED so please ignore anything that doesn't make sense in lighting up the segments.

I am not sure if the bottleneck is my code, the 1MHz AtTiny85, or the shift register.

EDIT: switched over to `micros()` instead of using `millis()` for more resolution. Still not solid.

body:
The original idea was to divide up a specific period into segments where each digit on the 4-digit 7-segment would light up. I would use a mod(%) and divide it up to make the function call more generic for future extensibility (and also make it more asynchronous). What I learned is that it would probably take more work doing the calculations then just calling a function to reset and light up the next digit one after another. Here's the updated code:

    // CONFIGURATION
    // Pins
    const int latchPin = 2;
    const int clockPin = 4;
    const int dataPin = 3;

    // Timers
    const int countdown = 60; // amount of time to countdown from in seconds
    const long reset_interval = countdown*1000000; // interval before reset in microseconds, i.e. if countdown is set to 60s, every 60 seconds will reset display to countdown start

    // States
    unsigned long last_display_update_time = 0; // Holds the last time output change was checked
    unsigned long curr_time = 0;
    bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led

    // States
    byte leds = 0;
    byte digits = 0;

    int output_count=0;

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

    void loop()
    {
      updateResetTimer(); // checks what the countdown is at
      int timeleft = countdown - (curr_time - last_display_update_time)/1000000;
      leds = getSevenSegmentFormation(timeleft/10);
      updateShiftRegister(0);
      leds = getSevenSegmentFormation(timeleft);
      updateShiftRegister(1);
    }

    void updateShiftRegister(int digit)
    {
      digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
      if(fourDigit7Segment_enable){
        int digitON = micros();
        digits = 0;
        bitWrite(digits, digit, 1);
        //shift out digit control first in LSB
        shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
      }
      shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
      digitalWrite(latchPin, HIGH); // Trigger with rising edge
    }

    //Turns off all 7 segments of a digit, will need to specify digits 0 to n
    void clearMemory(int i){
      leds = 0;
      updateShiftRegister(i);
    }

    //Updating timer for resetting countdown
    //Will take absolute current time and compare it to the last time checked, if it is greater than countdown value, we reset
    void updateResetTimer(){
      curr_time = micros();
      if (curr_time - last_display_update_time >= reset_interval){
        last_display_update_time = curr_time; // reset_interval set to 10000000, because LED counts 0 to 9, and then needs to reset // actually set to 60*1000000 to countdown 1 minute
      }
    }

    byte getSevenSegmentFormation(int i){
      switch (i) {
          case 0:
            return 0x7E; //01111110
            break;
          case 1:
            return 0x48; //01001000
            break;
          case 2:
            return 0x3D; //00111101
            break;
          case 3:
            return 0x6D; //01101101
            break;
          case 4:
            return 0x4B; //01001011
            break;
          case 5:
            return 0x67; //01100111
            break;
          case 6:
            return 0x77; //01110111
            break;
          case 7:
            return 0x4C; //01001100
            break;
          case 8:
            return 0x7F; //01111111
            break;
          case 9:
            return 0x6F; //01101111
            break;
          default:
            return 0x0; //Arduino doesn't handle bytes in binary
      }
    }


message:
Bizarre compilation problem -- only compiles with the addition of a single Serial.println() line?

I have a [SwitchDoc Labs DS3231 Real Time Clock Module][1] that I am using with an Arduino Mega.  It's connected to 3.3V and the SDA(20)/SDL(21) pins.  I'm also using SwitchDoc's RTC_SDL_DS3231_ARDUINO library (see link to the example sketch below).

I can compile and run the example provided with the library just fine.  However, I'm running into a very bizarre compilation problem when I remove the Clock set function calls in the setup.

Rather than take up the space and copy the code that works I'll just link to it on github: [100% working for me example][2].

The problem I am running into happens when I remove (or comment out) the section in the setup function that sets the time:

    void setup() {
   // Start the I2C interface
   Wire.begin();
      // Removed code
   // Start the serial interface
      Serial.begin(9600);
    }

Then I get the following error when I try to compile/verify the sketch:

    /Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/../
    lib/gcc/avr/4.3.2/../../../../avr/lib/avr6/crtm2560.o: In function `__vector_default':
    (.vectors+0x90): relocation truncated to fit: R_AVR_13_PCREL against symbol `__vector_36'
    defined in .text.__vector_36 section in core.a(HardwareSerial.cpp.o)

If I add back just one single clock set call it will compile:

    void setup() {
   // Start the I2C interface
   Wire.begin();
      Clock.setYear(15);  //Set the year (Last two digits of the year)
   // Start the serial interface
      Serial.begin(9600);
    }

However, the truly strange thing is that if I simply add a Serial.println() line to the setup function, the sketch compiles too!

    void setup() {
   // Start the I2C interface
   Wire.begin();
   // Start the serial interface
      Serial.begin(9600);
      // Adding the following line allows the sketch to compile
      Serial.println("Why does this work now???");
    }

Thanks for any help.

  [1]: http://www.switchdoc.com/ds3231-real-time-clock-module/
  [2]: https://github.com/switchdoclabs/RTC_SDL_DS3231_ARDUINO/blob/master/DS3231/Examples/DS3231_TEST/DS3231_TEST.ino

body:
**Update**: This seems to be a linker bug. Quick fix: upgrade your
Arduino installation. See the end of this answer for details. What
follows is the first version of this answer, with a detailed explanation
of the error message.

------------------------------------------------------------------------

You have a problem linking the interrupt vector table with your program.
I quite understand what the error message means, but I do not understand
how in the world you can possibly have this error. This should not
happen. I will try to explain the error anyway.

The Arduino Mega is based on an AVR chip. The AVR instruction set has
“jump” and “call” instruction that come in two flavors:

- “absolute” jumps and calls (opcodes: `jmp` and `call`) can address the
  whole flash memory, which means you can branch from any part of the
  program to any other part, without restrictions.
- “relative” (a.k.a. “PC-relative”) jumps and calls (opcodes: `rjmp` and
  `rcall`) have limited range: they can only bring you to nearby places,
  no more than 4 K from your starting point.

The relative flavors take less space and execute faster, they are thus
better _if_ the destination is close enough. On the smaller AVR chips
(up to 8 K of flash), they can access the whole flash, then these
chips lack the absolute flavors.

## How the vector table is normally linked

Every program you build for an AVR starts with an “interrupt vector
table”. This is a series of jump instructions that are automatically
executed whenever an interrupt triggers: if the _n_-th supported
interrupt triggers, then the hardware automatically loads and executes
the _n_-th jump instruction, which will jump the execution of the
program to the corresponding ISR (_interrupt service routine_). The
table is chip-specific: on the smaller AVRs (up to 8 K), it's a
table of `rjmp`, whereas on the bigger ones it's a table of `jmp`. This
table is part of the CRT (_C run time_) provided by the avr-libc library
in a file named crtXXX.o, where XXX is a code identifying the chip. The
Arduino Mega being based on the ATmega2560 chip, it's CRT is crtm2560.o.

I disassembled my own copy of crtm2560.o and found this vector table:

    00000000 <__vectors>:
       0:   0c 94 00 00     jmp 0
       4:   0c 94 00 00     jmp 0
       8:   0c 94 00 00     jmp 0
       ...
      e0:   0c 94 00 00     jmp 0

You can see these are all `jmp` instructions (absolute flavor), as
expected for any AVR with more than 8 K of flash. The address of
the jump, however, is always 0, which is obviously wrong. This is
because the proper addresses cannot be known until the program is fully
built. When you build your program, the linker will put all the pieces
together. It will then know where the ISRs are, and it will patch the
vector table to make it correct. This kind of patching is known as
“relocation”, and the linker performs this based on some “relocation
records” included in the CRT. Here are the relevant records from my copy
of crtm2560.o:

    RELOCATION RECORDS FOR [.vectors]:
    OFFSET   TYPE              VALUE
    00000000 R_AVR_CALL        __init
    00000004 R_AVR_CALL        __vector_1
    00000008 R_AVR_CALL        __vector_2
    ...
    00000090 R_AVR_CALL        __vector_36  [*]
    ...
    000000e0 R_AVR_CALL        __vector_56

The record I marked with [\*] means: “at offset 0x90 into the vector
table there is an absolute jump or call instruction, and the instruction
should be modified to point to \_\_vector\_36”. This tells the linker
how to fix the table when building the program.

If I instead disassemble a CRT for a smaller chip, I get a smaller table
made of `rjmp` (instead of `jmp`) instructions, and the relocation
records look like this:

    RELOCATION RECORDS FOR [.vectors]:
    OFFSET   TYPE              VALUE
    00000000 R_AVR_13_PCREL    __init
    00000002 R_AVR_13_PCREL    __vector_1
    00000004 R_AVR_13_PCREL    __vector_2
    ...
    00000032 R_AVR_13_PCREL    __vector_25

These records mean “at offset XXX into the vector table there is a
PC-relative jump or call instruction, and the instruction should be
modified to point to \_\_vector\_XXX”.

## Your error message

Your error message provides the following information:

- “crtm2560.o”: this is your CRT, where the vector table and the
  relocation records live.
- “.vectors+0x90”: this means the problem is at offset 0x90 into the
  vector table.
- “R\_AVR\_13\_PCREL against symbol \`\_\_vector\_36'”: this means there
  is a relocation record of type R\_AVR\_13\_PCREL (PC-relative jump or
  call) referencing \_\_vector\_36. **Here seems to be the problem**.
- “defined in [...] core.a(HardwareSerial.cpp.o)”: this \_\_vector\_36
  is part of the serial port code from the Arduino core library.
- “relocation truncated to fit”: \_\_vector\_36 is too far to be reached
  by a PC-relative jump, thus the linker could not relocate properly.

The problem seems to be that the relocation record is of type
R\_AVR\_13\_PCREL, which is what you expect on smaller chips but not on
your ATmega2560. You normally expect R\_AVR\_CALL.

Now, about the strange behavior: the exact point where the ISR lands
when the program is built is difficult to predict. Add or remove a few
lines in your code and the linker may bring the pieces together in a
different order. Then, the infamous \_\_vector\_36 may end up being in
range or out of range of a relative jump. Given the nature of the error,
the behavior you find “strange” is actually quite normal.

## Further debugging

The root of the problem seems to be an incorrect relocation record in
your CRT. You can try to disassemble the CRT to see what is wrong:
search your computer for a file named crtm2560.o, probably in
/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/avr/lib/avr6
or a similar place. The tool needed for disassembling is called
“avr-objdump” and should be hidden somewhere in your Arduino
installation folder. Once you find the files, start a terminal and type

    /path/to/avr-objdump -d /path/to/crtm2560.o

with “/path/to” replaced by the actual paths. You should see something
very much like the first listing of my answer, with lots of `jmp`
instructions. If you have `rjmp` instructions instead, then something is
already wrong at this level.

To see the relocation records, type:

    /path/to/avr-objdump -r /path/to/crtm2560.o

The output should look like my second listing, with lots of `R_AVR_CALL`
records. If you have `R_AVR_13_PCREL` instead, the records are wrong.

If this is the problem, then the obvious fix would be to replace the
broken CRT with a sane one. You may try to reinstall the whole Arduino
package. If you still have a corrupted CRT, you should report the error
to the Arduino folks. Then you may try to fetch a fresh copy of the
[avr-libc](http://www.nongnu.org/avr-libc/) and replace the relevant
parts of your Arduino installation. Replacing just the CRT may or may
not work: I don't know whether the last version of the CRT has
incompatibilities with older versions of the rest of the libc.

## Update: this is a linker bug

I did some research, and I now believe you have hit a linker bug. There
is a gcc option called `-mrelax` that allows some link-time
optimizations. One if them is to have the linker replace some absolute
jumps and calls by the smaller and faster relative ones. Obviously, this
is only possible if the target address is within reach of the relative
jumps or calls. There was a bug in old versions of the GNU linker (up to
2.22) where, under some obscure circumstances, it would erroneously
believe the target was reachable, only to find out later that it was
not. This bug mainly affected the interrupt vector table, producing the
kind of error message you are seeing now.

Here is a partial timeline of this bug and its fix:

- November 2011: this is filed as
  [bug 13410](https://sourceware.org/bugzilla/show_bug.cgi?id=13410)
  on the bug tracker for the GNU binutils package.
- January 2012: Vidya Praveen, from Atmel, publishes a fix.
- February 2012: the fix is committed to the development version of
  binutils.
- October 2012: GNU binutils 2.23 is released, including the fix.
  The same month, the bug is reported again as
  [issue 1071](https://github.com/arduino/Arduino/issues/1071)
  on the Arduino issue tracker.
- June 2013: Paul Stoffregen links this new issue to the old bug.
- June 2014: Arduino [gets an updated
  toolchain](https://github.com/arduino/Arduino/commit/98c3080d2a6065013f40c3656ce593e765b3bdb1)
  including binutils 2.23.2, which fixes the bug in the development
  version of Arduino.
- July 2014: [Arduino 1.5.7 beta is
  released](http://arduino.cc/en/Main/ReleaseNotes) including the
  updated toolchain.
- September 2014: Arduino 1.0.6 is released _with the old toolchain_.

A [workaround for the bug](https://stackoverflow.com/a/18062480) has been
published by Mark Anderson on stackoverflow. The real fix, however,
would be to upgrade to the latest Arduino package (1.6.1 as of this
writing).


message:
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.

body:
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.


message:
Simulation of Arduino Mega 2560 with GSM Module using Proteus

I have really been suffering with my simulation! Tried connecting my arduino mega 2560 to COMPIM (used as GSM Module) in my circuit and also loaded sample code but damn! In vain! I wanted to view the data sent in virtual terminal but am getting nothing! and its also complaining of excessive CPU usage.

This is the circuit as seen below in Proteus.

![enter image description here][1]

And thereafter, the log messages are displayed as shown below.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/ZnXU2.png
  [2]: https://i.stack.imgur.com/crkuK.png

Someone please help me out. Am I making a mistake oh? Infact the arduino code for displaying in the simulation is also giving me hard time. The one am using is as shown below.

 #include <SoftwareSerial.h>

 SoftwareSerial mySerial(10, 11); // RX, TX

 void setup()
 {
   // Open serial communications and wait for port to open:
   Serial.begin(9600);
   while (!Serial) {
  ; // wait for serial port to connect. Needed for Leonardo only
   }

   Serial.println("Goodnight moon!");

   // set the data rate for the SoftwareSerial port
   mySerial.begin(9600);
   mySerial.println("Hello, world?");
 }

 void loop() // run over and over
 {
   if (mySerial.available())
  mySerial.println("Hello, world?");
   if (Serial.available())
  mySerial.println("Hello, world?");
 }

Will b every grateful for any help offered.

body:
You should download this [GSM Library for Proteus][1] . You can use this library to simulate your GSM module in Proteus software. You should also check this example where they have discussed Hoe to [Send SMS with GSM module in Proteus ISIS][2]. I hope it will help you out.

Thanks.

  [1]: http://www.theengineeringprojects.com/2016/03/gsm-library-proteus.html
  [2]: http://www.theengineeringprojects.com/2016/04/send-sms-sim900d-proteus-isis.html


body:
Hello I had the same problem as you, but I managed to solve it.
Use the TinyGSM library. Open the library folder, locate the Tinygsmcommon file.
Open the file, line 75 changes the value from Baud 9600 to 2400. That is the minimum speed of my module.

In proteus work with the same speed 2400.
It worked here. Proteus can not handle so much speed.
And do not forget to also change the speed of GSM, place 2400.


message:
Why does timer ISR not execute?

This is my code which I have written as a library

    #include "avr/interrupt.h"
    #include "Arduino.h"
    #include "AllTimer.h"

    AllTimer::AllTimer()
    {}

    void AllTimer::dofun(void)
    {
      //TIFR1 |= _BV(OCF1A);

     TCCR1B = 0X00;
     //TIFR1 = 0X01;
     digitalWrite(13,!digitalRead(13));
     Serial.print("I printed");
     TCNT1 = 0X0000;
     TCCR1B |= (1<<CS12) && (1<<CS10);
     //sei();
    }

     void AllTimer::setTimer(void)
     {
     TCNT1 = 0x0000;
     TCCR1A = 0x00;
     TCCR1B = 0x00;
     TCCR1B |= (1<<CS12) && (1<<CS10);
     TIMSK1 |= (1<<TOIE1);
     sei();
     }

    ISR (TIMER1_OVF_vect)
    {
      AllTimer::dofun();
    }

Code in Arduino IDE:

     #include <AllTimer.h>

     AllTimer mytimer;

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

     void loop()
     {
         mytimer.setTimer();
        //delay(200);
      }

But I am not getting anything on the serial monitor. What is the error I have made?

body:
The Arduino `main()` calls `loop()` continuously, in a tight loop. Thus
your `AllTimer::setTimer()` is called continuously, and each time it
resets the counter (`TCNT1 = 0x0000;`). Thus the counter can never
overflow.


message:
Can I use relays with 10A125V~ for my 220V~ applications, safely?

I am using the [TinkerKit Relay Module][1] and recently they changed the relay mounted on the board from a white one with `10A250V~` to a black one with `10A125V~`.

In my country the voltage is `220V~`. Can I use the black relay in my application, safely? May be there problems that I have to be careful?

  [1]: http://store.arduino.cc/product/T010010

body:
The part is obsolete now according to [Mouser][1].  The simple answer is no, you cannot use a 120 volt part at 220 volts.  The higher voltage can breakdown the lower voltage rated parts.  It really has nothing to do with the "power" rating as there will be very little power actually dissipated in the relay.  The current handling of the contacts is one issue and that seemingly didn't change but the voltage rating change is basically saying that this part cannot work at 220volts.

  [1]: https://www.mouser.com/ProductDetail/Arduino/T010010/?qs=/ha2pyFaduia6R6na02v8WdqPh%2bg5WbwIxjODzSpP4DYszJBtcfl8A==


message:
Arduino Uno R3 USB is not working

I have a problem with my Arduino Uno board. It's not mounting in my Linux machine, but its power is *on* and the LED light is glowing. It was working before. After I tested buttons with an 12 V external supply, I am facing this scenario.

I tried `lsusb` and I checked `/dev/ ports`. Also, I couldn't find `ttyACM. I tried with another Arduino board and it's working. I think the board is gone, and I need help to fix this problem.

I thought it was a bootloader problem, and I got a *new ATmega328P chip board*. It is getting power on and the LED is blinking, but the port is not mounted. I tried with `lsusb` and also `ls /dev/ttyACM*` with no result.

body:
You could try to flash the firmware of the USB controller.

General steps for Arduino R3 are:

1. Put the Arduino in DFU mode (the R3 does *not* require soldering for that)

2. Flash the firmware using:

        dfu-programmer atmega16u2 erase
        dfu-programmer atmega16u2 flash Arduino-usbserial-atmega16u2-Uno-Rev3.hex
        dfu-programmer atmega16u2 reset

    The package "dfu-programmer" is most likely available for your distribution.

If you have to build it from source, because your DFU programmer does not know the ATmega16U2 yet, you will need to install libusb-dev (on Debian-based systems).

Useful links for that:

* *[Resetting your Uno R3's default firmware][1]*
* *[Updating the Atmega8U2 and 16U2 on an Uno or Mega2560 using DFU][2]*

A useful search term for that is `Arduino R3 DFU-programmer`.

  [1]: https://github.com/leocadiotine/Dvorany/wiki/Resetting-your-Uno-R3's-default-firmware
  [2]: http://arduino.cc/en/Hacking/DFUProgramming8U2


message:
UNO analog input voltage reading not accurate

My loop code is this:

    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(float(sensorValue*5000.0/1023));
    delay(1);        // delay in between reads for stability

When I read 5V it gives 5000 mV. When I read 3.3V pin it gives 3211 mV. When I read 1442 mV battery it gives 1392. What do you think about this situation?

NOTE: There is no any additive circuit. Just wires.

body:
Both your measurement (e.g. using a voltmeter) and the ADC of the Arduino have a limited accuracy (cf. table 28.7 in the [datasheet of the ATmega328][1]). Therefore you should never expect them to agree to all given digits.

Concerning the points raised in your comment:

> All comments are true but it gives 5V correctly, why?

`analogRead` returns a value between 0 and 1023. For all voltages above an (unknown) threshold close to 5 V, it will saturate and always return 1023, no matter what the actual input voltage is. This value is then converted to 5.000 V in your code. What you are probably seeing is just the maximum value your code can return, not an accurate measurement of a 5 V input voltage.

> And my voltmeter is not corrupted.

It doesn't have to be corrupted. It will still be off. Have a look at the manual to find the nominal accuracy. (Also note that [accuracy and precision][2] are two different things and different from the number of digits of the display, assuming your voltmeter is digital.)

  [1]: http://www.atmel.com/dyn/resources/prod_documents/doc8161.pdf
  [2]: https://en.wikipedia.org/wiki/Accuracy_and_precision


body:
Your question contains a number of errors and misconceptions.

Firstly the maximum output of a successive approximation ADC (here 0x3ff) corresponds to Vref - 1 LSB
The voltage will thus be `sensorValue*5000.0/1024`. Note this error is less than the error of ±2LSB.

Measuring your 5V is futile, as this is the default analog reference, so the result must be 0x3ff.

Measuring the 3.3V pin will give a relative value to the 5V reference. Both are produced from commercial grade regulators with a accuracy of ±5%.

You are also confusing the precision of the reading (10 bit) with accuracy which is a best ±5% ±2LSB.

If you really want to measure voltage you should use the internal 1.1V bandgap reference. You would of course need to reduce the 5V and 3.3V to less than 1.1V. This introduces another potential error (even if you use 1% resistors), but would give more accurate results which are directly comparable.


message:
Can I safely connect my original Arduino Uno to a 19V adapter?

I have an original Arduino Uno R3. According to the [specifications](http://www.arduino.cc/en/Main/arduinoBoardUno) the recommended input voltage is 7 to 12 Volt.

However, I have a laptop adapter of 19V that I want to use to power my arduino because it offers more current than the 9V adapter I have as well.

I don't want to damage the Arduino or the [DFRobot 2A Motor Shield](http://www.dfrobot.com/index.php?route=product/product&product_id=69) I'm using. Can I safely plug in the adapter and will it still work correctly?

body:
According to the page you linked:

> [The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.][1]

So, yes. You can use the 19V external power supply to power the board. However, be aware that the voltage regulator can overheat over time and damage the board.

  [1]: http://www.arduino.cc/en/Main/arduinoBoardUno


body:
It's often better to supply separate power to high-current applications (such as motors) rather than taking power off the Arduino. This avoids problems with current and thermal limits of the Arduino on-board power regulator.

Looking at the [manual for your board][manual], the motors can be powered by a separate power supply hooked up directly to the motor shield. There's a six-pin header on the board marked VIN and PWRIN. When the jumpers are on the VIN side Arduino-supplied power is used to drive the motors; when the jumpers are on the PWRIN side the motors are supplied with power from the terminal block next to the jumper. (The rest of the board remains powered from the Arduino, but that's usually a negligible amount of current compared to your motors.) A photo in the manual demonstrates the pins set to PWRIN and an external power supply hooked up.

The documentation says you can supply any voltage between 4.8 V and 35 V DC, but **be careful!** What they don't make clear in the documentation (but is clear from the [schematic] and the [L298N datasheet]) is that this power is supplied directly to power side of the L298N and the motors without further regulation. The chip can handle up to 50 V DC, so it would be fine with a 35 V input, but you'll want to check that your motors can handle the voltage you want to give them.

If the motors can handle 19 V input, and your 19 V power supply is reasonably well regulated itself (which a laptop computer power supply generally would be), you can use that to power the motors directly through the motor shield and continue using your current power supply to power the Arduino.

(The [ST L298] page has further information, including a slightly less readable copy of the data sheet and application notes.)

[manual]: https://www.dfrobot.com/wiki/index.php/Arduino_Motor_Shield_(L298N)_(SKU:DRI0009)
[schematic]: http://image.dfrobot.com/image/data/DRI0009/Arduino L298 Shield Sch.pdf
[L298N datasheet]: http://image.dfrobot.com/image/data/DRI0009/L298N datasheet.pdf
[ST L298]: http://www.st.com/en/motor-drivers/l298.html