message:
Servo Driven Through Custom Library Not working Properly

I'm a little new to Arduino, but not to programming or electronics in general.  I'm working on a library that will be more fleshed out later, but I'm having issues getting the basics working properly.

The following code produces the desired behavior if a servo is attached to pin 3:

    #include <Servo.h>

    Servo myServo;

    void setup() {
      myServo.attach(3);
    }

    void loop() {
      myServo.write(1);
      delay(1000);
      myServo.write(45);
      delay(1000);
      myServo.write(90);
      delay(1000);
      myServo.write(135);
      delay(1000);
      myServo.write(180);
      delay(1000);
    }

However, when I try to implement similar functionality in my own library the servo locks and just sort of grinds.  Here's the header file:

    #ifndef MotorControl_h
    #define MotorControl_h

    #include "Arduino.h"
    #include "Servo.h"

    class MotorControl
    {
      public:
        MotorControl(int north, int south, int west, int east);
        void setNorth(int value);
        void setSouth(int value);
        void setWest(int value);
        void setEast(int value);
        int getNorth();
        int getSouth();
        int getWest();
        int getEast();
      private:
        Servo _north;
        Servo _south;
        Servo _west;
        Servo _east;
        int _northVal;
        int _southVal;
        int _westVal;
        int _eastVal;
    };

    #endif

And here's the .cpp file:

    #include "Arduino.h"
    #include "MotorControl.h"
    #include "Servo.h"

    MotorControl::MotorControl(int north, int south, int west, int east)
    {
      _north.attach(north);
      _south.attach(south);
      _west.attach(west);
      _east.attach(east);
      _northVal = 0;
      _southVal = 0;
      _westVal = 0;
      _eastVal = 0;
    }

    void MotorControl::setNorth(int value)
    {
      _north.write(value);
      _northVal = value;
    }

    void MotorControl::setSouth(int value)
    {
      _south.write(value);
      _southVal = value;
    }

    void MotorControl::setWest(int value)
    {
      _west.write(value);
      _westVal = value;
    }

    void MotorControl::setEast(int value)
    {
      _east.write(value);
      _eastVal = value;
    }

    int MotorControl::getNorth()
    {
       return _northVal;
    }

    int MotorControl::getSouth()
    {
      return _southVal;
    }

    int MotorControl::getWest()
    {
      return _westVal;
    }

    int MotorControl::getEast()
    {
      return _eastVal;
    }

And finally, the code using the above library which should produce the same behavior as the code up top, but does not:

    #include <MotorControl.h>

    MotorControl mc(3, 5, 6, 9);

    void setup() {}

    void loop() {
      mc.setNorth(1);
      delay(1000);
      mc.setNorth(45);
      delay(1000);
      mc.setNorth(90);
      delay(1000);
      mc.setNorth(135);
      delay(1000);
      mc.setNorth(180);
      delay(1000);
    }

I'm not sure what else to add ... this is running on an Uno R3.

Edit:  This is interesting.  I've tried the code from this example:
https://arduino.stackexchange.com/questions/1216/how-do-i-initialize-a-servo-object-in-my-own-library
which works out just fine.  I'm still not sure that I see what I'm doing incorrectly here.  I see the differences between my code and the example, but not how they are causing problems.

If it's worth mentioning, I've also stored my library in the libraries folder.  Just throwing out any random detail I can think of.

body:
In C++, when an object is declared as a member of another object, the **constructor method of the inner object must be called explicity** (see [constructors and member initializer lists][1]).

In your code, properties of _Servo_ type can be constructed within the header of the _MotorControl_ constructor:

    MotorControl::MotorControl(int north, int south, int west, int east)
        : _north(), _south(), _west(), _east()
    {
      _north.attach(north);
      _south.attach(south);
      _west.attach(west);
      _east.attach(east);
      _northVal = 0;
      _southVal = 0;
      _westVal = 0;
      _eastVal = 0;
    }

  [1]: http://en.cppreference.com/w/cpp/language/initializer_list


sender: user

sender: assistant

body: When you create your instance at global scope then you have no control over when exactly the constructor gets called.  If it gets called before init() runs then your attach lines won't work out.  You should have a begin method in your class that handles attaching the servos and call that method from setup.


message:
Can you tell me if this circuit will work?

[![enter image description here][1]][1]
Here's an image of my circuit diagram. There are 8 9g servos connected to the arduino gpio pins. The servos have an external power supply of 3 volts (may vary depending on the voltage requirement of the 9g) and the arduino is powered through an adaptor. Is this a convenient way of doing it? Have I gone wrong somewhere? I am new to circuit designing so I am confused.

Thank you! :)

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

body:
These servo are driven off of a PWM signal. This means that you need to connect the control line to a pin that is capable of PWM.

For the Uno it is D3, D5, D6, D9, D10 & D11.

Unfortunately there are only 6 PWM capable pins and you need 8.

You could consider [bit banging][1] the PWM for the 7th & 8th motor.

Alternatively, if two of the motors are to be driven exactly the same, they could share the PWM control line between them.

If you need to control each motor separately (without bit banging) you may have to upgrade to a [Arduino Mega 2560][2]. The Mega has 15 PWM channels.

An Arduino example of controlling the servo motor can be found in the Libraries section of the Arduino website.
https://www.arduino.cc/en/Tutorial/Knob

  [1]: https://en.wikipedia.org/wiki/Bit_banging
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560


message:
How to break out of a loop if it is contained in a function

I am trying to figure out how to break out of a loop if it is being called from a function.  I have a similar post, [here][1], that I've decided to do something with the Arduino onboard LED, to isolate it from the NeoPixels Library and it is giving me the same issue.  The answers I have received there have been helpful but something is still puzzling me.

Using serial from the Arduino to my PC, the below "Example 1" code, can break out of a local loop successfully (and immediately) when the Arduino received keyboard input with key "2".

    //Example 1
    int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
    char rx_byte = 0; // variable to hold serial input from console;
    int count = 0; // placeholder for incrementing during debugging of loops

    void setup() {

      Serial.begin(115200);

      pinMode (ledPIN, OUTPUT);

    }

    void loop() {

      if (Serial.available() > 0) {    // is a character available?
        rx_byte = Serial.read();       // get the character

        // check if a number was received
        if ((rx_byte >= '0') && (rx_byte <= '9')) {
          switch(rx_byte) {
            case '1':
              Serial.println("You've entered: 1");
              for (int i; i <=5000; i++) {
                rx_byte = Serial.read(); // must read character again
                if (rx_byte == '2') {
                  Serial.println("Quitting...");
                  digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
                  break;
                }
                else {
                  Serial.println(i);
                  digitalWrite(ledPIN, HIGH); // turn LED pin 13 on
                }
              }
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              break;

          }
        } // end: if (Serial.available() > 0)
      }
    }

From what I've been told, you shouldn't necessarily perform a "serial.read()" inside of a loop.  However, if I do not include that in the for loop, it does not allow for any further input.

Since "Example 1" works, I am now trying to accomplish the same principle, but, this time, when calling a function which contains its own independent loop of course.  I've spent countless hours trying to resolve this.

I was under the impression that I could use a while loop within "void loop()" and call in a function which also contains a loop, then be able to break it from the while loop.  When attempting this various ways, the for loop within the function seems to blink the LED 10+ times and totally ignores my keystroke "2" to break the loop and is now infinite.  I know I could just put the for loop up in "void loop()" and it would work to break out similar to Example 1, but I'm sure it can be broken from a function as well.  I will eventually have similar functions that will contain parameters.

How would I go about doing this the correct way?

Below is "Example 2" that I am trying to break from the function.  I'm assuming it's an issue with doing it from the while loop?

Again, any assistance is greatly appreciated.

    //Example 2
    int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
    char rx_byte = 0; // variable to hold serial input from console;
    int count = 0; // placeholder for incrementing during debugging of loops

    void setup() {

      Serial.begin(115200);

      pinMode (ledPIN, OUTPUT);

    }

    void loop() {

      if (Serial.available() > 0) {    // is a character available?

        rx_byte = Serial.read();       // get the character
        boolean forceTerminate = false;

        // check if a number was received
        if ((rx_byte >= '0') && (rx_byte <= '9')) {

          switch(rx_byte) {
            case '1':
              Serial.println("You've entered: 1");
              while(forceTerminate == false) {
                rx_byte = Serial.read(); // must read character again
                if (rx_byte == '2') {
                  Serial.println("Quitting...");
                  digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
                  forceTerminate = true;
                  break;
                }
                else {
                  //count = count+1;
                  //Serial.println(count);
                  blinkPIN13(); // FUNCTION: blinkPIN13
                }
              }
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              break;

          } // end: switch(rx_byte)

        }

      } // end: if (Serial.available() > 0)

    }

    /************************************************************************************
     * FUNCTION for blinking LED located on PIN 13 to the state of ON(1)/OFF(0)
     ************************************************************************************/
    void blinkPIN13() {

      for (int i; i <=10; i++) {
        digitalWrite(ledPIN, HIGH);
        delay(1000);
        digitalWrite(ledPIN,LOW);
        delay(1000);
      }

    }

  [1]: https://arduino.stackexchange.com/questions/31596/arduino-serial-response-is-slow-when-in-while-loop/31597#31597

body:
To tell a function-caller what to do when the function exits, have the function return a status value.  You can do this at multiple levels.  For example:

    byte doOtherStuff(int howLong) {
      digitalWrite(ledPIN, HIGH);
      delay(howLong);
      if (doneDoing()) return false;
      digitalWrite(ledPIN,LOW);
      delay(howLong);
      return !doneDoing();
    }

    void loop() {
      while(doMore) {
        doStuff();
        for (byte i=0; i<9 && doMore; ++i) {
          doMore = doOtherStuff(1234);
        }
        if (doMore) {
          doMoreOtherStuffInWhile();
        }
      }
    }


message:
It seems like the math of arduino is off

*[SOLVED] By changing the offset for the incoming data into `int16_t` type there won't be any rounding errors and the values I'm getting are all back to zero in the sensor its base position*

This is my first project where I use Arduino.

