message:
Upload Assembly to AVR on a breadboard using Arduino as ISP

I try to learn assembly and use an arduino uno R3 to act as a programmer. i have build a standalone circuit with an atmega328p, can upload usual sketches (written in c) and have also sucessfully burned the bootloader to the external chip with the arduino as an isp but i cant bring my assembly code onto the chip on the breadboard. i tried it with avrdude and the following command

    avrdude -C avrdude.conf -p atmega328p -c avrisp -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

and also

    avrdude -C avrdude.conf -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

but the code is always uploaded to the chip on the arduino - not to the one on the breadboard. can anyone lead me how to upload my assembly programm to the standalone chip on the breadboard using the arduino as isp? is this possible anyway?

EDIT This command worked for me

    avrdude -C avrdude.conf -v -v -v -v -p atmega328p -c stk500v1 -P /dev/ttyACM0 -b19200 -Uflash:w:test.hex:i

body:
Try uploading the blink sketch to the standalone atmega328 first.

Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings).


sender: user

message:
Why can only some digital ports output PWM and the others not?

If it matters, I'm talking about the arduino uno v3.

sender: assistant

body:
Check out the ATMega328p [datasheet][1]: each of the 3 timer/counter blocks can generate PWM (2 PWM signals per timer) and on top of that, typically Timer1 (16 bits) is used by the OS/scheduler/whatever, unless you are really running on bare metal.

It's a limitation, but so is everything else.

If you do not like it, you can always choose a different microcontroller, either AVR or something else.
Certain models might  be designed to have more units of a specific type than you would find on generic microcontrollers.

  [1]: http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf


body: That is one of the hardware features/functions of the microprocessor.  It is like a bag of candy when you eat the last piece there is no more left.  You can do software PWM but that can use a lot of compute power.  You can also get PWM peripheral devices you can connect to it.


body:
After all, it's a cost issue.

Not only of the Arduino/Atmel, but any microcontroller.

The outputs of the PWM unit (which has a limited number of PWM channels) have to be routed to the output pins.

This routing is basically fix, because the silicon mask is fix.

However, to add some flexibility, most controllers allow a limited configuration of this routing by adding some internal switches which can be accessed by writing to the specific registers.

But any additional routing capabilities means more of those internal switches, which results in
more size -> more silicon -> more expensive.

Therefore the micro designers say - for example - "OK, it's enough to be able to output x of the y available PWM channels at every edge of the micro", and the poor PCB designer has to cope with what he gets.

Using an FPGA instead of a microcontroller you are really free to setup your function to pin routing - but look at the price of an FPGA ;-)


message:
Need help in the project "Arduino for audio processing"

I am following this link from Instructables site:

http://www.instructables.com/id/Arduino-Audio-Input/

My question is:

Instead of using the Microphone Radioshack 33-3038, which is listed in the tutorial, can I use https://www.sparkfun.com/products/9964?

Kindly suggest if there any modifications required in other parts for the circuitry, if I go for Electret Microphone.

body:
The replacement microphone you link to contains all the circuitry in that instructable*.  You can do away with the op-amp and all the associated stuff, and just connect it direct to the analog input of the Arduino.

----
*Actually it's better circuitry since they do it right, unlike the Destructable that is a rubbish circuit.


message:
How to use TimerOne while calculating time?

I'm trying to get warning with buzzer while I get same values on 3 seconds. But first warning doesn't wait 3 seconds. Second warning is correct. Code is attached. BlinkLED1() method is same BlinkLED2. Probably, I'm missing crowning touch. Can you help me?
Thanks in advance.

    void initialsettings(double roll,double pitch){
      if(level==0){
        if(roll>=34 && timerstatus==false){

            Timer1.initialize(3000000);
            timerstatus=true;
            Timer1.attachInterrupt(blinkLED);
        } else{
             Timer1.stop();
             timerstatus=false;
             level=0;
        }

       }else if(level==1){
          if(roll<=-34 && timerstatus==false){

            Timer1.initialize(3000000);
            timerstatus=true;
             Timer1.attachInterrupt(blinkLED2);
          } else{
               Timer1.stop();
             timerstatus=false;

          }

      }else if(level==2){

      }
    }

    void blinkLED(void)
    {
        noInterrupts();
        Timer1.stop();

        //Timer1.restart();
        digitalWrite(buzzerpin,HIGH);
        delay(7000);
        digitalWrite(buzzerpin,LOW);
        timerstatus=false;
        interrupts();
        if(level==0){
          level=1;
          Serial.println("level 1");
        }
      Serial.println("Sag ");
        //Serial.print("\n");

    }

body:
        Timer1.attachInterrupt(blinkLED);