Until today everything went good with the Arduino Pro Mini (3.3v).
But as of today I got a bit of a weird problem.
I am using a MPU gy-521 (doesn't really matter) and I'm working on calculating the actual movement.

The problem which occured is that I'm using a deadzone to negate the smallest numbers (I know, this isn't the right way to use data). The way I negate the numbers is with the following code

    // Check deadzone values
      if (ax+axo < adz && ax+axo > -adz) ax = -axo;
      if (ay+ayo < adz && ay+ayo > -adz) ay = -ayo;
      if (az+azo < adz && az+azo > -adz) az = -azo;

      if (gx+gxo < gdz && gx+gxo > -gdz) gx = -gxo;
      if (gy+gyo < gdz && gy+gyo > -gdz) gy = -gyo;
      if (gz+gzo < gdz && gz+gzo > -gdz) gz = -gzo;

ax is accelerometer data over the x-axis, axo is the offset, adz is the accelerometer deadzone.

gx is gyroscope data over the x-axis, gxo is the offset, gdz is the gyroscope deadzone.

All of the other letters are the same, for different axis.
After getting the values within the offset basically set to 0 with the offset I'm doing the following.

    // Calculate acceleration
      axa = (ax+axo) / aFactor * g;
      aya = (ay+ayo) / aFactor * g;
      aza = (az+azo) / aFactor * g;

      gxa = (gx+gxo) / gFactor;
      gya = (gy+gyo) / gFactor;
      gza = (gz+gzo) / gFactor;

The a- and gFactor are mentioned in the datasheet, but these values should all be 0 if the value of axis plus the offset is within the deadzone.
The problem is that I'm not just getting 0.00 values.
I'm also getting -0.00 and 0.01.

    0.00  0.00  -0.00  0.00  0.01  0.01

Could someone enlighten me about what's wrong in my situation or if this is just a Arduino issue.

*[EDIT]*

The data originally from the sensor is from type int16_t (ax, ay, az, gx, gy, gz) and the other variables are doubles.

The values which are off are always the same ones: Accelerometer Z, Gyroscope Y and Z.

body:
If your program is basically working but gives you rounding errors, it can be that you are facing some problems related to conversion from floating-point to binary or reverse. It is a very common problem in computer science. For example, the decimal number `0.1` has no exact binary  representation, it is infinite. For more information, you can read these pages:

http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html

In order to solve your problem, you can try to apply appropriate rounding to your results and if possible avoid mixing different data types and use `double` only if absolutely needed (which I guess is the case in your application).


message:
Data acquisition/logging question

I want to use an Arduino Uno for a data-acquisition purpose.

Normally adhoc data acquisition boards can record each sample at a desired sampling rate. So that I can plot all the samples recorded. I want to do the same sort if thing with Arduino.

I want to record 30 minutes of analog voltage input at 4kHz sampling rate and record all the samples taken to a PC.

And at the end I want to be able to plot the data with all samples not the averages ect.

Is there an easy workaround for this?

body:
This question is actually two or three different questions.

To the first: is it possible to record 30 minutes of data with an arduino uno at 4KHz: no.  Assuming even that you are only taking 1 byte of data at a time, the uno only has 2K of RAM, so you'd be out of RAM in under a second.

To the second: can you instead send this data to a PC at the desired rate: possibly, depending on how much data you are taking.  If it's just a single analog channel, then you can most likely do it.  Anything more and I doubt it.  The problem is that you'll simulutaneously have to read the analog at the correct time AND send the data to the PC, presumably over the serial.  As long as you use Serial.write, NOT Serial.print, then your UART should be more than fast enough at high baud rates to handle a single channel with minimal overhead.  However, that would mean that you have to reconstruct the data on the PC, but that's the third question, to which I shall turn shortly.

If you need absolute real-time operation, then you need to use timer interrupts, which are not native to the Arduino libraries, if I recall correctly.  However, a quick google for "Arduino timer interrupt" leads me here: http://playground.arduino.cc/Code/Timer1, which is where you should start.

In terms of plotting the data: that's not an Arduino problem, that's a problem for whatever you choose to use to collect and analyze your data.  I suggest Excel, since it's relatively common, or Google Sheets, since it's free.  If you have access to Matlab, though, that's a much more powerful program.  Either way, that is off topic for this forum.


body:
Here is a program I wrote that follows an approach somewhat similar to
Michael Stachowsky's answer:

* The ADC is configured with the prescaler set to 128 (just like the
  Arduino core does), which gives a 104 µs conversion time,
  significantly shorter than the 250 µs sampling period you want.
  The first conversion takes longer, and it is discarded.

* It is also configured an auto-trigger mode, and the timer 1 overflow
  flag is selected as its trigger source.

* The timer 1 is configured to loop every 500 × 8 = 4000 CPU cycles
  (clocked at F\_CPU / 8, with TOP = 499), which
  provides the required 250 µs sampling period. It is set in a PWM
  mode even though the PWM outputs are not used, simply because in this
  mode the overflow flag is set every time the timer loops.

* An interrupt is triggered every time an ADC conversion is complete.
  The interrupt service routine clears the timer overflow flag (this is
  required because the ADC is triggered by the rising edges of this
  flag), saves the result in a global variable and sets a global flag.

* The main loop waits for that flag and sends the data through the
  serial port, in binary, LSB first:
    - the sample number modulo 64 (6 bits)
    - the sample value (10 bits).

* The serial port runs at 115.2 kb/s, it can then transmit the two bytes
  of data in about 174 µs, which is less than the sampling period.

* The sample numbers, and a 16-byte preamble can be used as a sanity
  check by the receiving end.

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

    #include <avr/interrupt.h>

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

        // Transmit preamble.
        for (int i = 0; i < 16; i++)
            Serial.write(0xff);

        // Start the ADC.
        ADMUX  = _BV(REFS0)   // reference = Vcc
               | 0;           // input = ADC0
        ADCSRA = _BV(ADEN)    // enable the ADC
               | _BV(ADSC)    // start first conversion
               | _BV(ADPS0)   // prescaler = 128,
               | _BV(ADPS1)   // ditto
               | _BV(ADPS2);  // ditto

        // Wait for the first conversion to complete.
        loop_until_bit_is_set(ADCSRA, ADIF);

        // Wait for the preamble to be fully transmitted.
        Serial.flush();

        // Stop timer 1.
        TCCR1A = 0;
        TCCR1B = 0;

        // Configure the ADC in auto-trigger mode.
        ADCSRA |= _BV(ADATE)   // enable auto-trigger
                | _BV(ADIF)    // clear interrupt flag
                | _BV(ADIE);   // enable interrupt
        ADCSRB  = _BV(ADTS1)   // trigger source = timer 1 overflow
                | _BV(ADTS2);  // ditto

        // Configure Timer 1.
        ICR1   = 500 - 1;     // period = 500 * 8 CPU cycles
        TCCR1A = _BV(WGM11);  // mode 14: fast PWM,
        TCCR1B = _BV(WGM12)   // ... TOP = ICR1,
               | _BV(WGM13)   // ... overflow flag set on TOP
               | _BV(CS11);   // clock at F_CPU / 8
    }

    volatile uint16_t reading = 0xffff;
    volatile bool reading_available;

    ISR(ADC_vect)
    {
        TIFR1 |= _BV(TOV1);    // clear timer overflow flag
        uint16_t x = reading;  // work on a copy of the reading
        x &= ~0x03ff;          // remove previous ADC value
        x |= ADC;              // add current ADC value
        x += 0x0400;           // increment sample number
        reading = x;
        reading_available = true;
    }

    void loop()
    {
        // Wait for a reading to be available.
        while (!reading_available) ;

        // Grab a copy.
        uint16_t x = reading;
        reading_available = false;

        // Transmit, LSB first.
        Serial.write(x >> 0);  // low byte
        Serial.write(x >> 8);  // high byte
    }

How you deal with the data on the receiving end (save to file, skip
preamble, check sample number consistency, extract sample values, plot
them...) is up to you. You can use whatever language and tools you want.
It is _not_ an Arduino-related question.

**Addendum**: More about the binary format used.

There is a preamble consisting of 16 `0xff` bytes. This can be useful
because it is not uncommon to get in one file a mix of data from two
different runs of the program. The buffering of the serial port on the
PC can lead to this happening. If you do not want that preamble, remove
the two lines right after the “Transmit preamble.” comment.

Then there is a continuous stream of 16-bit unsigned integers
(`uint16_t`), transmitted LSB first (i.e. little endian). The byte order
can be changed by swapping the two `Serial.write()` by the end of the
program.

Each of these integers contains an ADC reading in the lower 10 bits and
a sample number in the upper 6 bits. The sample number can be extracted
by right-shifting (`x >> 10` in C) and could be used as a sanity check
(the number should increment by 1, modulo 64, from one sample to the
next). The ADC reading can be extracted by masking out the sample number
(`x & 0x03ff`).

If you do not want the sample numbers, you can simplify the ISR to:

    ISR(ADC_vect)
    {
        TIFR1 |= _BV(TOV1);    // clear timer overflow flag
        reading = ADC;         // read the ADC result
        reading_available = true;
    }

and remove the (now useless) initialization of the `reading` variable.


message:
Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port

Hello is there an Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port?

I've seen simulator online but I can't seem to find a simulator that can be programmed using the Arduino IDE through a Virtual COM port.

body:
One of the option is using Proteus simulator with [Arduino library][1]. You can build the program via Arduino IDE, then export the compiled binary (.hex file). Proteus also provided virtual terminal feature (not Virtual COM).

  [1]: http://www.electronicslovers.com/2015/03/how-to-add-arduino-library-in-to.html


message:
what is the right way to parse JSON to Arduino?

i am trying to Turn an LED from a hosted website, though Arduino using the CC3000 wifi shield. It is working as it should. but i have to questions about optimising my code :

1) the Part where i parse my JSON is kind of sloppy, what is the right way to Parse the code so i can turn the LED on and off when clicking on the website buttons ?

2) i need to keep the arduino connected to the website, so i can always control the LED. Do i need to close the connection at the end ? if so, how can i activate the connection only when clicking the button on the website to active the LED.

    #include <ArduinoJson.h>

    // Include Libraries
    #include <Adafruit_CC3000.h>
    #include <ccspi.h>
    #include <SPI.h>
    #include <string.h>

    // Define Pins
    #define ADAFRUIT_CC3000_IRQ   3
    #define ADAFRUIT_CC3000_VBAT  5
    #define ADAFRUIT_CC3000_CS    10

    // Define Variables
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);

    #define WLAN_SSID       "MyWeb"
    #define WLAN_PASS       ""
    #define WLAN_SECURITY   WLAN_SEC_UNSEC // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2

    uint8_t dhcpTimeout;

    #define host "mygarden.comli.com" // Your domain
    uint32_t ip;
    String path   = "/light.json";
    int port = 80;

    int pin = 9;

    void setup(void)
    {
      Serial.begin(115200);
      delay(10);

      pinMode(pin, OUTPUT);
      pinMode(pin, HIGH);

      // Connect to Wifi
      cc3000.begin();
      Serial.println(F("Initialising the CC3000"));
      if (!cc3000.begin())
      {
        Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
        while(1);
      }

      /* Delete any old connection data on the module */
      Serial.println(F("Deleting old connection profiles"));
      if (!cc3000.deleteProfiles()) {
        Serial.println(F("Failed!"));
        while(1);
      }

      // Connect to Network
      beginning:
      Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
      cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
      Serial.println(F("Connected"));

      //Wait for DHCP to complete
      Serial.println(F("Requesting DHCP"));
      while (!cc3000.checkDHCP()) {
        delay(500);
        Serial.print(F("."));
        dhcpTimeout ++;
        if (dhcpTimeout == 60) {
          Serial.println(F(""));
          Serial.println("DHCP Timeout! Attempting to reconnect.");
          dhcpTimeout = 0;
          goto beginning;
        }
      }
      Serial.println(F(""));
      Serial.println(F("DHCP complete"));

      //get website IP
      ip = 0;
      Serial.print(host); Serial.print(F(" -> "));
      while (ip == 0) {
        if (! cc3000.getHostByName(host, &ip)) {
          Serial.println(F("Couldn't resolve!"));
        }
        delay(500);
      }
      cc3000.printIPdotsRev(ip);
      Serial.println("");
    }

    void loop(void) {

      Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

      client.print(String("GET ") + path + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: keep-alive\r\n\r\n");
      delay(500); // wait for server to respond

      Serial.println(F("----------"));
       while (client.connected()) {
        String response = "";
        bool begin = false;
          while (client.available() || !begin) {
          char c = client.read();
          if (c == '{') {
            begin = true;
          }
          if (begin) response += (c);
          if (c == '"}') {
            break;
          }
          delay(1);

          }
          int start = response.indexOf("light\":\"") + 12;
          int end = start + 3;
          String LED_Control = response.substring(start, end);

          if (LED_Control == "onn") {
            digitalWrite(pin, HIGH);
            Serial.println("LED ON");
          }
          else if (LED_Control == "off"){
            digitalWrite(pin, LOW);
            Serial.println("led OFF");
          }

       }

      delay(1000);
      Serial.println(F("\n\nClosing the connection"));
      client.close();
      cc3000.disconnect();

    }

And this is my JSON output

    {"light": "off"}

body:
Assuming that `String response` will contain the json `{"light": "off"}` and your program is ready to use the [ArduinoJson library](https://arduinojson.org) (`#include <ArduinoJson.h>` on top), a simple solution could be:

**Step1** - declare and initialize `StaticJsonBuffer` object.

    StaticJsonBuffer<80> jsonBuffer;

**Step2** - deserialize the json from `response`.

    JsonObject& root = jsonBuffer.parseObject(response);

**Step3** - if the deserialization doesn't succeed, warn and break,

    if (!root.success())
    {
      Serial.print("parseObject(");
      Serial.print(response);
      Serial.println(") failed");
      break;
    }

**Step4** - otherwise, use json object to get the `LED_Control`.

> Is the json will really contain `{"light": "onn"}` or is a typo ?

 String LED_Control = root["light"];

 if (LED_Control == "onn") {  // 'on' or 'onn' ??
  digitalWrite(pin, HIGH);
  Serial.println("LED ON");
 }
 else if (LED_Control == "off"){
  digitalWrite(pin, LOW);
  Serial.println("led OFF");
 }


body:
If the response from the web server is just a boolean value, the 'right' way would IMHO be to return e.g. just a 0 and 1 instead of JSON encoded data. That saves you from parsing JSON on the Arduino completely. Instead you can simply read one character of the response and check for '0' or '1'.

HTTP is a request-response based protocol and not suitable for staying connected to the server. If you need immediate reaction from the Arduino to server-side changes and your web server supports WebSockets, you could use any of the WebSocket libraries for the Arduino. Otherwise, you can use HTTP and poll the web server at a set interval to get the current value of the switch. And if you don't implement HTTP keep-alive, you will have to close the TCP connection and make a new connection for each HTTP request.


message:
Scan IP address of ESP8266

I am working on a project in which, the mobile app/browser sends HTTP command to ESP8266 in AP mode. The default IP address of ESP is 192.168.4.1. Therefore in order to connect the ESP to WiFi, the command goes like this :- 192.168.4.1/SSID=XYZ/Pass=XYZ.

On connecting to router, the ESP goes into STA mode and Doesn't create AP until WiFi is not found to which it was connected earlier. Now when ESP is connected to router, the router assigns the IP to ESP through which HTTP command will be sent. On Serial monitor, it does show the IP address to which it is assigned, but what if app controls the ESP, there is no serial communication. How will app know the IP address assigned to particular ESP8266? Is there any way app can scan the router? Or any other way to do this? If there are multiple ESP connected to router, how can I identify the IP of particular ESP.

body:
You can hard-code the required IP address for ESP8266. (That may not be possible all the times).
There's a sample code :https://www.arduino.cc/en/Reference/WiFiConfig

If you are not hard-coding IP address, you can read IP address of ESP by using WiFi.localIP() function in Arduino.


body: Have the app send a broadcast UDP packet, and have the ESP listen for such  broadcasts. Now the ESP knows the IP address of the device on which the app is running, and it can somehow let it know its own IP address: perhaps connecting to a particular socket on which the app will listen, or sending a UDP broadcast of its own.


body:
The de-facto standard way for devices to broadcast their IP address to clients is through the Multicast DNS system (mDNS). In this system the server sends a UDP message to a specific multicast group address and clients listen for it so they can work out what is where.

mDNS is also known as Zeroconf or Bonjour depending on who you talk to.

The ESP8266 Arduino core (if you are programming the ESP8266 directly) has mDNS examples with it. If you are using the AT command interface instead, then you will need to read the manual to find how to send UDP packets to multicast addresses.


body:
Regarding mDNS is the solution but unfortunately it has limitation just like currently not supported with Android Platform.

My Suggestion is to keep listen the UDP port on all range of IP address of network as of token and on when you found right reply of UPD packet along with that device IP/MAC/port inside of that replayed packet then you will good to go.

No doubt this will take bit time to done but its only one time or until the IP has been changed.


message:
Arduino Mega Serial2 seems to stop functioning mid-sketch

thanks in advance for the advice.

I've got an Arduino Mega talking to a Cavro XL-3000 pump. After a lot of time I got the arduino successfully controlling the Cavro. However, the big problem I have now is after my Mega sends about a dozen commands, communication breaks down between the two. The Arduino sends commands and gets no response back from the Cavro. I've written code that, when the Arduino gets no response, it tries twice more before terminating the program.

For a while I thought the problem to be pump related. After all, my test code (the vast majority of my code is in a library I created to have the Mega talk to the Cavro pump) simply tells it to move the Cavro between two different positions interminably. But when I reset my arduino, it starts working again. Not when I reset the pump.

Finally, I hooked my logic analyzer up. It turns out that, when I get no response from the pump, it's because no command is reaching the Cavro. I am definitely successfully creating a command packet and sending it using Serial2.write(packet,packet_length).  And though the Arduino is calling these lines of code and thinks data is going out, nothing is actually going out on the TX line. It's like Serial2 gets tired after about a dozen calls and stops shifting out data even though I'm calling Serial2.write.

I'm pretty stumped. I'm clearing the receive buffer after each response, so no overflow there. Each time I send a command I wait until it is fully shifted out before moving on, so no overflow on the write buffer either. If I get no response back from the pump I try two more times. On the last try, I shut down Serial2, begin it again, and wait until it is connected (while(!=Serial2)). But even after I do all this, Serial2.write isn't actually sending out data. My logic analyzer isn't picking anything up.

A simple reset of the Arduino and commands are actually going out again. Logic analyzer picks them up immediately. After about a dozen or so commands (it seems fairly random but never lasts very long), the same thing happens. I swapped out Arduino megas and the same thing occured.

So.

 1. It seems to be a code issue (repeatable on multiple arduino megas)
 2. It does not seem to concern the pump or the rs232 converter
 3. A push of the reset button fixes it temporarily
 4. My logic analyzer snoops in between the arduino and rs232 converter.
 5. Serial2.write(packet, packet-length) is definitely being called.
 6. I have no idea what's happening.

Here is a schematic. Any advice would be appreciated!
[![enter image description here][1]][1]

Here is my test code:

    #include <Hydro.h>

    Hydro pump;
    void setup() {
      Serial.begin(9600);
      Serial2.begin(9600);
      pump.InitComm(0,true,"right");
      Serial.println("Communication initialized");
      delay(5000);
    }

    void loop() {
    //  Serial2.begin(9600);
      //long mil = millis() - 10000;
    //while(true){
      //if(millis() > mil + 10000){
        //Serial.println("Sending command...");

        //byte datastuff[10]={0x02, 0x31, 0x31, 0x41, 0x35, 0x30, 0x30, 0x52, 0x03, 0x27};
        //Serial2.write(datastuff,10);
        //Serial.println("Sending command...ONE");
        pump.AbsoluteMove(0,4000);
        delay(10000);
        //Serial.println("Sending command...2");
        pump.AbsoluteMove(0,9000);
        delay(10000);
        //Serial2.write(new byte[10] {0x02, 0x31, 0x31, 0x41, 0x35, 0x30, 0x30, 0x52, 0x03, 0x27}, HEX);
        //mil = millis();
    }

Here is my library.

    /*
    Hydro.c - Library created for OEM communication with Cavro XL-3000 Pump.

    11/23/2016
    Written for Mega using Serial2, can we tweaked.
    */

    #include "Arduino.h"
    #include "Hydro.h"

    Hydro::Hydro(void){}

    const byte LineSynch = 0xFF;
    const byte StartByte = 0x02;
    byte seq = 0x31; //confirm this
    const byte ETX = 0x03;
    const byte EX = 0x52;
    int length_total = 0;

    //Initializes communication and then sets it to Fine (12000 steps) Control.
    void Hydro::InitComm(int addr, boolean fc, String initdir){
     Serial2.begin(9600);
     Initialize(addr,initdir);
     delay(2000);
     FineControl(addr,fc);
    }

    //Top Level Send Command. First Queries the pump to make sure it's ready for a command.
    //If Pump is ready, passes along actual command to MidCommand.
    void Hydro::SendCommand(int addr, String command){
     byte status = Query(0);
     while(status==false){
      Serial.println("Query: Stat Error: Wait till Pump No Longer Busy.");
      delay(10000);
      status = Query(0);
     }
     Serial.println("Query: Pump Not Busy.");
     MidCommand(addr, command);
     ReadData(false);

    }

    //Executes the actual command by calling command.
    //If no response received (command != true), tries again twice.
    void Hydro::MidCommand(int addr, String command){
     bool response = Command(addr, command);
     if (response == true){}
     else if (response == false){
      //resend
      Serial.println("Command Failed. Resending.");
      bool response2 = Command(addr, command);
      if (response2 == false){
       //shut off
       Serial.println("Second Command Failed.");
       Serial2.end();
       delay(2000);
       Serial2.begin(9600);
       while (!Serial2){
        Serial.println("Waiting for S2 to Connect.");
        delay(1000);
       }
       Serial.println("Connected.");

       bool response3 = Command(addr, command);
       if (response3 == false){
        Serial.println("Final Command Failed.");
        while(true){}
       }
      }
     }
    }

    //Send a Command.
    //Returns True if a response is received from the pump.
    bool Hydro::Command(int addr, String command){
     command.concat("R");
     byte address = 0x31+ addr;
     int length = command.length()+1;
     byte dat[length];

     Serial.print("Command: The string command is: ");
     Serial.println(command);
     command.getBytes(dat,length);

     //Serial.println("Data----");
     //for (int i = 0; i < length; i++){
      //Serial.print("i equals: ");
      //Serial.println(i);
      //Serial.println(dat[i], HEX);
     //}
     //Serial.println("----");
     //Serial.print("Dat Length is: ");
     //Serial.println(length);

     //line sync, stx, add, seq, etc, checksum. 6. 6 + (length.data) == length.
     //Decided to ignore Line Sync. Pump seems to have no problem without it. So 5+length.data.
     length_total=5+(length-1);
     byte packet[length_total];
     int p = 0;

     //packet[p++] = LineSynch;
     packet[p++] = StartByte;
     packet[p++] = address;
     packet[p++] = seq;

     for (int i = 0; i<(length-1); i++){
      //Serial.print("i equals: ");
      //Serial.print(i);
      packet[p++] = dat[i];
      //Serial.print(".  Inserting Data: ");
      //Serial.println(dat[i], HEX);
     }

     packet[p++] = ETX;
     byte checksum = StartByte;

     for (int i = 1; i<length_total-1; i++){
      checksum = checksum^packet[i];
     }
     packet[p++] = checksum;
     int x = Serial2.write(packet,length_total);
     Serial.print("bytes written: ");
     Serial.println(x);
     seq++;

     //print out packet to verify.
     Serial.println("Packet----");
     for (int i = 0; i < length_total; i++){
      Serial.println(packet[i], HEX);
     }
     Serial.println("----");

      //Waits for packet to be fully shifted out.
      //Serial.flush could be used instead.
     while(Serial2.availableForWrite() != 63){
      Serial.println("Command: Waiting to finish sending command...");
      delay(1000);
     }
     Serial.println("Command: Finished Sending.");

     unsigned long time = millis();

     //looks for a response from the pump.
     //returns true if received.
     while(Serial2.available()==0){
      Serial.println("Waiting for Response...");
      delay(1000);
      if (millis() > (time+5000)){
       Serial.println("Resend Command.");
       return false;
       }
     }
     Serial.println("Command: Response Received.");
      return true;
    }

    //Both initialize at half force.
    //Init with volve output to Right or Left.
    void Hydro::Initialize(int addr, String dir){
     if (dir == "right"){SendCommand(addr,"Z1");}
     else if (dir == "left"){SendCommand(addr,"Y1");}
    }

    //If Fine Control is True (active), Resolution is 0-12000.
    //Else If Fine Control is False (deactivate), 0-3000.
    void Hydro::FineControl(int addr, boolean control){
     if (control==true){SendCommand(addr,"N1");}
     else if (control==false){SendCommand(addr,"N0");}
    }

    //See Fine Control for Integer Values
    void Hydro::AbsoluteMove(int addr, int move){
     String mc = "A";
     mc.concat(move);
     SendCommand(addr,mc);
    }

    void Hydro::Execute(int addr){
     SendCommand(addr,"R");
    }

    //Sends a Query for Status.
    //Returns true if Status byte is 60, ready for command.
    bool Hydro::Query(int addr){
     MidCommand(addr,"Q");
     if ((ReadData(true)) != 0x60)return false;
     else return true;

    }

    //True to print out data, false to not.
    //Grabs and returns the Status Byte.
    byte Hydro::ReadData(bool print){
     byte status;
     int i=0;
     if (print == false){
      while(Serial2.available()){
       if (i==3){
        status = Serial2.read();
       }
       else Serial2.read();
       i++;
      }
     }

     else if (print == true){
      while(Serial2.available()){
       if (i==3){
        status = Serial2.read();
        Serial.print("i is: ");
        Serial.print(i);
        Serial.print(". Reading (s): ");
        Serial.println(status, HEX);
       }
       else {
        Serial.print("i is: ");
        Serial.print(i);
        Serial.print(". Reading: ");
        Serial.println(Serial2.read(), HEX);
       }

       i++;

      }

     }
     return status;
    }

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

body:
I'm not a C++ guy, but I have looked at the code and fail to find where some of the index's are set to the proper values (whatever that is.) Some of it may occur during instantiation, but...  Most of these I've seen are index related (out of bounds), so.. As an example, the code sequence of

    for (int i = 0; i < (length - 1); i++)
        packet[p++] = dat[i];

Seems to me, if the bytes (length) of 'dat' is 6 assuming 6 bytes, then the loop will run from 0 to 4.  That would seem to lose 2 bytes? Some of the array indexes are difficult to track for their value, not knowing what you were thinking.

My suggestion is

1.) ensure indexes stay within bounds
2.) ensure every function call (related to problem) is checked for it's expected return status
3.) attempt to ascertain the number of operations that occur before failure.  This may give you a clue about indexes or lead to discover of other problems.