...

    void blinkLED(void)
    {
        noInterrupts();
        Timer1.stop();

        //Timer1.restart();
        digitalWrite(buzzerpin,HIGH);
        delay(7000);
        digitalWrite(buzzerpin,LOW);
        timerstatus=false;
        interrupts();
        if(level==0){
          level=1;
          Serial.println("level 1");
        }
      Serial.println("Sag ");

---

* Don't do serial prints inside an interrupt service routine (ISR).
* Don't use `delay()` inside an ISR.
* Don't turn interrupts on or off inside an ISR.
* Variables shared between an ISR and the main code should be `volatile` (I can't see from your [snippet](http://snippets-r-us.com/) whether they are or not).

Reference: [Interrupts](http://www.gammon.com.au/interrupts)


message:
Wrong calculation UNO

I've a joystick and a servo connected to my UNO, but for some reason my calculations keep on being wrong? I'm trying to calculate how the rotation should be of my servo (Tower Pro 9g, max value of 180 I think) with my Joystick (Keyes_SJoys, max value of 1023 on any axis) and example would be:

y = 500;
servo.write(y * 180 / 1023); // should equal to 87.97, but in reality it's 24?

    #include <Servo.h>

    Servo servo;
    int d2 = 2;
    int a0 = 0;

    void setup() {
      Serial.begin(9600);
      servo.attach(d2);
    }

    void loop() {
      int y = analogRead(a0);
      Serial.print("y: "); Serial.println(y);

      servo.write(y * 180 / 1023);
      Serial.println(y * 180 / 1023);

      delay(100);
    }

PS. It's a Robotale UNO; I don't know if that makes any difference or not, but.

body:
What you are experiencing is a common pitfall.
You are probably expecting floating point calculations, but what you are writing are only integer ones.

Try with:  y * 180. / 1023.   (notice the dots).

This will work only with constants.

To make it work with anything, use a cast:  y * 180 / (float) 1023

Happy hacking.


body:
The reason you're getting completely the wrong value (not just losing the decimal portion) is because of a problem called *integer overflow*.

Because the Arduino is an 8-bit device the default integer size is double that.  That means that an integer value can store 16 bits, and when signed that's -32768 to 32767.

Any calculations, unless you specify otherwise, have to fit into that range.  If you take your calculation step by step you will see how it works:

    500 * 180 = 90,000

Represented in Hexadecimal (for ease of demonstration) 90,000 is 0x15F90.  That is 17 bits (4 bits per digit, the left hand is just one bit since it's only the value 1), and 17 is more than the maximum 16 allowed.  So we have to "overflow" that value and discard the lefthand-most digit to keep it at 16 bits.  So we end up with 0x5F90.

0x5F90 in decimal is 24464.  Now we divide that by 1023 and we get:

    24464 / 1023 = 23.914

Because it's integers we have no decimal portion of it, so that just ends up as the 23 that you are seeing.

Solutions?  Change the data type.

As @IgorStoppa has pointed out you can use floating point values which gives you big values and the decimal portion.  As long as one value in your sum is floating point all the values will be. This is known as *promotion*.  There's numerous ways you can force floating values:

1. Represent your literals as a floating point value - that means adding a decimal place. You could have (as Igor shows) things like `1023.`, but I find that a little obscure.  It's better to explicitly show a decimal value since it's obvious what it is then, such as `y * 180.0 / 1023.0`.
2. Use a floating point *literal suffix*.  You can add certain letters after a number to describe what that number is.  `f` is for floating point: `y * 180f / 1023f`.

Floating point is quite heavy weight though and can cause your program to get bigger than you'd like.  If you're not interested in the decimal portion you can instead use *long* variables.  The best way to do that is with the *long* literal suffix `L`:  `y * 180L / 1023L`

*Promotion* means that all the variables are *promoted* to the size of the biggest variable (not greatest value, the variable with the largest storage space).  Long and Float are both 32 bits in size, so using either of those will force the other values to both be *promoted* to equivalent types.


message:
Beginner here. Which arduino revision should i buy?

I have no idea what difference is there between the revisions and how it affects me. I have a pdf and this pic was in there:
![arduino pic][1]

My questions

 - which arduino revision is this?
 - Does it matter which revision i    buy?

  [1]: https://i.stack.imgur.com/7ARQA.jpg

body:
That looks like an UNO R2, the type with DIP micro controller (you can extract it and replace it with another one, in case of problems).
The R3 version is probably the best choice to get started.
You might want one that has a connector where this one has only the 3x2 empty pads on the top left (close to the vertical writing AREF).
Have a look on ebay/aliexpress/amazon. You can find it for as little as $5-$6. Just search for UNOR3, if you elect to buy this type.


body:
That looks like an early-version Uno, rather than an Uno R3 as shown below. (Image is from dxcdn.com and is one of the first few images in a [google images for Uno R3](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1002&bih=626&q=UNO+R3&oq=UNO+R3&gs_l=img.12..0l7j0i5i30l3.1757.1757.0.2961.1.1.0.0.0.0.92.92.1.1.0.ecynfh...0...1..64.img..0.1.91.PlZ5WbbvIEA#imgrc=gYQV8pLWKcYuZM:) search.)

[![Uno R3][1]][1]

For a beginner, replacing a DIP ATMEGA328P may be a chip too far.  I suggest that rather than looking for an Uno with a replacable chip, get any Uno you like.

Also note that for beginning projects, it makes sense to use the same kind of Arduino – an Uno, a Mega, a Pro Mini, a Nano, etc. – as the guide you are following uses, so that you won't have to adapt any pin numbers and wiring pictures.  As you gain experience, it should become easy to adapt designs to different boards.

  [1]: https://i.stack.imgur.com/jhKAV.jpg


message:
How to control 6 stepper motors with Arduino?

I would like to control 6 stepper motors (0.225A, 2 V) with Arduino. I was thinking to use motor drivers from Pololu website, for example [DRV8834][1].

Is it possible?

Any suggestion for another type of motor driver?

We need to limit the current, but I also got the advice to use the PWM signal to control the stepper motor. Any advice for this?

  [1]: https://www.pololu.com/product/2134/resources

body:
You could create your own custom shield with an Arduino mega and 6 Stepper sticks

http://www.amazon.com/Hobbypower-StepStick-4-layer-DRV8825-Stepper/dp/B00NCSK6T2/ref=sr_1_1?ie=UTF8&qid=1455740571&sr=8-1&keywords=DRV8825

Here is a link to the stepper sticks I was talking about. To make this work you would need to be able to solder the breadboard together and set up the arduino to accept pins from the breadboard. You would also need a 12v power supply to give the motors power


body:
Yes it is possible, of course everything is possible!

These drivers need two IO lines at very minimum: DIR and STEP. Pulsing STEP makes one step movement forward or backwards (depending on DIR).

For 6 steppers you need therefore 12 outputs from Arduino. (Which Arduino please? pick one which has enough IO, or otherwise use an I2C output extender).

M0 and M1 controls microstepping mode - configure at your wish. CFG is high on this Pololu board, allowing the board to use as a stepper driver out of the box.

Steppers (if you want to get them working at full torque) require a constant-current drive. (Inexpensive solutions use a constant voltage drive, such as using an ULN2803 - however those can not get too much torque). Happily this driver can do this well, the potentiometer sets the maximum current.

Steppers need considerable current when starting movement to a next step. However, unlike DC motors, even a still position will consume current, which eventually makes the motor hot. Therefore you are supposed to limit the current when the motor is _not_ moving. This is usually done from software (the driver does not known when it is time for a long period at stop).

The way for limiting motor current at stop can be either an analog limiter, or a PWM. This driver has no dedicated input for this purpose. You can do two things:

 * use smaller drive current (use the potentiometer) - this can work well if you're satisfied with the torque
 * use the sleep mode of the driver with a PWM from the Arduino side.

This latter solution needs you to:

* connect all EN pins of all 6 drivers, and connect it to one Arduino pin which has PWM (i.e. `analogWrite()`)
* drive this to 0, then start movements
* once movements are finished, use `analogWrite()` and set to say, 128 (usually half of the move current is a good guess for holding current)

This way when the motors are stopped, the holding current will be less, hence the motors don't get hot.


message:
Wrong analog reading

I am making a simple Li-Ion battery Tester. Basically its two 5R1 resistor in series and a relay (used to cut off the battery when it reaches cutoff voltage). Arduino is connected with ground to the battery and with A3 to the end of the resistors. But when I try to read the analog value, I receive something like 870, which is about 4.24V. BUT the real voltage is about 3.90V (according to my multimeter). How is that possible? Thanks for any suggestions.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/CelLF.png

body: I have found the answer. I am not an arduino-newbie, but I was thinking that probably I am making a stupid mistake somewhere. But the problem is in **my arduino**. I tried setting pin D13 (and then all other pins) to HIGH, and I only measured **4.60V**! I measured my USB port and it outputs 5.00V exactly, so there must be a problem in the arduino. So the solution - **the ADC takes 4.60V as 1023, and therefore if you calculate it you get that the real voltage is 3.90V**, which is exactly the same as my DMM said. Thanks Majenko, you were pointing the right way :) By the way, I was using a cheap Arduino Nano from China, I bought it only for 2.2 USD from Ebay. When I used original Arduino, the code and circuit perfectly works. Do you think that this can limit the functionality of my board?


message:
GPRS shield - Hayes commands to identify a faulty SIM connection

I'm currently battling with a LinkSprite GPRS shield (it's based on the SIMCom SIM900 chip) and seem to have absolutely no luck trying to connect to the network.  I've got two SIMs, both of which should be active, but I cannot get the connection light on.

I've got a serial connection going and it's responding to various AT commands, but I can't connect:

> AT+COPS=?

 is working, and giving me a list of networks, so I think my antenna is good, but

> AT+COPS=-whatever-

 immediately gives me +CREG: 3.

I'm now wondering whether there's a fault with my board, and that it's not seeing the SIM cards.  A few commands that I thought would work aren't, for example:

> AT+CPIN?

 just returns ERROR

Similarly, when trying to read SMS data:

> AT+CMGL="ALL"

 returns ERROR.

Have I proved that the board isn't seeing the SIM, or is there something definitive I can try?

Thanks in advance!

body: Having exchanged the board for another one (that works!) I can now confirm that the calls above (e.g. AT+CMGL) *should* work if there is a working SIM connection.


message:
does INPUT_PULLUP uses power?

When using a digital pin as input, one has the option of using the internal arduino resistor, which is connected to VCC; that is setting the digital pin as INPUT_PULLUP, and then the pin reads HIGH. Does this uses electricity?.

I mean the resistor is connected directly to VCC and I presume electricity is constantly flowing through the system, no?.
as oppose to having the pin as just INPUT?

body:
Only the leakage current on the input itself is constantly consumed if there is no external connection. This is usually much less than the waste caused by having the input floating.

> If a voltage between 0.8 V and 2 V is applied to the input for a prolonged period of time, this situation becomes critical and
should not be ignored, especially with higher bit count and more dense packages [...]. For example, if an 18-bit
transceiver has 36 I/O pins floating at the threshold, the current from VCC can be as high as 150 mA to 200 mA.


body: See <https://arduino.stackexchange.com/questions/16424/deviation-of-power-consumption-between-datasheet-and-real-world> - there we established that leaving the pins input consumed considerably more power than input_pullup. That was with the pins not connected to anything.


body: The pullups have a value between 20k and 50kOhm. If the input is connected to ground (button pressed), between 0.1mA and 0.25mA is flowing through the resistor. So bare anything.


message:
A knob that can be turned by hand, have the position read, and turned by software to another position?

I'd like to be able to change variables on the Arduino by adjusting a set of knobs.  When I get to a desirable setting I'd like to be able to save those settings on the Arduino... and then I'd like to be able to load those settings back, and have the knobs turn themselves back to the correct positions.  Specifically I'm thinking of using this with a synthesizer.

I understand how to do all of this, except, I don't know if there are knobs that allow this type of behavior.

body: If you can't get a motorised potentiometer could you use a rotary encoder, a motor, a shaft and some cogs.  Press the shaft and rotate manually then release and it disengages the manual cog and moves back to the motor cog.


body: If you attach a knob to the Analog Feedback Micro Servo, either directly or via gears, then you can use the pot output to measure the current position and use the normal servo control protocol to turn it under software control.


body:
Alternatively, just add an LED/LCD display on top of each knob (or have a larger LCD showing info for all the knobs) to show the value.
Then you can have the knobs implemented with an optical rotary encoder.

Each knob is unmarked and doesn't need to be reset.

This solution doesn't put any mechanical part under strain.


body:
Not a knob, but depending on your application, would a [motorized slider like this be applicable][1]?

You would read it just as you would a potentiality, and you have a motor that you can use to drive it to a specific position when you make a change in your software.

As for knobs, I have seen very few if any _motorized knobs_. What I would recommend here would be a continuous rotation encoder so that the position of the knob actually doesn't matter.

  [1]: https://www.sparkfun.com/products/10976


message:
A question about including libraries

I'm a beginner in creating my own libraries so the following might contain some stupid stuff.

Anyways, I'm using NRF24L01+ modules for wireless communication and I've been utilizing the magnificent RF24 library (https://github.com/TMRh20/RF24) to operate these modules using Arduino. I wanted to clean up my code and decided to write my own library that uses the R24 library. My own library would contain all the subroutines that handle TX and RX functions.

Problem is that the RF24 library is initialized using e.g.

    /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
    RF24 radio(7,8);

To begin using the NRF24L01+ one would the use the RF24 library like for example:

    byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
    Serial.begin(57600);
    printf_begin();
    radio.begin();

    radio.setPALevel(RF24_PA_HIGH);
    radio.setCRCLength(RF24_CRC_16);

    radio.setRetries(2,15);
    radio.setChannel(RFChannel);
    if(radioNumber){
    radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
    radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
    }else{
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
    }

    if(radioNumber == 1){
    radio.startListening(); // Start listening
    }
    radio.printDetails();

Well, now I would like to make a library that would allow me just to call setup to handle all of the above. My library would be called RadioComm so I would call in my main code:

    RadioComm rComm();

    setup() {
    rComm.setup();
    }

The problem is that how do I use the RF24 library and all its functions in my library? To initialize the RF24 library in my own library I would have to call somehow this

    RF24 radio(7,8);

and use all the radio. commands. How do I tell my own library that everything starting with "radio." is related to RF24 library because right now I'm getting this:

    RadioComm.cpp: In member function 'void RadioComm::setup()':
    RadioComm.cpp:20:18: error: 'radio' was not declared in this scope
    radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

Below are my .h .cpp and .ino files

Lib_test.ino

    #include <RadioComm.h>
    #include <RF24.h>
    #include <SPI.h>

    RadioComm rComm;

    void setup() {

    rComm.setup();

    }

    void loop() {

    }

RadioComm.h

    #ifndef RadioComm_h
    #define RadioComm_h

    #include "Arduino.h"
    #include <RF24.h>

    struct dataStruct{
 unsigned long id;
 float value1;
 float value2;
 float value3;
 float value4;
 };

    class RadioComm
    {

    public:

 RadioComm();
 void setup(void);

    private:
    int pin1;
 int pin2;

    };

    #endif

RadioComm.cpp

    #include "Arduino.h"
    #include "RadioComm.h"
    #include <RF24.h>
    #include "printf.h"

    RadioComm::RadioComm(void)
    {}

    void RadioComm::setup()
    {
    byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
    radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10
    Serial.begin(57600);
    printf_begin();
    radio.begin();
    radio.setPALevel(RF24_PA_HIGH);
    radio.setCRCLength(RF24_CRC_16);

    radio.setRetries(2,15);
    radio.setChannel(RFChannel);
    if(radioNumber){
    radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
    radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
    }else{
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
    }

    if(radioNumber == 1){
    radio.startListening(); // Start listening
    }
    radio.printDetails();
    }

Any help is appreciated.

Thanks.

body:
Firstly, to address your compilation error:

    RadioComm rComm();

That is not a constructor, that is a function prototype. When you have no parameters to a constructor you *must not* include the brackets or it confuses the poor little compiler.

    RadioComm rComm;

Now - to address your main question.  Well, there's many ways of doing it, but the way I always tackle this is to have your sketch define the RF24 object and pass it to the library for later use.

In the class definition, in the `private` section, add:

    RF24 *radio;

Then change the constructor to have:

    RadioComm(RF24 &r);

The constructor itself would then read:

    RadioComm::RadioComm(RF24 &r) {
        radio = &r;
    }

Now throughout your library, instead of working with `radio.whatever` you need to work with `radio->whatever` since you are now using a pointer to an object not the object itself.

Then in your sketch you need to adjust your constructor to be:

    RF24 myRadio(7, 8);
    RadioComm rComm(myRadio);

The beauty of this is it decouples the configuration of the RF24 class from the RadioComm class, so you can use the same library in a different situation on a different board with different pins without having to change the library - just change the RF24 constructor in your sketch.

It also gives you direct access to the RF24 class in your sketch so you can do any advanced manual tweaks outside the library should you wish to.


message:
Can't upload my sketch from arduino IDE

I am using arduino uno and window7 64bit.I can't upload my program to arduino uno.When I upload it the warning message is show me.The warning message is"WARNING:Category 'USB' in library keyboard and mouse is not valid. Setting to 'Uncategorized'.What can I do?

body:
Arduino IDEs v.1.6.x have recently been causing such kind of trouble on windows and mac systems. These problems seem to be caused by Java issues. Arduino IDE comes with java suit for it to work, installing java separately will cause problems. I suggest you uninstall java completely(by that i mean even the residue files that are not removed after uninstalling. For removing java completely you can use third party java remover like JavaRa ( https://singularlabs.com/software/javara/ ).
After doing so you can install the IDE again (i suggest to use .zip download of the IDE).
If it does'nt help it check this out http://forum.arduino.cc/index.php?topic=341144.0
its possible that problem is caused by out dated executables after updating the IDE.

Hope it helps.


message:
MPU-9250 : How to convert pitch (+90/-90) to 360 degree?

I'm using Arduino Uno with MPU-9250 to find roll, pitch and yaw.

Everything works fine but I want to covert pitch from (+90/-90) to 360 degree.

I'm using this code:

    vec.setX(atan2(2.0 * (m_data[2] * m_data[3] + m_data[0] * m_data[1]),
            1 - 2.0 * (m_data[1] * m_data[1] + m_data[2] * m_data[2])));

    vec.setY(asin(2.0 * (m_data[0] * m_data[2] - m_data[1] * m_data[3])));

    vec.setZ(atan2(2.0 * (m_data[1] * m_data[2] + m_data[0] * m_data[3]),
            1 - 2.0 * (m_data[2] * m_data[2] + m_data[3] * m_data[3])));

    m_data[0] = scalar;

    m_data[1] = x;

    m_data[2] = y;

    m_data[3] = z;

What should I do?

body:
I assume you want to map the range `-90...-1` to `270...359` and the range `0...90` to `0...90`?

It's simple enough:

    if (angle < 0)
        angle = 360 + angle;

Note that you are *adding the negative value* to 360, which is the same as *subtracting the positive value*.

*Or* do you want to map it so that -90 is 0 and +90 is 360?  In that case you need to offset and scale it:

    angle = angle + 90; // Angle is now 0..180
    angle = angle * 2; // angle is now 0...360

Or in one line:

    angle = (angle + 90) * 2;


body:
The equations in you example convert a quaternion representation of rotation into euler angles correctly; The "pitch" euler angle only has a valid range of +90/-90 and changing it will make your angular representation invalid.

Euler angles specify an arbitrary rotation by 3 consecutive turns. You may want "apparent angle with the horizon", which is not the same thing, and does not define a sequential set of turns to get from rotation A to B.

To get pitch and roll with the horizon from a quaternion, I think you want something like:

    float x = 2*m_data[1]*m_data[3] - 2*m_data[2]*m_data[0];
    float y = 2*m_data[1]*m_data[0] + 2*m_data[2]*m_data[3];
    float z = 1 - 2*m_data[2]*m_data[2] - 2*m_data[1]*m_data[1];

    float pitch = atan2(y,z);
    float roll  = atan2(x,z);

I got this by rotating the vector <0,0,1> by the quaternion and then measuring the angles of the result around x and y axis. This kind of freaks out when one of the angles is close to 90 degrees though; there are probably better equations out there.

"Yaw vs the horizon" doesn't make any sense, and people usually want the same "style" of yaw you are getting from the euler angle equations, so that shouldn't change.


message:
Burned Arduino?

I have an arduino that I programmed a PWM signal on pin 5. When I power the arduino with 12v or USB5v, pin 5 has the PWM signal. Iam checking it with a oscilloscope. Oddly enough the arduino is not recognisable to a windows PC or MAC, the device never shows up on the usb. The LED on the device seem to give all the right signals. The Green ON LED is on. And the L LED is also on. The program is not using serial so the RX and TX are not on.

When I try another Arduino it works fine.

What could I have broke? I am guessing the ATmega328 is fine?

body: Just a guess, if anything else work fine, my (first) guess would be the serial to usb adapter. I damaged one a while ago on a breadboard but also dont know how. But it could also be almost everything else. The pwm sketch, in which language is it written and burned? Does the Atmega have a bootloader on it?


message:
Help understanding code to build circuit for plant reader

I'm working a design project that measures the tiny changes of conductivity in a plant. (To visualize how a plant reacts to its environment) I'm working with Arduino to realize that. Two wires are hooked up to the plant to measure the changes and are connected to the Arduino. I haven't worked with Arduino before but a friend got me the code from his plant reader (he got help too and doesn't know how to build it anymore). I do understand most of it but I just don't manage to translate the code he gave me into a circuit on the Arduino bread board. I use processing to visualize the measurements afterwards.
[![Code plant reader][1]][1]

  [1]: https://i.stack.imgur.com/IrmNL.png

Who can help me building the circuit. I don't get what's happening at pin13. Thank you for helping me :)

body:
Pin13 is attached to the onboard LED.

So when you see a reference to it, it means that the program is turning the light ON/OFF. You do not need to do any wiring with it.

But the logic seems strange: it turns the LED off only when the analog reading is out of range (and it resets the stress).

It seems to imply that once the plant is stressed, it will stay stressed :-)

Btw, as side note: posting the code in ASCII form would allow people to quote/comment on it. The screenshot is not very good for that purpose.

What cannot be figured out from the code, is how to instrument your plant.
If your friend has a working setup, you could try to replicate it.
At least post a few pictures.


message:
Arduino and 127/220 Volts: Relay and Isolation

I am new to Arduino, also, I am not fluent in english.

I wish to create a controller for several circuits. All of those circuits are "in parallel" with additional circuits.

My question is:

* Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

Suppose the following:

[![Eletric wiring][1]][1]

The retangular boxes are "parallel switches" connected to the devices.

    R = Power Supply Phase

    S = Another Power Supply Phase

    N = power Supply Neutral

    Arduino, C2 and C3 are 127 Volts, (S+N)

    C0 and C1 are 220 Volts (R+S)

* Are the Shields safe from oscilations from the eletrical supply?

* What / Where / How should I look on what to ground? Local regulations state that I cannot let R and/or S be grounded.

  [1]: https://i.stack.imgur.com/EhmwY.png

body:
> Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

A relay provides *galvanic isolation* in the circuit.  The mains power is electrically isolated from the rest of the circuit since the device that performs the actual switching (the contacts in the relay) have no physical connection to the rest of the circuit - they are merely acted upon by magnetism.

That doesn't mean that it's *safe*, however.  There are a number of things you still need to deal with:

* The Arduino cannot directly drive a relay - it can't provide enough current. You must use a drive circuit.
* Back-EMF from the relay coil as the magnetic field collapses can damage sensitive semiconductors - good snubber circuit design is important here.
* Mains electricity is dangerous and must be treated with respect.  Proper circuit design is paramount to ensure that the mains is kept away from the rest of the circuit. Proper connectors must be used and exposed high voltage points must be rendered inaccessible, either by the project housing or by the addition of plastic insulating shielding.
* Relays as they turn on and off cause sparks. Sparks cause EMI. EMI causes induced currents. Induced currents cause damage to electronics.  Minimizing the spark generation not only prolongs the life of your relay but the life of everything else around. Ensure your relays can switch fast enough for the currents you are dealing with, or consider using *solid state relays* (SSRs) that don't suffer from this issue.


message:
Why I cannot connect directly Arduino UNO and Xbee S2?

I'm connecting Arduino UNO to Xbee S2 Zigbee module directly, and X-CTU cannot find Xbee module via arduino. i'm not using shield, it finds with non-arduino board connecter, but not by arduino UNO board.

i checked all parameters like baud rate, etc.., wirings, and it seems no problem at all, but it keeps msg like 'reset your radio module' and even i swtiched pin 5 and GND, it doesn't works.

what i have to do?

body:
If you want X-CTU to see the Xbee while it's connected to the Arduino, you have to connect the Arduino's reset pin to ground. This bypasses the Arduino's MCU and allows the Arduino to act as a USB to serial adapter.

Also don't forget to connect the Arduino's Tx to the Xbee's Tx when it's connected like this, and likewise with the 2 Rx's.


message:
What is the relationship between the gain on the receiver and the delay time

I was conducting some research on wireless communication between a simple transmitter and receiver module using an Arduino. Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%. I am not quite sure why the data would result in this. I think it possibly has something to do with the gain on the receiver and the delay time. Some sweet spot perhaps? Can anyone offer me some ideas/explanations? Also, sorry for any confusion in this question. I am happy to clarify.

Part 2:

Hey Everyone,

I also had a question regarding what purpose each of the following delay serves in wireless communication.

    // Write each of the 8 bits
    for (uint8_t i = 8; i > 0; --i)
    {
      if (b & 1) // choose bit
        *reg |= reg_mask; // send 1
      else
        *reg &= inv_mask; // send 0

      tunedDelay(delay);// line in question ---------------------
      b >>= 1;
    }

and the delay used in the regular blink program.

**The regular delay used in the blink programs was what set the 2 microsecond delays.**

Lastly, I am looking at the read and recv methods in the software serial library and i don't see any checks for start bits, so what's the point of writing one in the write method?

body:
>  I am looking at the read and recv methods in the software serial library and I don't see any checks for start bits, so what's the point of writing one in the write method?

The start bit is absolutely essential in serial comms. In the graphic below, the start bit is marked "B" - which distinguishes it from "idle" data which is "A". Once received, the receiver then waits 1.5 bit times and starts clocking in the remaining bits. (Starting at "C" in the diagram, and then moving on for a total of 8 bits).

[![One serial byte][1]][1]

Without a start bit, how would the receiver know when the byte started? Imagine you wanted to send 0xFF (all 1 bits). Without a start bit that would be indistinguishable from the idle state.

In the graphic, "D" is the stop bit. Why have a stop bit? We need one (which is a "1" bit), so that we can detect the transition from the stop bit in the previous byte (a "1") and the start bit in the next byte (a "0").

In the graphic, "E" is the start bit for the next byte.

---

> I don't see any checks for start bits ...

SoftwareSerial has a pin-change interrupt set up to detect that the receiving pin has changed state (to a zero usually). **That** is your start bit. You don't see it in the loop, because it has already arrived, otherwise you wouldn't be in the receive loop in the first place.

  [1]: https://i.stack.imgur.com/xmEc6.png


body:
> Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%.

Microsecond resolution delays on an Arduino are tenuous at best.  They aren't that accurate.  Simply because you're hitting the limit of the speed of the CPU.

At 16MHz you have a clock period of 1/16000000 seconds.  That's 63ns.  That's the *granularity* of the delays you can achieve - and that can only be achieved by inserting a precise number of `NOP` assembly instructions.

So for the best 1µs delay possible you would need (0.000001 / 0.000000063) 15.87 `NOP` instructions.  Of course, you can't have that many, so you have to round it either up or down.  Normal integer truncation would result in 15.  So that would actually be a delay of 945ns, which is an error of 5.5%.

2µs would be (0.000002 / 0.000000063) 31.74 `NOP` instructions, which would round to 31, so 1.953µs, or an error of 2.35%.  As you can see increasing the length generally reduces the error.

*HOWEVER*

The delay function on the Arduino for microsecond accuracy (`delayMicroseconds()`) is maybe not as accurate as it could be.  Simply because it's impossible to just have an exact number of NOP instructions for a delay since you can't know how long the delay should be until the function is called with a parameter detailing how long the delay should be.  So it has to perform a number of calculations and *make a number of assumptions*.  It tries to come close, but it was written for one specific version of the compiler and compilers change. Things may have been changed in how the function gets called, and how long parts of it take (what registers are pushed and popped may change with different compiler versions, for instance).  So it's not a perfectly reliable delay.

For more detail you can look at the source code of it (it's in `wiring.c`) and you can see how for small delays it's very hard to get it right. For instance, this couple of lines highlights the problem nicely:

        // for a one-microsecond delay, simply return.  the overhead
        // of the function call yields a delay of approximately 1 1/8 us.
        if (--us == 0)
            return;

Note the use of the word *approximately* there...

Also you need to note that the delay functions are just that - a delay *at that specific moment in time from the start of the call to its finish*.  It doesn't take into account anything else that's going on in your code, so a delay of 1µs in a loop of code that does other things will end up in a loop that takes `X + 1µs` where `X` is the amount of time that the rest of the code takes to execute.

And that's where the `tunedDelay()` function comes in.  It has been specially written to be used in that specific circumstance to provide a delay that *takes into account the time the rest of the loop takes to run*.  That is, the loop's time plus the `tunedDelay` time equate to the final period you want for the whole loop.  For asynchronous serial communications the timing accuracy is important.  Since there is no separate (or even embedded) clock to get the timing from both ends have to agree what speed the communication happens at (the baud rate), and any deviation from that can cause communication errors.  So the timing has to be as close as possible. A normal `delayMicroseconds()` function call just wouldn't cut the mustard - they needed it more precise than that.  Manually tuned to have specific delay values that are as precise as possible, and that was done for specific baud rates on specific speed chips.  Each supported frequency has a table such as this:

    static const DELAY_TABLE PROGMEM table[] =
    {
      //  baud    rxcenter   rxintra    rxstop    tx
      { 115200,   1,         17,        17,       12,    },
      { 57600,    10,        37,        37,       33,    },
      { 38400,    25,        57,        57,       54,    },
      { 31250,    31,        70,        70,       68,    },
      { 28800,    34,        77,        77,       74,    },
      { 19200,    54,        117,       117,      114,   },
      { 14400,    74,        156,       156,      153,   },
      { 9600,     114,       236,       236,      233,   },
      { 4800,     233,       474,       474,      471,   },
      { 2400,     471,       950,       950,      947,   },
      { 1200,     947,       1902,      1902,     1899,  },
      { 600,      1902,      3804,      3804,     3800,  },
      { 300,      3804,      7617,      7617,     7614,  },
    };

That's the value to send to the `tunedDelay()` function in the four different situations where its used for each of the baud rates at that specific clock frequency (16MHz in that example).

`tunedDelay()` itself is written in assembly code and is a very tight loop for the number of iterations specified in the parameter.  The shortest possible piece of code with the minimum of overhead to get the maximum accuracy and finest granularity (least number of clock cycles for one iteration) out of it.


message:
Connect 2 LSM9DS0 to Flora

So I'd like to connect two of these sensors to an Adafruit Flora (https://www.adafruit.com/products/2020). In the product page it says you can only connect one but in the forum an admin said that you could do it but it required a bit of hacking. I'm new to arduinos and circuits in general. Can someone tell me how I could do this, or at least point me in the right direction?

**Edit**

I decided to use this multiplexer to use LSM9DS0's with the Flora.
https://www.adafruit.com/products/2717

body:
[Adafruit's rectangular 9DOF](https://learn.adafruit.com/adafruit-lsm9ds0-accelerometer-gyro-magnetometer-9-dof-breakouts) device, unlike [their round 9DOF](https://www.adafruit.com/products/1059), brings several more signals out to pads.  When using I²C with the rectangular 9DOF board, as I understand it signal pin SA0_G can be set low or high to modify the device address:
> The SDO/SA0 pins (SDO_XM/SA0_XM or SDO_G/SA0_G) can be used to modify the least significant bit of the device address. If the SA0 pin is connected to the voltage supply, LSb is 1 (ex. address 0011101b) else if SA0 pad is connected to ground, the LSb value is 0 (ex. address 0011110b).

Controlling that signal should let you put multiple 9DOF's on one system.  (See my answer to  [question 13830](https://arduino.stackexchange.com/questions/13830/arduino-due-and-bno055-address-in-i2c-mode/13833#13833) for some additional comments on setting an I²C address.) Also see tables 15 and 16 on page 33 in the spec sheet (DM00087365.pdf) regarding addresses.

If you insist on using round 9DOFs for this application, you would need to find the trace from pin 22¤ of the LSM9DS0 to Vcc on *one* of your 9DOF boards; working under a microscope with miniature tools, cut the trace and rewire the pin end of the trace to Ground.  This will change that board from using addresses 0x1D and 0x6B to 0x1E and 0x6C, if I correctly understand the spec sheet.

It probably would be a good idea to get one of the rectangular 9DOF's so that you could experiment with changing its addresses, before modifying one of the round ones.

¤ Looking at the top of the chip, pin 24 is just clockwise from the depressed round dot marking pin 1; pin 22 is 1.75 mm from the corner.  See Figure 21, LGA 4x4x1 mm 24-lead outline, in the spec sheet.  That figure shows the underside of the chip.


message:
Can I use GSM and GPS modules at the same time?

In my project I want to retrieve the Latitude and longitude and then transmit to a cell phone through GSM module. But the GSM as well as GPS modules uses the same pins i.e. Tx and Rx, so is it possible to use both modules at the same time?

Link to products

GSM - http://www.ebay.co.uk/itm/SIM800L-GPRS-GSM-Module-SIM-Board-Quadband-PCB-Antenna-for-MCU-Arduino-/191611848583?hash=item2c9cf4c787

GPS-- http://www.ebay.co.uk/itm/New-1PC-Ublox-NEO6MV2-GPS-Module-Aircraft-Flight-Controller-For-Arduino-/400830328802?hash=item5d53596fe2

Thank you.

body:
Yes.  Use SoftwareSerial for one of them.  That way you can use any pins you like for that module.

I'd recommend using the GPS module on the SoftwareSerial since it's (mainly) half duplex, and SoftwareSerial can't both transmit and receive at the same time like the hardware UART can.

Either that or switch to a different Arduino board that has more than one hardware UART.


body:
If you are using two software serial then you can always use the `listen()` function to listen to specific object.

Suppose you have two software serial objects named GSM and GPS.
Now if you are reading or writing data to GSM then start with this, `gsm.listen();`
Now you can read/write data to GSM.
Next if you plan to read or write data to GPS then do this, `gps.listen();`


message:
Esp8266 server unreachable. Port doesn't open

I have followed all the instructions provided on  [http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/][1]

I have got the correct setup, I have got the message "Server Ready" in the serial monitor, i have an app similar to this, means the only thing i have done different from the web page is removing two buttons from the app.

But then also whenever i use my app to send request parameters to arduino it says "connection to 192.168.x.x:xx refused" , when i put the same ip and port in chrome, it says Server not reachable, the website may be down, What to do ? , Please help...

  [1]: http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/

body:
The ESP module is not that difficult to work with, if you send the correct parameters to it AND you have the correct power it should work as expected.

My main suspicions will be cabling (just triple check that connections are as expected) and power source (the ESP is VERY power hungry, if you are powering the ESP from the Arduino that is your problem, you need a very good and stable power for the ESP to work (it might show up on your network but will not have enough power to actually send anything and it will disconnect (that will still show up on your router, it depends on how fast it connects/disconnects but won't be able to send anything).

This link can provide some good information about this subject:

http://bbs.espressif.com/viewtopic.php?t=133


message:
Error in Arduino Library file

I am working on a project which includes Arduino and a fingerprint scanner. It is completely based on embedded system. But then, I have downloaded a library for the fingerprint scanner. When I run the program I get an error which maps to the cpp file of the library file. See below to see the error and the library file.

**Error**

> FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
> Command_Packet::GetPacketBytes()':
> C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:17:
> undefined reference tooperator new[](unsigned int)'
> FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
> FPS_GT511C3::GetResponse()':
> C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:735:
> undefined reference tooperator new[](unsigned int)' collect2.exe:
> error: ld returned 1 exit status

Library File (CPP)

> byte* packetbytes= new byte[12];
>
> byte* resp = new byte[12];

body:
The core of the problem is that the code is being compiled as C and not C++.

The error says 'new[]' is undefined at the link stage.  This is because the linker is not pulling in the C++ standard libraries.  The built-in function new[] it doesn't exist in C.

The filename FPS_GT511C3.c.cpp is the elephant in the room.  You could consider renaming it (and others) to FPS_GT511C3.cpp.  Although the plain Arduino IDE does not really have a problem with building them.

Another option might be to modify the new[] (and delete[]) for C's malloc() and free().  However this is only appropriate for the allocation of simple types (byte, int, etc).  If the code also allocates objects, it's not possible to simply swap these functions out since C++ (default) initialisation is be going on.


message:
Json gets corrupted after first HTTP request

I'm a web developer and I started building a small environment logger that will post to my website`s API. I'm really new to this kind of coding so bare with me.

Since yesterday, the whole Arduino started to acting funny. After the first or second request to the server(with already tested code), I started sending corrupted JSON data.

    {
      ":12": "module3",
      "10-7 18:26": {
        "1": {
          "": 21.50,
          "26:12": 55.50,
          "measured_at": "2015-10-7 18:26:12"
        },
        "2": {
          "": 21.10,
          "26:12": 55.70,
          "measured_at": "2015-10-7 18:26:12"
        }
      }

Where it should be

    {
      "modulename": "module3",
      "environments": {
        "1": {
          "temperature": 21.40,
          "humidity": 55.60,
          "measured_at": "2015-10-7 18:25:52"
        },
        "2": {
          "temperature": 21.20,
          "humidity": 55.80,
          "measured_at": "2015-10-7 18:25:52"
        }
      }
    }

The second JSON is from the initial request to the server. The first one is the corrupted one. I tried stopping all kinds of parts from the code, without any luck, except when I enter the measured_at manually (without getting the data from the RTC.)

    #include <DHT.h>

    #include <elapsedMillis.h>

    #include <DS3231.h>
    #include <Wire.h>
    //Json Library
    #include <ArduinoJson.h>

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

    #include <LiquidCrystal.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS
    EthernetClient client;

    const String module_name = "module3";

    DHT dht1;
    DHT dht2;

    DS3231 clock;
    RTCDateTime dt;

    // initialize the library with the numbers of the interface pins

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    elapsedMillis timer0;
    const long interval = 10000; // READING INTERVAL

    int connected_sensors = 0;
    float t1 = 0;  // TEMPERATURE VAR
    float h1 = 0; // HUMIDITY VAR
    float t2 = 0;
    float h2 = 0;

    int nc = 0; //Network connection simulation INI

    byte temp[8] = { //icon for thermometer

      B00100,
      B01010,
      B01010,
      B01110,
      B01110,
      B11111,
      B11111,
      B01110
    };

    byte humi[8] = { //icon for water droplet
      B00100,
      B00100,
      B01010,
      B01010,
      B10001,
      B10001,
      B10001,
      B01110,
    };

    byte sconnect[8] = { //icon for connection
      0b00000,
      0b11111,
      0b10001,
      0b10001,
      0b11111,
      0b00100,
      0b11111,
      0b00000
    };

    void setup() {
      Serial.begin(9600);
      clock.begin();
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      Serial.println("Terrarium Serial");
      // Print a message to the LCD.
      lcd.print("Weather v0.1");
      delay(1000);
      lcd.setCursor(0, 1);
      lcd.print("Sensor loading...");

      lcd.clear();
      lcd.print("Network check...");

      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP"); //There is a problem with DHCP
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("DHCP ERROR");
        lcd.setCursor(0, 1);
        lcd.print("Please Restart");
        for (;;)
          ;
      }
      nc = 1;

      delay(2000);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(Ethernet.localIP());
      lcd.setCursor(0, 1);
      lcd.println("Ready!");

      Serial.println(F("Connected!"));
      Serial.println(Ethernet.localIP());

      delay(4000);
      lcd.clear();

      lcd.createChar(1, temp);
      lcd.createChar(2, humi);
      lcd.createChar(3, sconnect);

      dht1.setup(15);
      dht2.setup(16);

      h1 = dht1.getHumidity();
      t1 = dht1.getTemperature();

      h2 = dht2.getHumidity();
      t2 = dht2.getTemperature();

      delay(2000);

      //Display the statics on the display
      lcd.setCursor(2, 0);
      lcd.print(module_name);
      lcd.setCursor(9, 1);
      lcd.write(2);
      lcd.setCursor(15, 1);
      lcd.print("%");
      lcd.setCursor(2, 1);
      lcd.write(1);
      lcd.setCursor(8, 1);
      lcd.print((char)223);

      timer0 = 0; // clear the timer at the end of startup

    }
    void CheckSensors() {

      if (timer0 >= interval) { // READ ONLY ONCE PER INTERVAL
        timer0 -= interval;

        dt = clock.getDateTime(); //get current time

        h1 = dht1.getHumidity();
        t1 = dht1.getTemperature();

        h2 = dht2.getHumidity();
        t2 = dht2.getTemperature();

        DataSend(); //send data
      }
    }

    //Print the changeable values on the display
    void LcdPint() {
      lcd.setCursor(0, 0);
      if (nc == 1) {
        lcd.write(3);
      } else if (nc == 0) {
        lcd.print(" ");
      } else if (nc == 2) {
        lcd.print("E");
      }

      lcd.setCursor(10, 1);
      lcd.print(h1);

      lcd.setCursor(3, 1);
      lcd.print(t1);

    }

    //Construct the JSON response
    JsonObject& prepareResponse(JsonBuffer& jsonBuffer, String measured_at) {

      JsonObject& root = jsonBuffer.createObject();
      root["modulename"] = module_name;

      JsonObject& environmentsObject = root.createNestedObject("environments");

        JsonObject& environmentsOne = environmentsObject.createNestedObject("1");
        environmentsOne["temperature"] = t1;
        environmentsOne["humidity"] = h1;
        environmentsOne["measured_at"] =  measured_at;

        JsonObject& environmentsTwo = environmentsObject.createNestedObject("2");
        environmentsTwo["temperature"] = t2;
        environmentsTwo["humidity"] = h2;
        environmentsTwo["measured_at"] =  measured_at;

      return root;
    }

    void writeResponse(EthernetClient& client, JsonObject& json) {

      char buffer[256];
      json.printTo(buffer, sizeof(buffer));

      if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
        client.println("POST /v1/sensors HTTP/1.1");
        client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
        client.println("Content-Type: application/json");
        client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
        client.println("Connection: close");
        client.print("Content-Length: ");
        client.println(strlen(buffer));
        client.println();
        client.println(buffer);

        nc = 1;
      } else {
        nc = 2;
        Serial.println("connection failed");
      }

      while (client.connected())
      {
        if ( client.available() )
        {
          char c = client.read();
          Serial.print(c);
        }
      }
      Serial.println();
      client.stop();
      //End  post request

    }
    void DataSend() {

     //This is the part that I think crashes my entire code. I tried using the helper with the RTC library that I use
     //but that made things worse.

        String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

        StaticJsonBuffer<200> jsonBuffer;
        JsonObject& json = prepareResponse(jsonBuffer, measured_at);
        json.prettyPrintTo(Serial);

        writeResponse(client, json);

    }

    void loop() {
      CheckSensors();
      LcdPint();
    }

body:
In all probability you are either running out of memory, or the libraries you are using (and the fact that you are abusing String objects) is fragmenting your heap to such an extent that your whole 2KB of RAM is being used and you are ending up with a stack-and-heap collision.

You have to remember that the Arduino Uno only has 2KB of RAM.  It's not a computer, and has no OS, and as such you have to unlearn much of what you know about programming and do things slightly differently.

The first problem you have is with your String abuse.  This line:

    String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

will be doing horrible things to your heap.  The String class dynamically allocates memory on the heap to store the string content.  The operations you have there inadvertently create a rather alarming number of temporary Strings which are then thrown away at the end.  Every temporary String dynamically allocates RAM on the heap and can potentially lead to heap fragmentation.

For instance the numeric value `dt.second` is first converted to a String and memory allocated to store the content.  Every concatenation results in a new String with its dynamic allocation, etc.  Quite messy really.

Secondly, who knows what dynamic memory the `ArduinoJSON` library is using - quite a lot would be my guess - every tag, every value, etc, would need to be stored in memory somewhere, and unless they statically allocate a huge chunk of RAM (wasting most of your precious resource) they will be doing dynamic allocation - and that will make matters much worse.

So how would you get around it? It's actually quite simple - you need to think more about spoon-feeding a baby instead of preparing a 5 course banquet.

Instead of building up big objects with lots of data in them and sending them all out in one big chunk you need to just send little bits at a time.  There is absolutely no reason to use things like ArduinoJSON if all you are doing is sending data.

For instance to send the JSON data you could do something like this:

      if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
        client.println("POST /v1/sensors HTTP/1.1");
        client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
        client.println("Content-Type: application/json");
        client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
        client.println("Connection: close");
        client.println();

        client.println("{");
        client.println("    \"modulename\": \"module3\",");
        client.println("    \"environments\": {");
        client.println("        \"1\": {");
        client.print("            \"temperature\":
        client.print(t1);
        client.println(",");
        client.print("            \"humidity\":
        client.print(h1);
        client.println(",");
        client.println("        },");

Etc.  You get the drift.

You notice I removed the `Content-length` header?  That's because you don't know how long the content will be now (one drawback), so to signal the end of the transmission you will have to close the connection (I don't recall if `client` has a way of only half closing - just the TX portion) to signal to the web server that you have finished.  However, if you know how long your numbers will be (say you format them to a specific number of characters) then your body size would always be the same and you can hard code a `Content-length` header.

Also - do you really need to send the time and date?  Surely the computer has a better idea of what the current time and date is than the Arduino - just use the computer's internal clock.


body:
You have used 461 out of 2048 of your RAM bytes for string literals alone. At the very least, use the `F()` macro where you can, eg.

    client.println(F("POST /v1/sensors HTTP/1.1"));
    client.println(F("Host: api.terrariums.eu")); // SERVER ADDRESS HERE TOO
    client.println(F("Content-Type: application/json"));
    client.println(F("Authorization: Basic bW9kdWxlMzoxMzIxMzI="));
    client.println(F("Connection: close"));
    client.print(F("Content-Length: "));

Ditto for `Serial.print` and `lcd.print` where you are printing strings.

After that, what Majenko suggested is a good idea. Using a custom library is well and good, but JSON is easy enough to output directly. Just make a small function to do it for you.

---

> Problem now is the Content-length... How do I calculate it ?

Do you absolutely need it? If you do, instead of building up the entire content first, I suggest two passes.

First pass outputs to a dummy class which simply calculates the length, second pass actually outputs. Something like this:

    // outputting class that just counts output
    class DummyOutput : public Print
    {
    private:
      unsigned long length_;

    public:
      void begin ()
        {
        length_ = 0;
        }
      virtual size_t write (byte c)
        {
        length_++;
        return 1;
        }
      unsigned long getLength () const { return length_; }

    };  // end of DummyOutput

    DummyOutput countOutput;  // instance of DummyOutput

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

      Print * outputter;  // where to write to

      for (int pass = 1; pass <= 2; pass++)
        {
        randomSeed (1);
        switch (pass)
         {
         case 1: outputter = &countOutput;
                 countOutput.begin ();
                 break;

         case 2: outputter = &Serial;
                 break;
         } // end of switch

        // generate some output
        for (int i = 0; i < 25; i++)
          {
          outputter->print (random (5000));
          outputter->print ('\n');
          }

        switch (pass)
         {
         case 1: Serial.print (F("Content-length: "));
                 Serial.println (countOutput.getLength ());
                 break;

         case 2: break;
         } // end of switch

        }  // end of for loop
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Output:

    Starting
    Content-length: 121
    1807
    249
    73
    3658
    3930
    1272
    2544
    878
    2923
    2709
    4440
    3165
    4492
    3042
    2987
    2503
    2327
    1729
    3840
    2612
    4303
    3169
    2709
    2157
    4560

By generating the same output in two passes you can first just calculate the length (without outputting) and the second time you can output that length first, and then output the actual data.


message:
Can I use these cheap GSM module with arduino?

I found two cheap GSM module on ebay but didn't know that I can use them with Arduino or not.
Will you help me please?

Here are the link-

http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8

http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?_trksid=p2045573.c100033.m2042&_trkparms=aid=111001&algo=REC.SEED&ao=1&asc=20131017132637&meid=70128bc79b60410d862b64d36cc479b3&pid=100033&rk=1&rkt=4&sd=281517486292

body:
Both seem to have the pin header for a serial port. So chances are that they can take standard AT commands.
I've seen many modems using additional AT commands for special functions, but they all supported also the basic AT commands.


body:
The SIM900A won't work in the UK, it's dual band.

The SIM800L is cheap as there is no power regulation on board. IIRC it requires 3.4V - 4.5V, min 2 amp supply. Check the data sheet to be sure.


body:
You can actually use the sim900a and 900a mini in the uk but you will have to download firmware and flashing tools that you will find with a web search, not for the beginner though, an 800l is your best bet with a SMA Female JACK Connector to U.FL/IPX Converter Pigtail Cable F1445K so you can attach an sma antenna

cheers
Stuart


message:
Reading analog signal from digital pin #6

Is it possible to use digital pin 6 (PD6_PCINT22/AIN0) to read an analog voltage with analogRead()?

According to the ATMega datasheet, this should be possible.

If yes how is it done ? (pin configuration)

body: That is not possible. AIN0 is an input to the analog *comparator*, not the analog-to-digital converter. Only ADC0 through ADC8 (connected to the internal temperature sensor), the 1.1V reference, and ground can be connected to the ADC.


body:
Maybe. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega) and the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega).

As you can see in the image below the pin PD6 is not an analog input. To be an analog pin it should be write ADCx, like the PC0..5.

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

So, if you are not using and Arduino Uno you can't use PD6 as analog input but you can use PC0..5.

To read an analog value using [analogRead()][2] method you can do like this:

    int analogPin = 3;
    int val = 0;           // variable to store the value read

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

    void loop()
    {
      val = analogRead(analogPin);    // read the input pin

      Serial.println(val);             // debug value
    }

  [1]: https://i.stack.imgur.com/GNTeU.png
  [2]: https://www.arduino.cc/en/Reference/AnalogRead


message:
How is LED powered when PIN 2 is disconnected?

Using the Arduino tutorial "[Button][1]", I have noticed that if I totally disconnect Pin2 from the circuit, the LED comes on dimly.

I am trying to understand HOW this happens.  Is it simply due to being a floating ground?

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

  [1]: https://www.arduino.cc/en/Tutorial/Button
  [2]: https://i.stack.imgur.com/St0Tc.png

body:
The `pinMode(buttonPin, INPUT);` line tells the board to set the `buttonPin` in high impedance mode.

When you disconnect the wire the state of that pin becomes unknown; usually it oscillates.
Since it is oscillating, the LED turns on and off randomly: you see it "dimly light".

The usual solution is to use a pull-up or pull-down. I suggest you to wire your buttons towards the ground, declare the pins as `pinMode(buttonPin, INPUT_PULLUP);` and invert the logic (i.e. `buttonState = !digitalRead(buttonPin);`). This way it will never oscillate again.


message:
Using an Arduino Nano, how many LEDs can I safely power?

I am working on building a wordclock using one of the several design ideas that you can find all over the Internet. Something like a mix of this one: http://www.instructables.com/id/Sleek-word-clock/ and this one: http://www.instructables.com/id/Personalised-Word-Clock/ A lot of the guides suggested building your own Arduino to save money, but I found these Arduino Nano clones for $7/apiece: http://www.amazon.com/gp/product/B00SGMEH7G.

I've done a few simple projects before, but nothing with the same kind of power demand. How can I figure out the power requirements? My plan is to use approximately 64 3mm LEDs via shift register, or possibly the equivalent segments of an LED strip.

The Nano clone does not have a barrel connector for external power adaptor. Should I directly solder on the power cables from an external adaptor? Use a screw terminal or similar? Is the USB adaptor a good enough source of power for 64 LEDs? Or do I have to do something else to supply external power to that many LEDs?

Thanks for any advice! I am experienced in programming but not in electrical engineering so many of the concepts are something I don't have a good handle on yet.

body:
If you are running the LEDs from shift registers then the power rating of the Nano is irrelevant.

If you are wanting to use the Nano as the power source (not recommended) then you would need to know both your expected current and what the regulator on the Nano would be able to supply.  My immediate guess is "not enough".

64 LEDs at full brightness would be expected to use a maximum of say 20mA each, so 1.28A just for the LEDs.  That's a huge amount, and way more than any linear regulator can be expected to supply without melting everything around it.

So you can reduce your current requirements by not having the LEDs as bright.  Half the current does not equate to half the apparent brightness. In fact at half the current you probably won't notice much difference at all.  At a tenth of the current you will see them a bit dimmer, but not as much as you would expect.

So you can come up with a compromise between the brightness you desire and the current consumed by each LED.

Say you end up deciding on (as Gerben has suggested) a current of 5mA per LED.  When all LEDs are on that would be (5 × 64) 320mA.  That's reasonable for a linear regulator, but still will generate more heat than is really advisable.

So you should, for this project (assuming you aren't going to be using multiplexing, which is a whole other ballgame), investigate using a switching (aka "buck") regulator.  You can pick these up on eBay for just a couple of dollars and can quite happily supply amps as opposed to milliamps and will allow you to run far more LEDs without going into thermonuclear meltdown.

Another important consideration to think about is how much current an individual shift register can provide - both through its output pins and in total for the whole chip.  There are special constant current LED driving shift registers that remove the need for individual resistors on each LED and give much better control over the LEDs than traditional logic output shift registers.


message:
Looking for a game application oriented display for Arduino Mega

I was using displays with serial communication (SPI), but sending bytes to draw a tile-based picture was way too slow so I'd like find one with a parallel port, enough fast bandwidth to receive fast pictures at a speed at least 10FPS (but I'd like 50FPS or 60FPS) from Arduino Mega (ATMEGA2560) and which has a library compatible with the Arduino's C++ compiler.

I think I've seen somewhere how to connect a display onto the XMEM pins of the Mega and send bytes like this:

    *(0x12)=0x34 // Sends 0x1234

However, I couldn't find where to buy that specific one.

I was searching on eBay, but only found displays of unsupported drivers or drivers with broken links that I couldn't download, and displays that are ridiculously large like a shovel!

The resolution it needs to have is minimum 128x64, aspect ratio must be X:Y where X is greater than Y (unless it's possible to send bytes sideways while the screen is physically placed in a different orientation on the PCB).

It must be a touch display sensitive on anything (like Nintendo DSi when drawing Flipnotes).

It should be either:

 - Monochrome
 - Color display with MS Paint colors if it has equal to or less than 256 colors
 - Color display with 16-bit color input mode if it has a lot of colors

It should be no bigger than 2.5" because this is for a little handheld console.

If anyone knows where to buy it, please comment.
<br>Thank you for your time.

body:
I'd suggest, if you haven't done it already, to take a look at what is supported by [uGFX][1].

If you find any HW meeting your needs, you can at least be sure that it is supported.

  [1]: http://ugfx.org/


body:
> I was using displays with serial communication (SPI)  ...

Personally I regards serial and SPI as different things:

* [Serial](http://www.gammon.com.au/forum/?id=10894)
* [SPI](http://www.gammon.com.au/spi)

SPI is somewhat faster than serial.

---

> ... sending bytes to draw a tile-based picture was way too slow ...

How slow was it? What was your target speed?

---

> The resolution it needs to have is minimum 128x64 ... It should be no bigger than 2.5"

Something like [2.2" 18-bit color TFT LCD display](http://www.adafruit.com/products/1480) ?

---

> fast bandwidth to receive fast pictures at a speed at least 10FPS ...

See [Toorum's Quest II - Retro video game and console](http://www.gammon.com.au/forum/?id=12623)

That guy made a sideways scrolling game outputting to video with a display resolution of 104x80 with 256 colors. He also had sound generation and managed input from a NES controller.

See [video of it in operation on YouTube](http://www.youtube.com/watch?v=sLvgW_zb6bQ).


message:
Can I use this cheap GPS module with arduino

For my project I need a GPS module, it should be cheap and I should be able to use it with arduino, after some search I got a product on ebay, I'm a 16 year old school boy and I didn't know that it will work with Arduino or not. Help me.

Here is the link--
http://www.ebay.co.uk/itm/DIYMALL-VK16E-Module-Gmouse-GPS-Module-SIRF3-Chip-with-Ceramic-Antenna-TTL-Level-/181594912168?hash=item2a47e675a8

body:
Yes.  You can tell that from two entries in the specification:

> TTL Level 9600 Baud Rate

That tells you it uses standard TTL (5V) serial to communicate, so on an Uno that would be pins 0 and 1 and the Serial object, or any pins of your choice and the SoftwareSerial library.

> Output SiRF binary system OR **nmea0183 V3.0**(GGA, GSA, GSV, RMC, VTG)

It outputs NMEA encoded data (bold added by me) which is what most of the Arduino GPS libraries are written to use.


body:
After some research it seems you can use that gps module with an Arduino. Here's a link to the data sheet for it: http://www.hanssummers.com/images/stories/ultimategps/vk16e.pdf. Also it seems like you have to use the TinyGPSPlus library to get it to work. Here's a link to learn more about it: http://arduiniana.org/libraries/tinygpsplus/. You may have to use the protocols in this data sheet: https://www.sparkfun.com/datasheets/GPS/NMEA Reference Manual-Rev2.1-Dec07.pdf.

All of this information was taken from this thread: https://www.linkedin.com/grp/post/4573843-5806249757395406852.


message:
How to read an RFID reader?

I want to connect an RFID reader to an Arduino board. The RFID reader has several wires attached, and the manual mentions them as follows:

* Red: VCC +12V
* Black: GND
* Green: D 0/RX/4R+
* White: D 1/TX/4R−
* Blue: LED/CS
* Yellow: Beep

There is also another black wire attached, but the manual does not mention it.
This is an image of it:

[![Image of RFID reader][1]][1]

I have the red wire connected to the 5V pin and the black wire to the GND pin on Arduino board. Then I have the white wire connected to the RX pin on the Arduino board.

I'm trying to Serial-read the RX port using this code:

<!-- language: c -->

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

    void loop() {
        if (Serial.available() > 0) {
            int b = Serial.read();
            Serial.print(b);
            Serial.print(" ");
        }
    }

When I try to read a keyfob, only this is printed – nineteen times `248`:

    248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248

To me it looks like there's something wrong with the connection somewhere.

How can I properly read this RFID reader? If above assumption is not correct, is there something I should know?

  [1]: https://i.stack.imgur.com/OHCWM.jpg

body:
From my personal experience, you should give some init time to the rfid reader to init.

Try to use a digital output to control the chip reset, and give it some milliseconds to init.

I had a similar behavior with a rfid reader and the reason was this I just told.

Good luck!


body: Have you tried other baud rates? Could you paste a link to the manual or upload the manual itself? From what i could find quickly, the module supports 3 modes: RS232, RS485 and Wiegand 26/34. So the manual should provide some means of selecting a particular mode (perhaps the CS pin?). I suspect you arent actually using the RS232 mode, which is why you are getting strange results. If you can't find a way to select a mode, you could try brute-forcing it and try the WG26 mode next. This code from seeedstudio seems to do the job http://www.seeedstudio.com/depot/datasheet/RFID_630_WG.pde or you could look at the Wiegand protocol on Wikipedia and write your own code, since its relatively straight forward. Also a google image search turned up this link to Aliexpress: http://www.aliexpress.com/item/Waterproof-Security-Door-Access-Control-Wiegand-26-125KHz-RFID-ID-Card-Reader-EM4100-102A/1362129655.html; this is your reader, right?


message:
Alternative to delay function

I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour.

Here is the link to the example:

https://www.arduino.cc/en/Tutorial/AnalogWriteMega

Here is my code:

    int currmillis = 0; //used in my function to find the current millis()
    int prevmillis = 0; //used to hold previous value of currmillis
    int boolval = 0;    //used to control whether to write the brightness value to the led or not
    int time = 0;     //used in the delay function, difference between currmillis and prevmillis

    int timeloop(int); //the function i wrote, it is at the bottom of the code

    void setup() {
      Serial.begin(9600);
      for ( int i = 2; i <= 13; i++)
      {
         pinMode(i,OUTPUT);
      }
    }//Setting the pins to output and allowing serial communication.

    void loop (){

      for ( int thisPin = 2; thisPin <= 13; thisPin++ ) //to move from one led to the next
      {

        for ( int brightness = 0 ; brightness <= 255; brightness++) //change the brightness of the led
        {

          boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led

          if (boolval >= 2){
            analogWrite(thisPin, brightness);
          }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led.

        }

     for ( int brightness = 255 ; brightness >= 0 ; brightness--)
        {
          boolval = timeloop(2);

          if (boolval >= 2){
            analogWrite(thisPin, brightness);
          }
        }
              timeloop(100); // a delay of 100 ms using the function
      }
    }

    int timeloop (int interval){ // the delay function

      do{
       prevmillis = currmillis; //hold previous value
       currmillis = millis(); //find current value
        time = (currmillis-prevmillis);
      }while(time < interval);

      return time;
    }

Thank you

body:
What's the point? Why rewrite `delay()`?

Anyway:

    int timeloop (int interval){ // the delay function

      do{
        prevmillis = currmillis; //hold previous value
        currmillis = millis(); //find current value
        time = (currmillis-prevmillis);
      }while(time < interval);

      return time;
    }

In every iteration of that loop you are updating `prevmillis`. So you will never reach the wanted delay interval.

Apart from the fact that you may as well use the inbuilt `delay` rather than writing your own, and getting it wrong.

---

> I am trying to make a workaround for the delay function

Why?

[The XY Problem](http://xyproblem.info/)


body:
    // You don't need to return anything since it's just a delay
    // also I changed the parameters to long ints because millis()
    // returns a long int
    void timeLoop (long int startMillis, long int interval){ // the delay function

     // this loops until 2 milliseconds has passed since the function began
     while(millis() - startMillis < interval){}
    }

    // Your call for a 2 millisecond delay would be
    timeLoop(millis(), 2);

Also the leds may be acting weird because this schematic is wrong. As you can see one of the led's anode isn't connected to ground. It's circled in red.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/iH0su.png

If you really want it to return something you could use this:

    long int timeLoop (long int startMillis, long int interval){ // the delay function

     while(millis() - startMillis < interval){}
     return millis() - startMillis;
    }

But it really isn't needed.


body:
Depending on what you want the alternative function to do, there are a megaton of timer libraries at the [Arduino playground][1]. One of them is likely to provide what you need.

  [1]: http://playground.arduino.cc/Main/LibraryList#Timing


message:
Multiple If statements

I am using following code for my arduino project in which i have to control a dc motor using arduino uno via text messages.
my question is that i have used multiple number of 'If' statements and only one else statement at the last, i compiled this code and gives no error, is it ok to use multiple If statements one after another without using else after each if?

    #include <LiquidCrystal595.h>
    #include <GSM.h>

    GSM gsmAccess;
    GSM_SMS sms;
    char sendernumber[20];
    int Enable_m=11;
    int Control_2=12;
    int Control_7=10;
    LiquidCrystal595 lcd(7,8,9);
    void setup()
    {
       Serial.begin(9600);
       pinMode(Enable_m,OUTPUT);
       pinMode(Control_2,OUTPUT);
       pinMode(Control_7,OUTPUT);

       digitalWrite(Enable_m,LOW);
       digitalWrite(Control_2,LOW);
       digitalWrite(Control_7,LOW);

       lcd.begin(16,2);
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Hello");
       lcd.setCursor(0,1);
       lcd.print("Everyone");
       delay(2000);

       while (!Serial)
          Serial.println("SMS Messages Receiver");
       boolean notConnected = true;
       while(notConnected)
       {
          if(gsmAccess.begin("0000")==GSM_READY)
             notConnected = false;
          else
          {
             Serial.println("Not connected");
             delay(1000);
          }
       }
       Serial.println("GSM initialized");
       Serial.println("Waiting for messages");
    }

    void loop() {
       // put your main code here, to run repeatedly:
       char c;
       int val=0;
       val=digitalRead(Enable_m);
       if (val==LOW){
          digitalWrite(Enable_m,HIGH);
       }
       if (sms.available())
       {
          Serial.println("Message received from:");
          sms.remoteNumber(sendernumber, 20);
          Serial.println(sendernumber);

          if(sms.peek()=='#')
          {
             Serial.println("Discarded SMS");
             sms.flush();
          }
          while(c=sms.read())
             if(c=='motoroff'){
                analogWrite(Enable_m, 0);
                digitalWrite(Control_2,LOW);
                digitalWrite(Control_7,LOW);

             }
          if(c=='motoronclockwise'){
             analogWrite(Enable_m, 255);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          if(c=='motoronanticlockwise'){
             analogWrite(Enable_m, 255);
             digitalWrite(Control_2,HIGH);
             digitalWrite(Control_7,LOW);
          }
          if(c=='speedhalf'){
             analogWrite(Enable_m, 128);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          if(c=='speedquarter'){
             analogWrite(Enable_m, 65);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          if(c=='speed75'){
             analogWrite(Enable_m, 192);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          else{
             digitalWrite(Enable_m,HIGH);
             Serial.print(c);
          }
          Serial.println("\nEND OF MESSAGE");
          sms.flush();
          Serial.println("MESSAGE DELETED");
       }

    }

body:
Two things:

1. The `else` will only be subject to the last `if` being false, the rest of the `if` statements are completely separate and can affect the `else` in no way whatsoever.  To chain them you need `if (...) { blah blah } else if (...) { blah blah }` etc.
2. You cannot compare characters and strings like that (and in fact they're not even strings, they're lots of characters squeezed into a single character through the use of the wrong kind of quotes).

So basically no, your whole program there is completely wrong and won't do what you think it will and you need to completely re-thing how it works.

Some tips:

* Use `strcmp()` to compare strings.
* If reading strings from serial store them in character *arrays* not a single character.

You might find this useful:

* http://hacking.majenko.co.uk/reading-serial-on-the-arduino
* http://hacking.majenko.co.uk/the-evils-of-arduino-strings


body:
If you intend each `if` statement to be executed, regardless of the whether the prior one(s) did, then yes, they do not require `else` clauses.

If you mean to try each condition until you find one that is true, and execute that one and only that one, then the second and subsequent `if`s need to be `else if`s. The final one may be just an `else`, if you want a catch-all clause; or an `else if` if it is possible that none of the clauses might need to be run.

Update: To execute at most one clause, you need to use `if`, some `else if`s, and maybe a final `else`.

If you're trying to match strings, you can use an array of strings or use literal strings as you've tried to do. Strings have to be enclosed in double-quotes (`"`) however, not the single quotes you've used. And the variable `char c;` you tried to use to hold the SMS message is really only one character. You'll need to make it an array of characters such as `char c[140+1];`,  the size of the longest SMS message + one more for a  zero-character string-terminator. C doesn't directly compare strings as simple variables so `==` and `!=` won't work here. You'll need to compare them with strcmp().


body:
    #include <LiquidCrystal.h>
    #include <GSM.h>

    GSM gsmAccess;
    GSM_SMS sms;
    char sendernumber[20];
    int Enable_m=11;
    int Control_2=12;
    int Control_7=10;
    LiquidCrystal lcd(7,8,9,8,1,2,3,4,5,6);

    void setup()
    {
       Serial.begin(9600);
       pinMode(Enable_m,OUTPUT);
       pinMode(Control_2,OUTPUT);
       pinMode(Control_7,OUTPUT);

       digitalWrite(Enable_m,LOW);
       digitalWrite(Control_2,LOW);
       digitalWrite(Control_7,LOW);

       lcd.begin(16,2);
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Hello");
       lcd.setCursor(0,1);
       lcd.print("Everyone");
       delay(2000);

       while (!Serial)
          Serial.println("SMS Messages Receiver");
       boolean notConnected = true;
       while(notConnected)
       {
          if(gsmAccess.begin("0000")==GSM_READY)
             notConnected = false;
          else
          {
             Serial.println("Not connected");
             delay(1000);
          }
       }
       Serial.println("GSM initialized");
       Serial.println("Waiting for messages");
    }

    void loop() {
       // put your main code here, to run repeatedly:

       // I chose 160 since that is max size for sms
       char message [160];
       // this fills message with null characters
       memset( message, '\0', sizeof(char)*160 );

       int val=0;
       val=digitalRead(Enable_m);
       if (val==LOW){
          digitalWrite(Enable_m,HIGH);
       }
       if (sms.available())
       {
          Serial.println("Message received from:");
          sms.remoteNumber(sendernumber, 20);
          Serial.println(sendernumber);

          // you used single qoutes properly here
          // single qoutes denote a char which is a single character
          if(sms.peek()=='#')
          {
             Serial.println("Discarded SMS");
             sms.flush();
          }

          // this will add the characters to messages[]
          for(int i = 0; message[i] = sms.read(); i++){}

          // I changed this to double qoutes since you need double
          // qoutes to denote a string literal
          if(strcmp(message, "motoroff") == 0){
             analogWrite(Enable_m, 0);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,LOW);
          }
          else if(strcmp(message, "motoronclockwise") == 0){
             analogWrite(Enable_m, 255);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          else if(strcmp(message, "motoronanticlockwise") == 0){
             analogWrite(Enable_m, 255);
             digitalWrite(Control_2,HIGH);
             digitalWrite(Control_7,LOW);
          }
          else if(strcmp(message, "speedhalf") == 0){
             analogWrite(Enable_m, 128);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          else if(strcmp(message, "speedquarter") == 0){
             analogWrite(Enable_m, 65);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          else if(strcmp(message, "speed75") == 0){
             analogWrite(Enable_m, 192);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          // This else will only be executed if the previous if and else if statements are false
          else{
             digitalWrite(Enable_m,HIGH);
             Serial.print(message);
          }
          Serial.println("\nEND OF MESSAGE");
          sms.flush();
          Serial.println("MESSAGE DELETED");
       }

    }

So I've made some edits to your code. For example this code `'motoronanticlockwise'` isn't correct. Single quotes are used for `char` data types and double quotes are used for string literals. You should use double quotes since there are multiple characters `"motoronanticlockwise"`. Also as Majenko said you would have to use `strcmp()` in order to compare `c-strings`
c-strings are `char` arrays that have a null terminator `'\0'`. Also `strcmp()` returns `0` if the two strings are equal.

Your last `else` statement will only executed if the previous `if` statement is `false`. It seems like you only want it to execute if **all** of the previous `if` statement are false. To do this you make the first `if` statement and then make a chain of `if else` statements followed by a single `else` statement. You can have a single `if` statement with no `else` or `if else` statements however, if you want `else` or `if else` statements then you need to have an `if` statement. I've made the necessarily edits to your code already.

Lastly, this part of the program is the biggest problem `while(c=sms.read())` This is because `sms.read()` returns a `char` so you can only read the sms message one character at a time. To do this properly you should make a character array and store the values returned by `sms.read()` in it. This can be done like this

    char message [160]; // I chose 160 since that is max size for sms
    memset( message, '\0', sizeof(char)*160 ); // this fills message with null characters
    // this will add the characters to messages[]
    for(int i = 0; message[i] = sms.read(); i++){}

I am using a `for` loop to iterate through `message[]`.

Try the above and get back to me if there are any problems with it.


message:
How do you write to a free location on an external EEPROM?

I want to log GPS positions to an external EEPROM over I2C.

For example:
Latitude: 51.0000
Longitude: 4.0000

If I remove the decimal place then each of these addresses would consume up to two bytes each.

My question is: ***How can I log each new set of GPS data to a new memory address on the EEPROM each time?***

Bearing in mind that the Arduino might be switched off between entries.

body:
You could assign the first byte(s) of the EEPROM as the address of the next free location in which to store GPS coordinates, and update it before the Arduino sleeps. At wake-up, retrieve the address.

You could keep the pointer in RAM, too; RAM keeps its contents across a sleep. But using EEPROM would even let you power off the Arduino, and still pick up where you left off after the power-up reset. (Of course, other parts of your program would have to be restart-tolerant as well; I'm just looking at the coordinate storage here).

As an aside, two bytes isn't sufficient to store a GPS coordinate to four decimals unless their range is limited such that you can scale them into [0 - 65535].


body:
The trick you are looking to implement here is the ability to look through the EEPROM and say "This is the last place I wrote to - I will write to the next place now."

There's two ways of doing it, the easy way and the right way.

The easy way is to maintain a single address in the EEPROM that says where you wrote to last.  If you are trying to implement some form of wear levelling to extend the life of your EEPROM then this would basically negate it, since that one cell in the EEPROM will wear out before the rest of it and become useless.  So it's really not a good idea although it may sound like it at first.

The *right* way to do it is to store *more* information in the EEPROM every time.  Not only do you need to store the data, but also some kind of identifying *sequence* number.

Say you have 4 bytes of data to write each time.  Add a fifth byte to it.  That fifth byte increases by one each time you write.  Before you write you scan through the EEPROM looking at every fifth byte looking for the "end" of the sequence.

For instance, you may end up with (`xx` is your data bytes) in hexadecimal:

    00: 00 xx xx xx xx
    05: 01 xx xx xx xx
    0A: 02 xx xx xx xx
    0F: 03 xx xx xx xx
    14: FF FF FF FF FF

You see that at address 0x14 the nice sequence of numbers breaks.  Therefore your next write must be at that point.  Now, if you then loop through the EEPROM many times after a while, you may end up with something that looks like this:

    00: FE xx xx xx xx
    05: FF xx xx xx xx
    0A: 00 xx xx xx xx
    0F: 01 xx xx xx xx
    14: 58 xx xx xx xx

You can see a clear sequence here of `0xFE 0xFF 0x01` where they increase by 1 each time (0xFF + 1 = 0x00) so you can see that you have looped through your sequence numbers. You don't care though because it's still just plus one.  Only when you get the jump from 0x01 to 0x58 does the sequence break, so you know where the last write would have been.

There are only a couple of small gotchas here:

1. You can only use 5*n cells in the EEPROM since the last 5-byte packet of data may not fit within the last bit of EEPROM (say it's a 1024 byte EEPROM you would have room for 204.8 packets - so 204 packets and 4 bytes left over).
2. You must ensure that you don't end up with exactly 256 packets fitting in the EEPROM before you loop the address - otherwise the sequence won't "break" so you will never know where the last write was after the first loop.


body:
You can divide EEPROM space into entries and provide each entry with a single "used" bit. You could use a separate byte to store it, or reuse a bit from a byte which is not completely used by your data.

Suppose you start with EEPROM willed with zeroes, and you decide that the first byte of each entry holds the "used" bit in the LSb. When you log coordinates the first time, you'll have:

     /---"used"
    01 51 00 00 04 00 00
    00 00 00 00 00 00 00
     \---"free"
    ...
    00 00 00 00 00 00 00

(of course, you don't have to store GPS coordinates as [BCD](https://en.wikipedia.org/wiki/Binary-coded_decimal), it's just an illustration).

Note that as you add entries, it's trivial to keep track of the last one: just check the entries in sequence until you find a "free" one and go back one step. Also note that the first entry is always "used".

This will go on until all your entries are "used":

    01 51 00 00 04 00 00
    01 52 00 00 05 00 00
    ...
    01 53 00 00 06 00 00

At this point (when you have to write new data but there are no "free" entries), you start writing from the first entry again, inverting the value of the "used" bit:

     /---"used"
    00 54 00 00 07 00 00
    01 02 00 00 05 00 00
     \---"free"
    ...
    01 53 00 00 06 00 00

(remember that the first entry is always "used"? Thanks to this, it's possible to simply swap the values representing "used" and "free" entries without actually erasing anything).

To sum up, the algorithm is:

- read the "used" bit from the first entry
- scan entries until the value of the "used" bit changes, or until you reach the end.
- to read the last logged data, use the last "used" entry
- to write new data, use the first "free" entry. If there are no "free" entries, start from the beginning, inverting the "used" bit.


body:
The question asks specifically about EEPROM (E2) and many of the answers point out or attempt to address E2's main limitation: limited # of write operations. Not mentioned is E2's slow speed. Its is best suited for storing infrequently modified data such as-built- or setup parameters such device calibration data and features of a device's external operating environment. Its only real advantage over other solutions is that it may already exist on your MCU - Atmega 328, for instance.

The new(er) kid on the block for non-volatile data storage is Ferroelectric RAM - FRAM. Write times are on the order of 30 times faster, at 150ns, and endurance is claimed to be 10^12 writes, or 10 million TIMES the endurance of E2. I've built a data logger that uses a ring-buffer in FRAM to store periodic data samples and write them on request.

The same techniques proposed in the answers for E2 will work equally well in FRAM with the additional advantage that you can ignore the complications meant to work around E2's limited write-endurance.

And by way of disclaimer: I don't sell this this stuff or have any other interest in it. But I do use it and it works like it says on the box.

[Adafruit makes these][1] on a breakout board in a couple of variations - size and serial-bus type - that are sold by them and other retailers. The link is for an 8K-byte, SPI-bus board.

  [1]: https://www.adafruit.com/product/1897