I don't think you have a hardware problem. Intermittent hardware doesn't do this either. This is a software bug, and it's sounds repeatable. Step three may be useful.

Best of luck :)


body:
Difficult to say, but if your last trace is "Final Command Failed." , you are probably stuck in the following infinite loop.

    if (response3 == false){
        Serial.println("Final Command Failed.");
        while(true){}
    }

as @Jack says, you might as well have problems with your bound arrays. You have a lot of "length+1, length-1" scattered everywhere, this is really hard to follow.


message:
RF24 communication between Leonardo and Micro not responding

I have Arduino Leonardo and Micro. I can't manage them to communicate via nRF24L01. I made a receiver and sender sketch to test it and can't see any respond. I tested the same code on two arduino nano and they work fine.

I connected the pins correctly using the ICSP pins in Leonardo and corresponding pins (not ICSP) dedicated for SPI in Micro.

Please could someone tell me what am I missing in porting sketch from nano-nano to leonardo-micro?

Here are the sketches:

PS some additional channels are left to see what I expected from working sketch.

Receiver module:

    //NRF24
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    RF24 radio(9, 10);
    byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

    int channel = 1;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      radio.begin();
      radio.setAutoAck(1);
      radio.setRetries(15, 15);
      radio.openReadingPipe(1, addresses[0]);
      radio.openReadingPipe(2, addresses[1]);
      radio.openReadingPipe(3, addresses[2]);
      radio.openReadingPipe(4, addresses[3]);
      radio.startListening();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while (radio.available()) {
        char theMessage[13];
         radio.read(&theMessage, 13);
         Serial.println(theMessage);
         if(theMessage == "testingsend"){
           //this is removed in nano
          digitalWrite(13,HIGH);
          delay(50);
          digitalWrite(13,LOW);
         }
      }
    }

And the sender:

    //NRF24
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    RF24 radio(9, 10);
    byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

    int channel = 1;

    void setup() {
      // put your setup code here, to run once:
      radio.begin();
      radio.setAutoAck(1);
      radio.setRetries(15, 15);
      radio.openWritingPipe(addresses[channel]);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      char theMessage[13] = "testingsend";
      radio.write(theMessage, sizeof(theMessage));
      memset(theMessage,0,sizeof(theMessage));
      delay(300);
    }

body: Ok I solved the issue, somehow I had to use 10 uF capacitor instead of 4.7 uF


message:
GSM and NFC not working together

I have an Arduino Uno board, Seeed Studio NFC shield v2.1 and, an Arduino GSM shield stacked UNO -> NFC -> GSM, therefore, all the wires are going into pins in the GSM.

I have successfully created a program that measures various sensors on my attached breadboard and then prints them to serial and sends text depending on conditions. I have today added the NFC shield to the middle of the stack (so as to avoid unplugging all the pins in the GSM), now when I run any NFC program, the default ones provided on the serial I get the message "Didn't find PN53x board". However, if I unplug the GSM from on top of it the NFC programs run fine, reading and writing tags.

Is it just that the NFC and GSM will not work together or am I missing something.

Main code

    // Include the GSM library
    #include <GSM.h>

    #define PINNUMBER ""

    // initialize the library instance
    GSM gsmAccess;
    GSM_SMS sms;

    int buttonPin = 13;
    int buttonState = 0;
    int buttonPressed = 0;
    int trigPin = 11;
    int echoPin = 12;
    long duration, cm, inches;
    int greenLED = 6;
    int redLED = 8;
    int buzzerPin = 10;

    int pressurePin = A5;
    int force;

    const int inputPin = A0;
    unsigned int inputSample;
    const int inputWindow = 100;

    void setup() {
      Serial.begin(9600);
      pinMode(buttonPin, INPUT);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(greenLED, OUTPUT);
      pinMode(redLED, OUTPUT);
      pinMode(buzzerPin, OUTPUT);
      pinMode(inputPin, INPUT);
      startUp();
      //setupText();

    }

    void loop() {
      button();
      delay(100);
      if (buttonPressed == 1)
      {
        pressure();
      }
      else if (buttonPressed == 2)
      {
        distance();
      }
      else if (buttonPressed == 3)
      {
        sound();
      }
      else if (buttonPressed == 4)
      {
        pressure();
        distance();
        sound();
      }
    }

    void sound()
    {
      // two variables for minimum and maximum values in window
      unsigned int inputMax = 0;
      unsigned int inputMin = 1024;

      // loop for the window
      for (unsigned int i = 0; i < inputWindow; i++)
      {
        // read in a single value
        inputSample = analogRead(inputPin);
        // get the minimum and maximum value
        inputMin = min(inputMin, inputSample);
        inputMax = max(inputMax, inputSample);
      }
      // send the values on serial
      Serial.print("Min: ");
      Serial.print(inputMin);
      Serial.print("  Max: ");
      Serial.print(inputMax);
      Serial.print("  Diff: ");
      int Diff = inputMax - inputMin;
      Serial.print(Diff);
      Serial.println();
      if (Diff > 30)
      {
        alarm();
        sendText();
      }
      delay(250);
    }

    void pressure()
    {
      force = analogRead(pressurePin);
      Serial.print("The force is: ");
      Serial.println(force);
      delay(250);
      if (force > 400)
      {
        alarm();
        sendText();
      }
    }

    void distance()
    {
      digitalWrite(trigPin, LOW);
      delayMicroseconds(5);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      pinMode(echoPin, INPUT);
      duration = pulseIn(echoPin, HIGH);
      int echo = pulseIn(echoPin, HIGH);
      int trig = pulseIn(trigPin, HIGH);
      Serial.println(duration);
      Serial.println(echo);
      Serial.println(trig);
      cm = (duration/2) / 29.1;
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();
      delay(100);
      if (cm < 5)
      {
        alarm();
        sendText();
      }
    }

    void alarm()
    {
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,2500);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,300);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,2500);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,300);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,2500);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,300);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,2500);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,300);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
      digitalWrite(redLED, HIGH);
      tone(buzzerPin,2500);
      delay(200);
      digitalWrite(redLED, LOW);
      noTone(buzzerPin);
      delay(200);
    }

    void button()
    {

      buttonState = digitalRead(buttonPin);

      if (buttonState == HIGH)
      {
        buttonPressed ++;
        digitalWrite(greenLED, HIGH);
        noise();
        delay(2000);
        digitalWrite(greenLED, LOW);

      }

      Serial.println(buttonPressed);
    }

    void startUp()
    {
      digitalWrite(greenLED, HIGH);
      noise();
      digitalWrite(greenLED, LOW);
      delay(500);
      digitalWrite(greenLED, HIGH);
      noise();
      digitalWrite(greenLED, LOW);
      delay(500);
      digitalWrite(greenLED, HIGH);
      noise();
      digitalWrite(greenLED, LOW);
      delay(500);
      loop();
    }

    void noise()
    {
      tone(buzzerPin, 1000);
      delay(1000);
      noTone(buzzerPin);
    }

    void sendText()
    {
        Serial.println("...");
        Serial.println("...");
        Serial.println("...");
        Serial.println("...");
        Serial.println("...");
        Serial.println("MESSAGE SENT");
        Serial.println("...");
        Serial.println("...");
        Serial.println("...");
        Serial.println("...");
        Serial.println("...");
        delay(4000);
    //  char remoteNum[20];
    //  Serial.println(remoteNum);
    //  // sms text
    //  char txtMsg[200];
    //  Serial.println("SENDING");
    //  Serial.println();
    //  Serial.println("Message:");
    //  Serial.println(txtMsg);
    //
    //  // send the message
    //  sms.beginSMS("07123456789");
    //  sms.print("HELP");
    //  sms.endSMS();
    //  Serial.println("\nCOMPLETE!\n");
    }

    void setupText()
    {
      // initialize serial communications and wait for port to open:
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("SMS Messages Sender");

      // connection state
      boolean notConnected = true;

      // Start GSM shield
      // If your SIM has PIN, pass it as a parameter of begin() in quotes
      while (notConnected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
          notConnected = false;
        } else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      Serial.println("GSM initialized");
    }

Code to be added when at a later date

    #include <SPI.h>
        #include "PN532_SPI.h"
        #include "PN532.h"
        #include "NfcAdapter.h"

        PN532_SPI interface(SPI, 10); // create a PN532 SPI interface with the SPI CS terminal located at digital pin 10
        NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object

        void setup() {
            Serial.begin(9600); // begin serial communication
            Serial.println("NDEF Reader");
            nfc.begin(); // begin NFC communication
        }

        void loop() {

            Serial.println("\nScan an NFC tag\n");
            if (nfc.tagPresent()) // Do an NFC scan to see if an NFC tag is present
            {
                NfcTag tag = nfc.read(); // read the NFC tag into an object, nfc.read() returns an NfcTag object.
                tag.print(); // prints the NFC tags type, UID, and NDEF message (if available)
            }
            delay(2000); // wait half a second (500ms) before scanning again (you may increment or decrement the wait time)
        }

Edit: Added code

body:
You have a resource conflict between your breadboard sensors and the NFC shield.

    int buttonPin = 13;    <= This is SCK
    int trigPin = 11;      <= This is MOSI
    int echoPin = 12;      <= This is MISO
    int buzzerPin = 10;    <= This is chip select

You will have to use different pins for your sensors.


message:
What programming practices should be adopted while coding sketches for Arduino?

What are some of the best programming practices that can be adopted while coding sketches for Arduino, so that it uses the least memory and performance should not suffer from memory outage, and still the code be robust?

From the link: https://www.arduino.cc/en/Products/Compare

I have learned that the Uno has 32 KB of Flash memory. The maximum available is in the MEGA with 256 KB. I think Uno and Mega are the most widely used by people.

body:
Keep in mind that RAM is even less. 32KB is a fair lot of code, since C/C++ is highly efficient. "Don't save **** in RAM."

If you need to load images into a display, save the images on an SD card. And "stream" it to the display. You can read and transmit the bytes one by one, or 10 by 10 or something.

Also, if you need long strings, you can use the "flashStringHelper" to store the string in flash memory. For example: `println(F(”Error message: Couldn't connect to server));`. By using `F()` around the string, you save valuable bytes.

Not using Arduino code, but pure AVR-C/C++, can save you a little also. (Will also save the bootloader piece of memory, if you program directly with a programmer.)

If you use Arduino, know how it works. The Arduino serial library uses ~256 or 500 bytes (I believe) as a buffer. You can change this if you need it for other applications.

Keep in mind that your saving technique depends on what resources are low. If you need to do a lot simultaneously, it's better to write non-blocking code.

But also remember: Don't optimize unless it's actually needed! Or, actually set measurable and realistic requirements, optimizing something to be "as fast as possible" can take infinite amounts of time... Run a google search on "premature optimization" as the old folks in the field like to call it.


body:
Paul covered the most important points. This answer is intended to be a
complement to his.

First, you should keep in mind the general rules, which are more
important than the more specific ones. The general rule for saving RAM
is: be aware of what you are storing, and do not store anything you do
not really need. The general rule for saving flash is: be aware of what
you are doing, and do not do anything you do not really need.

Now, a few specific tips:

Use the `const` qualifier for declaring constants (e.g.
`const int ledPin = 13;`). The compiler will optimize-out the storage of
the constant and use immediate addressing instead.

Use `PROGMEM` for arrays of constants.

Whenever possible, use static memory (globals and `static` locals)
rather than heap allocation (`malloc()` and `new`). This will prevent
memory fragmentation and make the memory usage more predictable (only
the stack holds dynamic memory): you know at compile time, rather than
run time, whether you are low in RAM.

For the same reason, prefer C strings (`char *`) over `String` objects.

Use the C99 types `int8_t` and `uint8_t` whenever 8 bits are enough for
your integer variables.

Use the `static` qualifier for functions that will be used only in the
same source file, especially for functions that are called only from one
place. This gives the compiler more optimization opportunities.

If you need to optimize,
[use `avr-nm`](https://arduino.stackexchange.com/a/20541) to know what is
consuming your precious RAM.


message:
How do I use the Arduino Mega as a 16-bit SPI slave?

I have to interface an Arduino Mega as a slave with a SPI master running at **1 MHz** `SCK`. The master will send and ask for two bytes in a single transaction. I tried using the following code for the Mega. Its intended functionality is to store the master's sent data in `acc` and return local data `ret`, which is simply an integer to be incremented every transaction.

However, while the master data is stored in `acc` (verified through serial output), the data returned to the master is not the value in `ret`. Instead, the first response byte is correct (MSB of `ret`) and the second response byte is just the first byte received by the Mega, which was the value already present in `SPDR`.

How do I send the second byte of `ret` as the second byte of the response? What am I doing wrong?

    // SPI Slave

    #include <SPI.h>

    // return to master
    volatile unsigned int ret;

    // accept from master
    volatile unsigned int acc;

    // MSB/LSB indicator
    volatile byte SB;

    void setup(void)
    {

      ret = 0;
      SB = 0;

      pinMode(MISO, OUTPUT);

      // turn on SPI in slave mode
      SPCR |= _BV(SPE);

      // turn on interrupts
      SPCR |= _BV(SPIE);

      // set CPOL, CPHA modes
      // byte dataMode = 0;
      // SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode;

    }

    // SPI interrupt routine
    ISR(SPI_STC_vect)
    {

      if(SB == 0) {
        acc = SPDR << 8;
        SPDR = ret;
        ret++;
      }
      else {
        acc += SPDR;
        SPDR = ret >> 8;
      }
      SB = (SB + 1) & 0x01;

    }

    void loop(void)
    {
      // interrupt processing only
    }

**Edit** Changed `SCK` from 16 MHz to 1 MHz

body:
You might need to check the Arduino Mega/ATmega2560 product description and SPI slave mode.

> In SPI Slave mode, the control logic will sample the incoming signal
> of the SCK pin. To ensure correct sampling of the clock signal, the
> minimum low and high periods should be: Low period: longer than 2 CPU
> clock cycles. High period: longer than 2 CPU clock cycles.

This implies the maximum SCK in slave mode. 16 MHz SCK would be too fast for an Arduino Mega (at 16 MHz).

Also there is a significant latency to the ISR. To achieve higher slave mode clock frequency:

1. Time between slave mode chip select and clock must be stretched to compensate for the ISR latency.
2. The ISR will need to busy wait for all data (as the Arduino SPI transfer() is implemented).

Cheers!


body:
I'm late to the party, but...

I experienced exactly the same issues having a Arduino Uno as a SPI slave communicating to a Arduino Mega as SPI master. My conclusion is that the slave must take some time to process the SPI transfer of the first byte (your code in the SPI interrupt handler), but the master is not waiting for it. So the transfer of the second byte starts before your handler is completely executed, so the master receives the same byte again.

In my case, I fixed this with an ugly sleep in the master before sending the second byte:

    SPI.beginTransaction(spi_settings);
    word input = 0;
    digitalWrite(spi_devices[port].pin_ss, LOW);
    input |= SPI.transfer(output >> 8) << 8;
    delayMicroseconds(20); // Must give time to slave to read first byte
    input |= SPI.transfer(output);
    digitalWrite(spi_devices[port].pin_ss, HIGH);
    SPI.endTransaction();

Not elegant, but it works.


message:
How does Arduino determine whether the given condition provided to it is true or false?

I want to understand how does the microcontroller determine that the conditions provided to it in the input are true or false. eg:

    if (someVariable > 50)
    {
      // do something here
    }

Then how does Arduino determine if the value that I put in `somevariable' is larger than 50 (as apposed to less than or equal to 50)?

body:
In general terms comparisons are usually performed, at the low level of assembly language, using subtraction.

In assembly language when you perform a subtraction there are flags in the status register that may or may not get set depending on what has happened. These include the Zero flag and the Carry flag.

If you are comparing A to B then you subtract B from A and see what happened by examining the flags.

For instance, if your variable contains 30 and you compare it to 50 you subtract 50 from 30. Because the result "passes through" zero the Carry flag is set. You can then do a "Jump if Carry Set" call.

If you should have 50 in your variable and you compare it to 50 the subtraction ends up with the Zero flag set since the result is exactly zero. It is then possible to do a "Jump if Zero Set" call.

If you have 60 in your variable and compare it to 50, the subtraction results in 10, which doesn't set either flag. That is actually slightly harder to work out (depending on architecture) since you are then wanting to compare two flags (Carry and Zero) and see if neither of them are set. So it is common for the compiler to optimize it so that the condition is reversed (`a > b` is the same as `!(a <= b)` for instance).

Of course, some architectures have actual comparison instructions (often `CMP`) which compares two registers and sets or clears the different flags for you. For instance, the ATMega328P has the instructions:

* `CPSE` - Compare, Skip if Equal
* `CP` - Compare
* `CPC` - Compare with Carry
* `CPI` - Compare Register with Immediate

`CPI` would be the most logical choice in the example you give - compare the contents of a register (variable) with an "immediate" value (an "immediate" value is a constant value):

    CPI $r3, 50

According to the instruction set manual the comparison is, surprise surprise, performed as a subtraction, and what happened during the subtraction sets the different flags. To make life simpler the instruction set has a number of branch instructions which look at the different flag combinations and jump to another address if they match:

* BRLT - Branch if the result of the previous comparison was A < B
* BRLE - Branch if the result of the previous comparison was A <= B
* BRGT - Branch if the result of the previous comparison was A > B
* BRGE - Branch if the result of the previous comparison was A >= B
* BREQ - Branch if the result of the previous comparison was A == B
* BRNE - Branch if the result of the previous comparison was A != B

There are more as well for other special comparisons.  You can read up all about them in [the AVR instruction set manual](http://www.atmel.com/Images/Atmel-0856-AVR-Instruction-Set-Manual.pdf).


body:
Just to complement Majenko's answer with an example, I tried the
following:

<!-- language: lang-c++ -->

    volatile int someVariable;
    void do_something_here();

    void foo()
    {
        if (someVariable > 50)
        {
          do_something_here();
        }
    }

and the compiler generated the following assembly (comments mine):

    foo:
        lds r24, someVariable      ; load variable into registers, LSB
        lds r25, someVariable + 1  ; and MSB
        sbiw r24, 51               ; subtract 51
        brlt .L1                   ; if (result < 0) goto .L1
        jmp do_something_here      ; do_something_here()
    .L1:
        ret                        ; return

The `sbiw` instruction means "subtract immediate from word". It
subtracts a 6-bit immediate value from a 16-bit value contained in a
register pair (r25:r24 in this case). It is one of the very few 16-bit
instructions of this mostly 8-bit CPU.

As you see, the compiler did some optimization and changed the code to
something looking more like:

<!-- language: lang-c++ -->

    if (!(someVariable - 51 < 0))
    {
        do_something_here();
    }

It is also worth noting that the `brlt` instruction (branch if lower
than) tests the sign flag of the status register, which is the exclusive
OR of the negative flag (result < 0) and the overflow flag. This way the
result of the comparison is correct even if the subtraction overflows.

Note also that this is only an example. The generated assembly would be
different if you use another type than `int` (a wider or smaller or
unsigned integer), or an explicit constant greater than 62.


message:
How to use breakpoints for debugging

Breakpoints are a great way to see how the compiler runs to your code. Now my question is, is there a possibility to use breakpoints when you debug your code?

body:
Not in the Arduino IDE.

You need to:

1. Install and use a real IDE, such as Atmel Studio, and
2. Use a full hardware debugger

There is no provision for debugging through the UART/USB interface using the bootloader.


body:
As noted in Majenko's answer, the Arduino IDE doesn't provide a breakpoint  mechanism but [Atmel Studio does support breakpoints](http://www.atmel.com/webdoc/atmelstudio/ch05s07s01s01.html).[*]

However, if you have a switch and an LED, you can track the progress of your program in a way that provides some of the benefits of breakpoints.  You would add a subroutine, say `BPReport()`, that via serial output or an LCD reports values of critical variables, then lights the LED and waits until the switch has been pressed and released, with debounce.  Call your `BPReport()` routine whereever you want an unconditional breakpoint.  For conditional breakpoints, you can have a routine `BPReportIf(cond)` which calls  `BPReport()` if `cond` is true.  If you don't want to output via serial, you might use several LEDs or an LCD, and you might use several switches if you want external break controls (for example, `cond` could be a test of one of the extra switches).

[*] Some hardware debuggers modify downloaded code each time breakpoints are added, changed, or removed.  That usage will wear out flash memory more rapidly than just occasionally downloading to it.  If a chip has been heavily used for such debugging, don't use that chip in a production system.


body:
Though Majenko his answer is correct there are some other options.

As to the real hardware debugging as stated by majenko I would say:

1.  Install and use a real IDE, such as Atmel Studio or the arduino eclipse plugin called sloeber (I'm author), and
2.  Use a full hardware debugger or hardware that has it on board like the Arduio zero or hardware using other debugging technology like the ESP8266 that allows USB debugging

An other debugging option from a completely different category is to organize your code so that decision logic (hardware independent) and action (hardware dependent ) are completely separated.

Then compile your sketch as a local program and debug the "decision logic" on your local machine. This method does not allow for "hardware debugging". This method also enables unit testing.

Note that your local machine is probably a 32 or 64 bitter and most Arduino's are 8 bitters which will result in differences in data types which is an extra attention point when using this method.


body:
The [Arduino-Debug][1] library provides a simple on-target debugger for Arduino sketches. Debug command are added directly to the sketch. A debugger command shell is started on break-points and assertions.

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

The screen-shot above shows the [example sketch][3] run on an Arduino Mega with Serial output monitor used by application and Serial1 used for the debugger shell.

**Sketch Debug Commands**

 - ASSERT(cond)  Check assert condition. If false the debug shell is
   called. The sketch cannot continue.
 - BREAKPOINT()  The debug shell is called.
 - BREAK_IF(cond)  The debug
   shell is called if the condition is true.
 - CHECK_STACK(room)  Check
   that there is room (bytes) on the stack. If false the debug shell is
   called.
 - DEBUG_STREAM(dev)  Use the given stream device for debug session. Typically Serial.
 - OBSERVE(expr)  Print the expression to the debug stream.
 - OBSERVE_IF(cond,expr)  Print the expression to the debug stream if
   the condition is true.
 - REGISTER(var)  Register a variable for access
   from the debug shell. Debug Shell Commands

**Debug Shell Commands**

 - *?VARIABLE*  Print variable address and value.
 - *@VARIABLE*  Print pointer variable address and reference value.
 - *backtrace*  Print simple call-stack.
 - *commands*  Print list of commands (see also help).
 - *data*  Print contents of data area, i.e. global variables.
 - *go*  Leave debug shell and continue execution of sketch.
 - *heap*  Print contents of heap, i.e. dynamic allocated data.
 - *help*  Print list of commands.
 - *memory* Print memory status.
 - *quit*  Stop sketch.
 - *stack*  Print contents of stack, i.e. call frames, arguments, return addresses.
 - *variables*  Print list of registered variables.
 - *where*  Print source code file and line where debug shell was called.

All debug shell commands can be abbreviated to single character commands. Please see the README for further details; installation details, example sketch and benchmarking.

  [1]: https://github.com/mikaelpatel/Arduino-Debug
  [2]: https://i.stack.imgur.com/KAVaa.png
  [3]: https://github.com/mikaelpatel/Arduino-Debug/blob/master/examples/DebugDemo/DebugDemo.ino


message:
Can a motherboard be a simple circuit between arduino uno and a set of devices (ie: motors)

**Reason for question:**
My son is working on a project to build a robot controlled by an arduino uno. This question is more about terminology than process, but since terms are very important at this level, I rather ask some expert advice - I have not found any input on the internet about this!

**Question:**
What is the correct technical name (if any) of the circuit board that acts as the interface between the arduino-uno (a micro-controller) and the motors (the external devices)? According to the definition of a motherboard*, this "interface" circuit board would act as a very basic motherboard, as it would "allow communication" between the components, but it would not contain expansion slots, so should it be called something else?

**Background on project:**
The robot will be very basic. A body will be made of plastic legs and motors for joints; an Arduino-uno will provide the logic for motor movement; and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

We are just missing the proper terminology to use for this "interface" board and I cannot find any concrete info online or on books. If I get good terms in this post, then we can do further research on those terms. Thanks.

https://en.wikipedia.org/wiki/Motherboard

body:
In the Arduino ecosystem these boards are called 'shields'.

[Arduino][1] describes a shield as:

> Shields are boards that can be plugged on top of the Arduino PCB
> extending its capabilities.

For example, there is an [Arduino Motor Shield][2] which sounds very similar in purpose to the board that your son is making.

  [1]: https://www.arduino.cc/en/Main/ArduinoShields
  [2]: https://www.arduino.cc/en/Main/ArduinoMotorShieldR3


body:
I would call it an "interface" or "driver" board. You don't need to get too hung up on the exact name.

The word "shield" is one of the Arduino-peculiar words (like "sketch" for "code") which now has a generally-understood meaning. That meaning is, something that plugs directly onto the Arduino board, with the pins on the shield matching the sockets on the Arduino board.

Whilst a shield is a quick and easy way of getting started (because you don't need to wire anything) they can have their disadvantages. One being, what if you want two different functions, like a motor driver and an Ethernet interface? Two shields, one on top of the other? What if they both use a certain pin for different purposes?

I made up a [radio-controlled car](http://www.gammon.com.au/forum/?id=11506), see photo:

[![Radio-controlled car][1]][1]

The only shield I used was a generic "put whatever you want onto it" shield, which let me mount some MOSFETs, a radio receiver board, and other components, as required by the design. There is a Uno underneath it, not particularly easy to see. Adjacent on the right is a motor driver board. A LiPo battery is slung underneath.

This kept things reasonably compact, without requiring a specific purpose-made shield which only does one thing.

> and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

It sounds like your project is similar to my car. Just assemble things in a way that makes sense to you.

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


message:
Alternative distance-meter, HC-SR04 doesn't work very well

On door to my room there is [HC-SR04][1] that triggers led-wave. The shorter the distance, the faster the led-wave (8 leds).

The circuit works fine in synthetic tests – moving hand or flat object towards the sensor generates gradually accelerating wave.

However, when placed on door to detect approaching persons it generates short correct (<=170 cm) impulses and the wave starts and immediately stops, again starts, etc. I guess HC-SR04 isn't good enough to detect people.

Are there any alternatives to this sensor that will correctly detect human approaching?

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

body:
Try to find where the error comes from.

I suggest loading up a piece of code that outputs the measurements to through the serial terminal.

 - You should typically filter out any values that are > 200cm (since it's out of range).

 - You should take the average of a few readings, to be more accurate and less error-prone.

 - Find why some readings are weird, is the object fuzzy (may absorb the ultrasound)?

If all fails, you may look at IR distance sensors (SHARP) like:

https://www.adafruit.com/product/164

or

https://www.adafruit.com/product/1568

Alternatively, you could use a combination of (multiple) IR and ultrasonic sensors. But I doubt you really need that mount of accuracy.

You could also go for a Raspberry Pi + camera and openCV, but that's a whole other matter.


body:
In general the HC-SR04 is controlled using `pulseIn()`.

When there is nothing within range for the sensor to detect it usually has to wait for `pulseIn()` to time out. That can take up to a second by default.  While that is happening the rest of the sketch cannot do anything.

You can reduce the timeout in the `pulseIn()` function, but it's still not going to be perfect - you'll still get a delay which will interrupt your LED sequences.

The ideal way will be to create a "free running" distance sensor system - use a timer to periodically start a ping, and use the Input Capture module of the ATMega to measure the time between the start and end edges of the returning pulse. Everything will happen asynchronously to the rest of your sketch then.

I am not aware of any libraries for Arduino boards, but [I have one for the PIC32 based chipKIT boards that I use](https://github.com/MajenkoLibraries/ICPing). It can't ever work on AVR based boards, but you can use it to see the general concepts and how things fit together.


message:
RFM69HCW 915 MHz radio module: Sending a stream of int values rather than char[ ]

I'm trying to send a stream of int values (0-4096) from one arduino to another using an RFM69HCW module.

Here's my main code:

    #include <RFM69.h>
    #include <SPI.h>
    #define NETWORKID     0   // Must be the same for all nodes
    #define MYNODEID      1   // My node ID
    #define TONODEID      2   // Destination node ID
    #define FREQUENCY     RF69_915MHZ
    #define ENCRYPT       true // Set to "true" to use encryption
    #define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes
    #define RFM69_CS      10
    #define RFM69_IRQ     2
    #define RFM69_IRQN    0  // Pin 2 is IRQ 0!
    #define RFM69_RST     9
    #define IS_RFM69HCW   true
    #define USEACK        true // Request ACKs or not
    #define LED           9 // LED positive pin
    #define GND           8 // LED ground pin
    #define PULSEPIN      0 // Heart Rate Monitor at pin A0

    RFM69 radio = RFM69(RFM69_CS, RFM69_IRQ, IS_RFM69HCW, RFM69_IRQN);
    String pulsearray;
    bool recHR = true;
    unsigned long oldtime = 0;
    int interval = 5000;
    static int readtime = 3000;
    static int sampletime = 10; // 1000/this is the thing
    static int txinterval = 1000; // delay between transmissions

    void setup() {
      initSerial();
      initLed();
      initRadio();
    }

    void loop() {
      unsigned long newtime = millis();
      if (!recHR && newtime - oldtime >= interval) {
        recHR = true;
        oldtime = newtime;
        Serial.println("recording HR now");
      }

      while (recHR) {
        unsigned long newtime = millis();
        if (newtime - oldtime >= sampletime) {
          readhr();
        }
        if (newtime - oldtime >= readtime) {
          recHR = false;
          oldtime = newtime;
          Serial.println("stopped reading HR");
        }
      }
    }

And the function I'm using:

    void readhr() {
      for (int i = 0; i < 20; i++) {
        int pulse = analogRead(PULSEPIN);
        pulsearray = pulsearray + pulse;
        pulsearray = pulsearray + '\n';
        Serial.println(pulse);
      }
    }

The library function sendWithRetry() requires the following arguments:

    bool RFM69::sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferSize, uint8_t retries, uint8_t retryWaitTime)

**I would like a way to set up a buffer which can be transmitted in multiple packets during the 5 second analogRead() downtime.**
Using a string as my buffer doesn't work when I try to transmit the first n (<60) characters in the String. I've also tried using a char[ ] as my buffer (a lot more troublesome when storing int values) but it still gives the same error:

    exit status 1
    no matching function for call to 'RFM69::sendWithRetry(int, String&, unsigned int)'

body:
You need to send the address of a buffer and the size, in bytes, of that buffer. What that buffer consists of is neither here nor there.

If you have an array of 10 ints you have a 20 byte buffer (since one int is 2 bytes on an 8-bit Arduino).

So you just pass it the address of the buffer (which as an array it is already just an address) and the size of that buffer:

    int values[10];
    // whatever to fill the array
    RFM69::sendWithRetry(20, values, 20, 4, 1000);

As long as the array is statically created (e.g., a global variable with a fixed number of entries) you can use `sizeof()` to get the size in bytes:

    RFM69::sendWithRetry(20, values, sizeof(values), 4, 1000);

As long as you receive at the other and using the same type of buffer it should be completely transparent.

To keep the system cross-platform and able to run on an Arduino that is either 8 or 32 bits and have them completely interoperable it is best to use variables with a fixed size. Instead of `int` use `int16_t` which is always 2 bytes and signed on every platform everywhere:

    int16_t values[10];

Or use `uint16_t` if you want it unsigned.


message:
Arduino Sending faster/more data to a web server

I'm working on a project that reads vibration on a building using an accelerometer and displaying it's data on a web server. The plan is to read 10 samples/second from the accelerometer and send that data every 5 seconds to a web server using arduino yun.

So there would be 10(samples/sec) x 5(seconds) x 3(3 axis - x,y,z) = 150 data points that will be sent to the webserver, I tried this with the client.get() command but it cannot send that much data to a web server, I also tried POST request but i've had trouble with the sending it multiple times since it needs to have a delay.

What are the other options that I can do in order to achieve this? Any suggestion would help and please if you think my question is bad or not stated properly don't report me, I'm still new here in stack exchange. Any help/suggestion is much appreciated

Arduino Code for POST request
-----------------------------

    #include <Bridge.h>
    #include <HttpClient.h>
    #include <YunClient.h>

    //IPAddress server(192,168,1,200);
    byte php_server[] = {192,168,1,9};

    YunClient client;
    String data = "", datax="", datay="", dataz="";
    unsigned long ts_0 = 0, tr_0 = 0, t_read = 100;
    int counter=0;

    void setup() {
      // put your setup code here, to run once:
      Bridge.begin();
      Serial.begin(115200);

    }

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

      if((millis()-tr_0>=t_read)) {

        if(counter<49) {
          counter++;
        }
        else if(counter == 49) {
          //Serial.print("sent");
          String dat = "0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12";

          send_to_ws(dat);
          Serial.println(dat);

          counter = 0;
        }
        tr_0=millis();
      }
    }

    void send_to_ws(String data) {
      if(client.connect(php_server, 80)) {
        Serial.println("Connected");
        client.println("POST /arduino/add.php HTTP/1.1");
        client.print("Content-Length:");
        client.println(data.length());
        Serial.println(data.length());
        Serial.println(data);
        client.println("Connection: Close");
        client.println("Host:192.168.1.9");
        client.println("Content-Type: application/x-www-form-urlencoded");
        client.println();
        client.println(data);
      } else {
        Serial.println("Connection error");
      }
    }

Serial monitor output when running this sketch, It prints it in the serial monitor but only blank data is being pushed in the database of the server
[![here][1]][1]

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

body:
Option 1.
Send a single message from the client to the server.  This message should contain all 150 points of data.

Option 2.
Send the data in a format other than as a string.  Base64 encoding of the raw numeric values would be ideal, but its going to add extra load to the CPU.  Depending on the range of the data (0-359) and the resolution (use 2 DP) you might be able to use just 4 bytes for each data point.  Because you are using a fixed length value to represent each point you no longer need separators in you data so a single reading goes from 21 bytes to 12 bytes.

Option 3.
Hand off the data to a second processor that is dedicated to sending the data.  The Yun would write the data into a shard circular buffer and the other processor (possible another Yun or an ESP8266) would read the data from the buffer, convert it and write it to the server.

I can't say which is best, because I don't know enough about you system, but if you could expand on your details we should be able to narrow it down.

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

After reading you answer above.  If you ranges are 0-10 with two DPs then I would look at option 2 first.  If each reading can range from -9.99 to +9.99 you take the absolute value and multiply by 100 and write that as a 2 digit hex number to your message body.

    uint8 number = ((reading < 0) ? 0x80 : 0x00);  // Set the high bit for negative.
    number += (abs (reading) * 100);
    messageBodyString += String (number, HEX);

That will give you 2 bytes per point, and a 300 byte (+overhead) message should be transferable within 5 seconds.

------------------------------------------------------------
Here is some quick code to explain the encoding and decoding

    unsigned int Encode(const float& value)
    {
     unsigned int result = (value < 0) ? 0x80000000 : 0x00000000;// Work out and set the sign bit
     result |= (unsigned int)abs(value * 100.0);    // Get the absolute value (ignore sign) and multiply
     return result;
    }

    float Decode(const unsigned int& value)
    {
     const bool isNegative = ((value & 0x80000000)  != 0);  // Get the sign bit
     float result = (float)(value & 0x7FFFFFFF);     // To remove the sign bit
     result /= 100.0;           // Divide to return to the original number of dps.
     if (isNegative)
      result = 0 - result;
     return result;
    }


body:
You can use 2d Array for this and send all data at once in 5 Sec. It Read all 3 Axis data each 100Ms and make a matrix of 50 X 3 = 150 Values and then Print it in Serial Port. You can use this in your code to send data to server in desirable format.

    int Xaxis=A0;
    int Yaxis=A1;
    int Zaxis=A2;
    int axisMatrix[50][3];
    void setup(){
        Serial.begin(9600);
        pinMode(Xaxis,INPUT);
        pinMode(Yaxis,INPUT);
        pinMode(Zaxis,INPUT);}

    void loop(){
            for (int i = 0; i <= 50; i++) {
          axisMatrix[i][1]=analogRead(Xaxis);
          axisMatrix[i][2]=analogRead(Yaxis);
          axisMatrix[i][3]=analogRead(Zaxis);
          delay(100);}
         for (int i = 0; i <= 50; i++) {
          Serial.print(axisMatrix[i][1]);
          Serial.print(",");
          Serial.print(axisMatrix[i][2]);
          Serial.print(",");
          Serial.print(axisMatrix[i][3]);
          Serial.print(",");
          Serial.print("\n");
      }}


body:
Personally for this kind of frequency of data I wouldn't even consider sending it via HTTP. The extra bulk of the HTTP protocol makes the transfer way too slow.

Instead I would set up a UDP-based gateway server which accepts UDP messages from your sensor system and stores the data directly into the database (or wherever you are storing the data) for the website to display it at its leisure.

Yes, it is more complex to create since you need to write the UDP server gateway software. However you then completely remove the massive overheads of a text-based bulky protocol like HTTP.


message:
How time intensive or how long can an ISR be?

I would like to code my ISR to be time intensive or interrupt the main program for atleast 1 or more seconds. My goal is to verify that if I am reading a sensor in the main loop, would it stop reading the sensor when the code is interrupted and for how long. I have trying to call various functions from the ISR like to turn on the motor but everything is instantaneous.

body:
> How long can an interrupt be?

If you don't want anything else to happen, then as long as the time between successive interrupts.

> would it stop reading the sensor when the code is interrupted and for how long.

While the interrupt is running nothing else can happen in software. Absolutely nothing. Only one thing ever happens at once - either your main loop or the interrupt. For the entire duration of your interrupt everything else is put on hold.

That includes things that rely on other interrupts to function, such as serial communications, `millis()` and `delay()`, etc. That means using such functions from within your interrupt handler is a big no-go.

It is generally very very bad practice to have an interrupt blocking for more time than absolutely necessary (a few milliseconds or even less). If you need to have things taking a long time then you should consider breaking them down into smaller operations and doing different sections at different times through different means.


message:
Is the analogread function averaging the samples taken by the ADC?

In many development boards the analog voltage data which is sampled by the ADC can be sent to the serial port. But the data speed I see on the serial port by HyperTerminal or Serial monitor is much slower than the sampling rate.

Lets take Arduino as an example. As far as I understand the analogread() function samples an analog input at 10kHz rate. It means 10000 samples taken per second.

But when I use the Serial Monitor it seems the data speed which we see as upcoming/flowing line by line per second on Serial Monitor is much slower.

Is that because the analogread() is averaging the samples before the data is sent to the serial port?

body:
> As far as I understand the analogread() function samples an analog input at 10kHz rate.

No, it samples an analog input at *once per invocation*. This means that if it is run 10000 times within a second (assuming it can be run that many times within a second) then *the code* is sampling at 10kHz. But if it's run only twice per second then the code is sampling at 2Hz.


body:
If you have a loop that calls analogRead() to take a reading, and then serialPrint() to send the reading, each pass through the loop will take at least the sum of the time for those two functions calls together.

When you first call serialPrint(), it returns in uS, as it doesn't actually *send* data, but puts it into the 64 deep transmit buffer, to be sent in the background. If the transmit buffer is emptying slower than you are filling it (at 9600 baud, it's sending roughly one character per mS, so you can send at most 100 off 10 character messages per second) then eventually when called, it will find not enough space in the transmit buffer for the whole message, and will *Block*, that is not return, until there is enough space. Each call to serialPrint() will now take 10mS (assuming 10 characters at 9600 baud). That's what slows your loop down.

To send faster, choose a higher baud rate, and reduce the number of characters in the message.


message:
Mega 2560 & smoking/burning 5v requlator, probable cause?

Problem: board seriously fried.
Desired outcome: measures to take in future.

Background:
This project has been running for about a week on the 2560, and previously for a few weeks on an UNO clone. Board switch a result of program size/expansion.  It sits on a shelf with others of the same ilk.  Nothing is touched unless I need to plug in USB cable for update.
The Arduino is a clone, connected to DS3231, LCD1602 via I2C Serial Interface board, LCD2004 also via 12C SIB, SD card adapter, HC-12 wireless, 5 leds [normally off, used to flag specific conditions, each in series with 470 ohm resistor.
The unit receives data from another Arduino and logs to the SD, updating the two LCD displays.

Steps leading to failure:
Plugged in USB cable [no other physical changes, nothing else touched, power jack remained connected]. went to Arduino s/w to make minor changes, would not upload to Arduino.  While scratching my head, smelled something burning, then saw smoke coming from the shelf.

Post failure:
Board seriously scorched around 5v regulator, can provide photo, but seems unnecessary.
Visual wiring inspection revealed no obvious problems.
Input to power jack measured at 10.06v.
Replaced with new Arduino 2560 clone, matching connection for connection, connected USB but not power port [just in case of ?, seen ancedotal posts of possible conflict; a clone after all].  Uploaded my modified program, and all works fine. Disconnected USB, reconnected power jack and all still fine, 16 hours in.
Also searched internet for possible problems related to such a failure, but found nothing to suggest probable cause.

Seeking:
Words of wisdom from others far more knowledgeable and experienced than I.
Could the dual connection of USB and power jack, be the root cause?  Never experienced this with UNO clones.

I do not want to put more boards at risk in the future.

body:
They are using the same SOT223 LDO as every other product.  These have a very low limit of output current when run from an input voltage such as 12V.  If you replace the LDO with a switching regulator, you can eliminate the waste heat regardless of the output current (Except for the 5V to 3.3V secondary LDO which is a constant).  The PDF linked below shows a comparison between the LDO and drop in switcher.  Not that the switcher performance at 1900mA is equivalent to the LDO at 250mA... at 250mA the switcher temperature rise would only be 8.5C.

https://www.sugarsync.com/pf/D3258881_07979653_7526812


message:
`servo.attach()` paralyzing (one) motor on L298N

I have 2 DC motors (well, 4; but each pair is controlled by the same "signals") connected via a L298N, which is connected to the Arduino. In addition, I have a servo motor connected to the Arduino.

---

When I run the following program (in reality, it's a bigger program; however, I've managed to chiseled it down to the following):

    #include <Servo.h>

    const int servoPin = 3;
    Servo servo;

    const int LMotorsSpeedPin = 5;
    const int RMotorsSpeedPin = 10;
    const int LMotorDirectionBit1Pin = 7;
    const int LMotorDirectionBit2Pin = 6;
    const int RMotorDirectionBit1Pin = 8;
    const int RMotorDirectionBit2Pin = 9;
    const int MotorSpeed = 150;

    void setup()
    {
      // 1
      pinMode(servoPin, OUTPUT);
      servo.attach(servoPin);

      // 2
      pinMode(LMotorsSpeedPin, OUTPUT);
      pinMode(RMotorsSpeedPin, OUTPUT);
      pinMode(LMotorDirectionBit1Pin, OUTPUT);
      pinMode(LMotorDirectionBit2Pin, OUTPUT);
      pinMode(RMotorDirectionBit1Pin, OUTPUT);
      pinMode(RMotorDirectionBit2Pin, OUTPUT);

      // 3
      digitalWrite(LMotorDirectionBit1Pin, LOW);
      digitalWrite(LMotorDirectionBit1Pin, HIGH);
      analogWrite(LMotorsSpeedPin, MotorSpeed);

      // 4
      digitalWrite(RMotorDirectionBit1Pin, LOW);
      digitalWrite(RMotorDirectionBit1Pin, HIGH);
      analogWrite(RMotorsSpeedPin, MotorSpeed);

      // 5
      delay(10000);
    }

    void loop() {}

* `1` Sets up servo.
* `2` Sets up L298N pins.
* `3` Sets up left motor data.
* `4` Sets up right motor data.
* `5` Tests the code above for 10 [s].

---

I assume that you'll need some experience with the L298N; however, here's the gist.

`*MotorsSpeedPin` sends each motor what speed (`MotorSpeed` 0-255) they must go (via PWM).
Data into a pair of `*MotorDirectionBit*Pin` tell each motor what direction to go (i.e. back `01`, stop `00` `11`, right `10`).

---

When I run the program above, only the left motor runs. However, if I comment out `1` (which essentially renders the servo useless), both left and right motors start to work.

I find this problem quite odd. What does the servo code have to do with the motor code (and only one at that!)?

body:
The Servo library uses Timer 1 to create the servo control signal. That means it can run the servo on any pin or combination of pins, and at the 50Hz speed that a servo likes best.

However, pins 9 and 10 also use Timer 1 to create the PWM signal.

It can't do both.

As soon as you start using the Servo library you lose PWM on pins 9 and 10.

So what can you do about it? Simply move your pins around to different pins. You can't use 9 and 10 for PWM, but you can use them for the servo. So put your servo on pin 10 and your right motor speed control on pin 3 and all should be happy.