message:
How do string pointers work in Arduino?

To the best of my understanding, when I declare

    String s = "This is a string.";

what happens is that space is allocated on the stack for a pointer which points to some String object which internally contains a char array. My confusion stems from the fact that this pointer seems(I could be wrong) to behave differently than any other type of pointer. For example, if I write

    int a = 1;
    int* x = &a;
    int* y = x;

what happens is that the pointer saved in y now points to the same location in memory as the pointer saved at x. So if I write

    String s1 = "This is a string.";
    String s2 = "Hello World!";
    s1 = s2;

does the pointer saved at s1 now point to the same memory location as s2? Or does s1 copy the char array from s2 into its own separate memory? Further, If I write

    String s1 = "This is a string.";
    s1 = "Hello World!";

does s1 now point to whatever arbitrary memory location was created for the string literal "Hello World!"? Will this memory location be freed later, or is some sort of smart garbage collector in place which knows that I am using that memory in the heap? Finally, should I never assign a string declared on the stack to a global variable, as this will be referencing a memory location which will be freed soon?

Thank you in advance for your help!

body:
String is not a simple type like an `int` or a `char`. It is a class with many member functions and, more importantly, operators.  When you create the object it allocates room for that object either on the stack (for a local variable) or in the global data area if it's a global variable. However that object doesn't contain the memory used to store the actual string data - it only has a pointer. The memory for the string data is allocated on the *heap* using `malloc()` and `realloc()`.

Assigning string data to the String object is done through the `=` operator defined in the class, of which there are a number of overloaded varieties:

    String & String::operator = (const String &rhs)
    {
        if (this == &rhs) return *this;

        if (rhs.buffer) copy(rhs.buffer, rhs.len);
        else invalidate();

        return *this;
    }

    #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
    String & String::operator = (String &&rval)
    {
        if (this != &rval) move(rval);
        return *this;
    }

    String & String::operator = (StringSumHelper &&rval)
    {
        if (this != &rval) move(rval);
        return *this;
    }
    #endif

    String & String::operator = (const char *cstr)
    {
        if (cstr) copy(cstr, strlen(cstr));
        else invalidate();

        return *this;
    }

    String & String::operator = (const __FlashStringHelper *pstr)
    {
        if (pstr) copy(pstr, strlen_P((PGM_P)pstr));
        else invalidate();

        return *this;
    }

They all, ultimately, call the `copy()` or `move()` functions which copy the data from the source into the memory allocated on the heap (increasing the allocation if needed).

Using:

    String s1 = "Foo";
    String s2 = s1;

`s1` has memory allocated on the heap, then `Foo\0` copied into it.  `s2` then also has memory allocated on the heap, and the data from `s1` is copied into it. So you have two separate objects with separate memory allocated for their content.  So then doing:

    s2 += "bar";

you end up with:

    s1: "Foo\0"
    s2: "Foobar\0"

Since it's an object that's allocated on the stack (or in global space) and not a pointer to the object you can get a pointer to it like with an `int`:

    String s1 = "Foo";
    String *s2 = &s1;
    (*s2) += "bar";

Which gives you just one object and one memory space, but two names for it, and the result is:

    s1: "Foobar\0"
    s2: "Foobar\0"

This is why it's important to use either pointers or references when passing String objects as parameters to functions, and the constant allocation and reallocation on the heap why String objects are frowned upon in microcontrollers with very limited RAM.


sender: user

message:
Error to make a request using Arduino Uno and ESP8266

I'm using Arduino Uno and ESP8266 in a project.

I'm using AT Commands to connect to wi-fi and make a request. I'm using the monitor serial to test the code before compile it in arduino.

It is connecting to wi-fi and I can make a request to a server in my network but when i try to make a request to my web-service in cloud it doesn't work well.

The return is an HTML with an 404 page instead of what I am expecting:

Hello Versa

Here is my code:

    AT+CIPSTART="TCP","ternary.com.br",80
    AT+CIPSEND=18
    GET /webservice/

Can someone help me telling me what I am doing wrong?

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

After see the answer of Maximilian Gerhardt, I solved it writing the following sequence in the monitor serialize:

    AT+CIPSTART="TCP","ternary.com.br",80
    AT+CIPSEND=70
    GET /webservice/ HTTP/1.1
    Host: ternary.com.br
    Connection: Close
    [Just press enter and send a new line]

sender: assistant

body:
A HTTP requests is comprised of more than just `GET /webservice/`. Take a look at what `curl` (console-line HTTP client) does.

    C:\>curl -v "http://ternary.com.br/webservice/"
    *   Trying 187.84.237.200...
    * Connected to ternary.com.br (187.84.237.200) port 80 (#0)
    > GET /webservice/ HTTP/1.1
    > Host: ternary.com.br
    > User-Agent: curl/7.46.0
    > Accept: */*
    >
    < HTTP/1.1 200 OK
    < Date: Fri, 11 May 2018 15:04:16 GMT
    < Server: Apache
    < X-Powered-By: PHP/5.6.30
    < Vary: Accept-Encoding
    < Cache-Control: max-age=0, no-cache, no-store, must-revalidate
    < Expires: Wed, 11 Jan 1984 05:00:00 GMT
    < X-UA-Compatible: IE=Edge,chrome=1
    < Pragma: no-cache
    < Transfer-Encoding: chunked
    < Content-Type: text/html; charset=UTF-8
    <

Hello Versa
* Connection #0 to host ternary.com.br left intact

You will have to at least transfer the minimal correct HTTP Headers of the form

    GET /webservice/ HTTP/1.1
    Host: ternary.com.br
    Connection: Close

To get an answer. Also mind the ending `\r\n\r\n`. Refer to [this website][1] for more headers.

When I only send `GET /webservice/` I also get 404 page.

    C:\>cat test
    GET /webservice/

    C:\>cat test | ncat ternary.com.br 80
    [...]
            <title data-i18n="[html]404_page.title">404 ÔÇô P├ígina n├úo encontrada</title>

  [1]: https://www.tutorialspoint.com/http/http_header_fields.htm


message:
How to read main code inside main code in Arduino?

How can I read the hex code of the main programme stored inside flash memory inside my running Arduino programme?

So far I am able to read the Flash at any given address by using PROGMEM

    unsigned int displayInt;
    int k;    // counter variable

    void setup() {
      Serial.begin(9600);
      while (!Serial);  // wait for serial port to connect. Needed for native USB

      for(k = 0; k < 5; k++) {
        displayInt = pgm_read_word_near(k);
        Serial.println(displayInt);
      }
    }

    void loop() {
    }

The output is

    37900
    13716
    53
    3072
    37900

But this not hex code.

I am implementing the OTA (over the air) feature. I will get the new version of a code from GPRS. It will be huge code so I will write it to flash by using the custom bootloader mentioned [in this thread][1]. I am able to write to the flash memory. Now I would like to read the data from flash. To begin with I would like to read the main programme inside my main programme.

  [1]: https://forum.arduino.cc/index.php?topic=332191.0

body:
Interesting. If you want hex you have to tell it to print in hex. If I change your display line to:

    Serial.println(displayInt, HEX);

Then I get:

    940C
    3594
    35
    C00
    940C

Compare this to what the decompiled file looks like:

       0: 0c 94 35 00  jmp 0x6a ; 0x6a <__ctors_end>
       4: 0c 94 5d 00  jmp 0xba ; 0xba <__bad_interrupt>
       8: 0c 94 5d 00  jmp 0xba ; 0xba <__bad_interrupt>

If you take the endianness into account (you are reading words, not bytes) then it is the same.

---

If you change it to read bytes it looks better:

    void setup() {
      Serial.begin(115200);
      while (!Serial);  // wait for serial port to connect. Needed for native USB

      for(int k = 0; k < 12; k++) {
        byte c = pgm_read_byte(k);
        char buf [3];
        sprintf (buf, "X", c);
        Serial.println(buf);
      }
    }

    void loop() {
    }

I increased the baud rate to 115200. I'm always puzzled when people use 9600 baud. Do you hanker for the olden days, when 9600 baud modems were the fastest you could get?

That gives this result:

    0C
    94
    35
    00
    0C
    94
    5D
    00
    0C
    94
    5D
    00

As you can see, it is exactly correct.


message:
Arduino ESP8266 - wifi evt: 3 and wifi evt: 7 meaning?

I'm getting these in my serial port, but what does wifi evt 3 and 7 mean?
I am trying to complete this tutorial. https://youtu.be/4Z0gBG8dkqw

The PHP file is on my hosting, and the ESP reads out the temperature and humidity from the sensor so that's fine.

**The serial code:**

    Connecting
    wifi evt: 3
    Connected
    Temperature:
    24.10
    Humidity:
    39.70
    [hostByName] request IP for: lucasdebelder.be
    [hostByName] Host: lucasdebelder.be IP: 185.182.57.81
    connected
    HTTP/1.1 200 OK
    Date: Fri, 11 May 2018 13:14:17 GMT
    Server: Apache/2
    Upgrade: h2,h2c
    Connection: Upgrade, close
    Vary: User-Agent
    Content-Length: 0
    Content-Type: text/html; charset=UTF-8

    �
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7
    wifi evt: 7

**The code that I am running in Arduino.**

    #include <ESP8266WiFi.h>
    #include "DHT.h"

    const char* ssid     = "bbox2";      // SSID of local network
    const char* password = "azerty";   // Password on network

    WiFiClient client;
    char servername[]="lucasdebelder.be";  // remote server we will connect to
    String result;

    float temperature;
    float humidity;

    #define DHTPIN 14

    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);

    void setup() {
      dht.begin();
      delay(2000);
      Serial.begin(115200);
      Serial.println("Connecting");
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(100);
      }
      Serial.println("Connected");
      delay(1000);
      readSensor();
      String temperatureString = String(temperature,1);
      String humidityString = String(humidity,1);
      sendDataToServer(temperatureString,humidityString);
    }

    void loop() {

    }

    void sendDataToServer(String temperature, String humidity)
    {
      if (client.connect(servername, 80)) {  //starts client connection, checks for connection
        Serial.println("connected");
        client.println("GET /send_email.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
        client.println("Host: lucasdebelder.be");
        client.println("Connection: close");  //close 1.1 persistent connection
        client.println(); //end of get request
      }
      else {
        Serial.println("connection failed"); //error message if no client connect
        Serial.println();
      }

     while(client.connected() && !client.available()) delay(1); //waits for data
      while (client.connected() || client.available()) { //connected or data available
        char c = client.read(); //gets byte from ethernet buffer
          result = result+c;
        }

      client.stop(); //stop client
      Serial.println(result);

    }

    void readSensor()
    {

      humidity = dht.readHumidity();
      temperature = dht.readTemperature();
      Serial.println("Temperature:");
      Serial.println(temperature);
      Serial.println("Humidity:");
      Serial.println(humidity);

    }

body:
The codes are explained in [this forum thread][1]. The wifi event types are  described [here][2] (and also [duplicated here][3], which are ultimately coming from the [Espressif Non-RTOS SDK][4], chapter 6.2.4):

<!-- language: lang-cpp -->

    typedef enum WiFiEvent
    {
        WIFI_EVENT_STAMODE_CONNECTED = 0,
        WIFI_EVENT_STAMODE_DISCONNECTED,
        WIFI_EVENT_STAMODE_AUTHMODE_CHANGE,
        WIFI_EVENT_STAMODE_GOT_IP,
        WIFI_EVENT_STAMODE_DHCP_TIMEOUT,
        WIFI_EVENT_SOFTAPMODE_STACONNECTED,
        WIFI_EVENT_SOFTAPMODE_STADISCONNECTED,
        WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED,
        WIFI_EVENT_MAX,
        WIFI_EVENT_ANY = WIFI_EVENT_MAX,
        WIFI_EVENT_MODE_CHANGE
    } WiFiEvent_t;

The enum's values are increasing downwards, meaning that 7 is `WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED`. Receiving a probe request means that some other device has scanned the surrounding WiFi networks and your ESP answered. This indicates that your ESP is in the Software Access Point (AP) + Station (SoftAP + STA) mode. But you only want to be a station in your own WiFi network, not an access point yourself.

The output is triggered by [this function][5].

[This comment on an issue][6] suggests that you add `WiFi.mode(WIFI_STA);` to your `setup`, like

<!-- language: lang-cpp -->

    void setup() {
      WiFi.mode(WIFI_STA);
      dht.begin();
      delay(2000);
      Serial.begin(115200);
      Serial.println("Connecting");
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(100);
      }
      Serial.println("Connected");
      delay(1000);
      readSensor();
      String temperatureString = String(temperature,1);
      String humidityString = String(humidity,1);
      sendDataToServer(temperatureString,humidityString);
    }

Subsequently, a WiFi event 3 indicates `WIFI_EVENT_STAMODE_GOT_IP`. Which also makes sense because you're telling the module to connect to the WiFi, it acquires an IP over DHCP and is then fully connected. This message is harmless since it doesn't indicate an error.

You should investigate on why these debug messages are thrown in the first place. The messages are only printed if two macros are set: `DEBUG_ESP_WIFI` and `DEBUG_ESP_PORT` ([see here][7]). So *something* must do `#define DEBUG_ESP_WIFI` and `#define DEBUG_ESP_PORT Serial` somewhere.

This is either done in some compiler settings which you are not aware of or because you modified a header file to include this change. Either way, you can try to use the `#undef` pre-processor macro to remove these definitions again before including the library. Change your first line to the following:

    //Try to kill the DEBUG defines
    #undef DEBUG_ESP_WIFI
    #undef DEBUG_ESP_PORT
    #undef DEBUG_WIFI
    #include <ESP8266WiFi.h>

  [1]: https://www.esp8266.com/viewtopic.php?f=32&t=15454
  [2]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiType.h#L51
  [3]: https://github.com/esp8266/Arduino/blob/master/tools/sdk/include/user_interface.h#L444
  [4]: https://www.espressif.com/sites/default/files/documentation/2c-esp8266_non_os_sdk_api_reference_en.pdf
  [5]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp#L217
  [6]: https://github.com/esp8266/Arduino/issues/2068
  [7]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFi.h#L43


body:
You see the "wifi" debug messages because you set in Tools menu `Debug Level "WiFi"`. Set`Debug Level "None"`

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

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


message:
Arduino Mega Pins for SoftwareSerial (vs. AltSoftSerial)

I am currently looking at using an Arduino Mega to build a MIDI Receive box that will then pump the data over USB, but am having design issues/uncertainties with the Arduino's receiving end.

I am looking to having (hopefully) 16 MIDI (as 5-pin DINs) inputs on this build, with no outputs other than the USB. The Mega has the 4 Rx pins, which still leaves me with 12 to create in software. From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs, while AlftSofSerial does. However, it also appears (at least from what I've gathered) that AltSoftSerial is not supported on as many pins as I would need to make this work.

With my setup up, not all 16 MIDI devices would be sending data into the Arduino at once, but only 2 - 4; these would be operating at the same time though (i.e. a Keyboard note along with a volume fader), so I don't believe SoftwareSerial would work well for what I need.

Is it possible to work out what I need with SoftwareSerial/AltSoftSerial and the physical UARTs? If there's any necessary info that seems to be missing or I seem to be misunderstanding something, please let me know. Thanks!

body:
> From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs

Correct. You can only `listen()` on one instance at a time.

AltSoftSerial can only support 1 instance, but allows simultaneous transmit and receive, and doesn't block the whole system while either transmitting or receiving.

So the best you can hope for is 4 hardware UART and one AltSoftSerial for 5 ports.

I would suggest looking into the possibility of using multiple Arduino Mega boards with 4 ports on each (4 boards would give 16 ports in total) and have them communicate with each other through some other protocol (SPI or I2C for instance).


message:
Cannot connect Mega to COM 9 but okay with other COM ports

I previously had issue updating code to Arduino Mega (clone). This is a continuation of this [issue][1], but I think it should be made as separate thread.

After some time spending with it. Turns out if I change my USB port and connect it another USB port, the Mega is detected in port COM 6. I can upload code to the Mega using this COM port (COM6), although it shows an error sometimes. But if I change it back to the previous USB port (here the Mega detected as connected in COM9), I can't upload anything. You can see the error message in the above link.

I also have a Uno and tried uploading code to it through the same USB port (here it is detected as COM8), I can upload code.

I used the working COM (COM6) to upload Marlin FW to the Mega and I can connect my printer through the same COM port, but if I try it through COM9 I can't connect.

So why can't I use COM 9?

PS: I've been COM9 being used to communicate with the same Mega.

  [1]: https://arduino.stackexchange.com/questions/52669/arduino-mega-cant-upload

body:
Check to see if you have !!! In your code. This will fail the upload.

More details here:  http://net-forces.blogspot.ca/2017/08/arduino-upload-timeout-and-in-string.html?m=1


message:
How do you convert a formatted print statement into a string variable?

I'm using the following routine to print the current time on the com port. I would like to capture this as a string so I can display it using ePaper.
```c++
    void printLocalTime()
    {
      time_t rawtime;
      struct tm timeinfo;
      if(!getLocalTime(&timeinfo))
      {
        Serial.println("Failed to obtain time");
       return;
      }
     Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
    }
```
produces -
>Saturday, May 12 2018 12:18:27

body:
To achieve what you want you probably want to use the "string format time" function `strftime` ([docs][1]). You would write the result in a character buffer, which you can also print directly without having to convert it to `String` object.

So, the following code should work:

<!-- language: lang-cpp -->

    void printLocalTime()
    {
      time_t rawtime;
      struct tm timeinfo;
      if(!getLocalTime(&timeinfo))
      {
        Serial.println("Failed to obtain time");
       return;
      }
      char timeStringBuff[50]; //50 chars should be enough
      strftime(timeStringBuff, sizeof(timeStringBuff), "%A, %B %d %Y %H:%M:%S", &timeinfo);
      //print like "const char*"
      Serial.println(timeStringBuff);

      //Optional: Construct String object
      String asString(timeStringBuff);
    }

The overload for `Serial.print` also does [this exact same thing][2]:

<!-- language: lang-cpp -->

    size_t Print::print(struct tm * timeinfo, const char * format)
    {
        const char * f = format;
        if(!f){
            f = "%c";
        }
        char buf[64];
        size_t written = strftime(buf, 64, f, timeinfo);
        print(buf);
        return written;
    }

  [1]: http://www.cplusplus.com/reference/ctime/strftime/
  [2]: https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/Print.cpp#L149


message:
Capacitors, Arduinos and Saving Data

In short, I have programmed and wired a speed/odometer and all is working well. However, I need to save data from the components/sensors once a power button is pressed, which has led me down the road of capacitors which seem to be the solution to my problem. Reading online about capacitors has dropped me in the deep end where I would like some help to see if I am thinking right.

I have attached a clearly very crude circuit which I need someone to confirm if I have it correct. If it's important, the whole system ran on 5v, powered by a 9v battery. Is a 5v Capacitor even the right one to use, considering that most components will not be active at the point of powering down?

OLD IMAGE: https://i.stack.imgur.com/aXhRi.jpg
NEW IMAGE: https://imgur.com/a/aHRpzE4

Just tried to download the app and it's not happening for some reason, so the link(edited) will have to do, I'm sorry.

body:
Just slapping a random capacitor across your supply is not going to work. It's far more complex than that.

Yes, a capacitor is used to store a charge, but you have to manage that charge properly or you won't get much of a chance to do anything with it.

You need to:

1. Ensure that the discharge voltage remains high enough to run the chip for long enough to save your data (Note: writing to EEPROM causes an increase in current)
2. Isolate the capacitor from the rest of the circuit so it only powers the main chip
3. Monitor the incoming power to know when to do the saving.

A block-diagram of your setup may look something like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/NdcI1.png)

<!-- End schematic -->

In that diagram R1 and R2 form a voltage divider so you can monitor the battery voltage. C1 is a *big* capacitor. We're talking super-cap teritory here. Rated at 9V *minimum*. The regulator on the Arduino is ignored. You don't want to use it.  *Two* external regulators are now used to power your project - one direct from the battery to run the breadboard and other external components (which will lose power immediately the battery power is removed) and the other to run the main MCU and nothing else.  The second regulator is isolated from the rest of the circuit by D1, and the capacitor's charge then can only go through that regulator to power the main MCU.

That regulator for the MCU should be a switching regulator (DC-DC, "buck" regulator).  If you use a linear ("LDO") regulator you will waste power and your capacitor will have to be two or three times bigger than otherwise.  Even better would be to have a "buck-boost" regulator that will boost the voltage up to 5V when the input voltage drops below 5V, thus giving you even more life from the capacitor.

An alternative to all this is to use the 47C16 chip (5V) or [47L16](https://majenko.co.uk/product/47l16-eeram-breakout) chip (3.3V) to store your data. This is an "EERAM" chip - an EEPROM with RAM buffer and automatic saving to EEPROM at power failure. It works through I2C and needs a capacitor connected to it directly to provide the backup power while it stores the data to EEPROM.


message:
How can I loop my code? For example after 30 minutes?

So I have this code which records the temperature and humidity using a DHT22 sensor. After it get's the values it then sends it to a webpage using PHP $_GET method, where that gets imported into a DB and emails (using PHP). But this only happens when I upload the code to my ESP8266; how can I know build in a loop function that it sends it every 30 mins or given time?

    #include <ESP8266WiFi.h>
    #include "DHT.h"

    const char* ssid     = "bbox2";      // SSID of local network
    const char* password = "azerty";   // Password on network

    WiFiClient client;
    char servername[]="lucasdebelder.be";  // remote server we will connect to
    String result;

    float temperature;
    float humidity;

    #define DHTPIN 14

    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);

    void setup() {
      dht.begin();
      delay(2000);
      Serial.begin(115200);
      Serial.println("Connecting");
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(100);
      }
      Serial.println("Connected");
      delay(1000);
      readSensor();
      String temperatureString = String(temperature,1);
      String humidityString = String(humidity,1);
      sendDataToServer(temperatureString,humidityString);
    }

    void loop() {

    }

    void sendDataToServer(String temperature, String humidity)
    {
      if (client.connect(servername, 80)) {  //starts client connection, checks for connection
        Serial.println("connected");
        client.println("GET /send_temperature.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
        client.println("Host: lucasdebelder.be");
        client.println("Connection: close");  //close 1.1 persistent connection
        client.println(); //end of get request
      }
      else {
        Serial.println("connection failed"); //error message if no client connect
        Serial.println();
      }

     while(client.connected() && !client.available()) delay(1); //waits for data
      while (client.connected() || client.available()) { //connected or data available
        char c = client.read(); //gets byte from ethernet buffer
          result = result+c;
        }

      client.stop(); //stop client
      Serial.println(result);

    }

    void readSensor()
    {

      humidity = dht.readHumidity();
      temperature = dht.readTemperature();
      Serial.println("Temperature:");
      Serial.println(temperature);
      Serial.println("Humidity:");
      Serial.println(humidity);

    }

body:
You execute the corresponding function only in the `setup()` function, which is called once on startup of the ESP. After that the `loop()` function is called repeatedly. The `setup()` function is meant to "setup" your code for it's functionality, which is then executed in the `loop()` function. For example you are begin the Wifi connection and connect to a network in there, because you need the network for your main functionality.

So you have to put the code from `readSensor()` until (and including) `sendDataToServer()` into the `loop()` function. This will execute this code repeatedly.

Then you have to introduce some concept of time, else your code will be executed very fast, effectively flooding your webserver. The easiest way would be to add a call to `delay(30000)`, which would delay the code for 30s. But using delay is not considered good coding style, since it is basically busy waiting and you cannot do anything else during that time.

So to be able to add other functionalities in the future you can implement the time concept with non-blocking code. Take the `BlinkWithoutDelay` example from the Arduino IDE as reference. It uses the `millis()` function, which counts the milliseconds since the startup. You save a timestamp of the last execution of your code and wait until the difference between the current time (given by `millis()`) and your timestamp is greater than 30s. In this time the ESP can do other things, since it still goes through the `loop()` function undisrupted. Then after the timespan you execute the code and reset the timestamp to the current time.


body:
As stated in the previous answer. Code that needs to run more than one time should be called in the loop. But in this case the following solution will work as well.

You can end your setup with a call to the `deepsleep(time_us)` function which can be found in the [ESP library](https://github.com/esp8266/Arduino). This will shutdown everything except for the on board RTC(Real Time Clock). So the circuit only draws a very little current (20 uA). This can be very useful if the circuit is powered by a battery.

The RTC has a signal on GPIO 16 (D0 on NodeMcu) which will be held HIGH while the given time is not reached. If the given time is reached the signal will be LOW.

If you connect GPIO 16 to the RST(reset) pin, this will make the ESP8266 start-up again. And thus the `setup()` will be executed again.


message:
Setting 10 RGB Strips Independently from Single Arduino

I want to control 10 different 12V RGB LED strips independently from a single Arduino.

As a clarification - I've setup a bunch of NeoPixels and understand how to wire and control them independently. So now I'm looking to do something similar but rather than set color of individual LED's, I'm looking to set color of LED strips.

I've already done all the research to understand how to use a MOSFET to control a single strip - but that requires 3 PWM outputs on the Arduino board and I don't see any boards that have 3 * 10 = 30 PWM outputs.

Are there existing controllers that can abstract the power conversion and voltage control, so I can just send a color and brightness setting from the Arduino to each strip?

body:
You'll need external circuitry to control the actual LEDs.

There is the [WS2811 chip](https://cdn-shop.adafruit.com/datasheets/WS2811.pdf) which can control 3 channels of 12V LED strips controlled though a single wire and you can daisy chain them controlling each strip individually. The protocol is the exact same as you'll find in individually addressable RGB LEDS. In fact it's the same IC that is embedded in those LEDs.


body:
You could use chainable RGB drivers like these:

[<img src="https://i.stack.imgur.com/CRuWA.jpg" width="300"/>](https://i.stack.imgur.com/CRuWA.jpg)

They are based on the P9813 chip and can be used with the [FastLED library](https://github.com/FastLED/FastLED).
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".

Wiring:

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

Example code:

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

    #include <FastLED.h>

    #define NUM_LEDS 10
    #define DATA_PIN 3
    #define CLOCK_PIN 2

    CRGB leds[NUM_LEDS];

    void setup() {
        FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
    }

    int hue = 0;
    void loop(){
        for(int i = 0; i < NUM_LEDS; i++) {
            leds[i] = CHSV(hue + i*255/NUM_LEDS , 255, 255);
        }
        FastLED.show();
        delay(20);
        hue += 2;
    }

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


message:
LCD display weird characters

Im a newbie. I have a problem with displaying text in LCD (16x2). It shows incorrect message in the lcd. Here is the code and the picture that gives the wrong output : Kindly help Thank you.

    #include "SIM900.h"
    #include <SoftwareSerial.h>

    #include "sms.h"
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    //gsm
    SMSGSM sms;

    int numdata;
    boolean started  = false;
    char smsbuffer[160]; //message
    String newsms;
    char n[20];
    unsigned char i;
    //lcd
    int sensorPin = A0;    // select the input pin for the potentiometer
    int sensorValue = 0;  // variable to store the value coming from the sensor
    int outputValue = 0;   // value output to the %
    int outputValue1 = 0;   // value output to cursor

    void setup()
    {
      //Serial connection.
      //gsm
        lcd.begin(16, 2);

      Serial.begin(9600);

    //  lcd.setCursor(0, 1);
    //  lcd.clear();
    //  lcd.print("   Wireless Public       via GSM"); //55 chars
    //  lcd.setCursor(0, 2);
    //  lcd.print("    Notice Board "); //55 chars
       Serial.println("GSM Shield testing.");
      if (gsm.begin(2400)) {
        Serial.println("\nstatus=READY");
        started = true;
      }
      else Serial.println("\nstatus=IDLE");

      //lcd
      // set up the LCD's number of columns and rows:

    };

    void loop()
    {

      // read the value from the sensor:
      sensorValue = analogRead(sensorPin);
      // map it to the range of the analog out:
      outputValue = map(sensorValue, 0, 1023, 0, 100);
      outputValue1 = map(sensorValue, 0, 1023, 0, 200);

      //scroll = lcd.scrollDisplayLeft();
      if (started) {
        //Read if there are messages on SIM card and print them.
        if (gsm.readSMS(smsbuffer, 160, n, 20))
        {
          //lcd
          lcd.clear();
          lcd.setCursor(0, 2);
          lcd.print("SMS Received!");
          delay(2000);
          lcd.clear();
          lcd.setCursor(0,1);
          Serial.println(n);
          Serial.println(smsbuffer);
          lcd.print(smsbuffer);
          delay(1000);
    //      lcd.clear();
        }
        delay(1000);
      }
    }

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

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

body: The first thing to try is replacing `lcd.begin(16, 2)` with `lcd.begin(20, 4)`. The image of your LCD looks like a 20 char by 4 line display. Based on your comments, it seems that the SMS part of your code is working because it's outputting the correct characters to the serial monitor. I would focus on the LCD code and connections to your Arduino.


body:
I arrived a little late; however I'm leaving some further information to Debug similar problems for those who arrive here in the Future.

**Regarding the Question**

As already answered above:

 - You are specifying your LCD as a 16 Column with 2 Rows (1602); and in your picture you clearly have a 20 Column with 4 Rows.

**Change:**

    lcd.begin(16, 2);

**To:**

    lcd.begin(20, 4);

**How LCD Works**

Take into consideration that LCD works as a Matrix and both Columns and Rows are Zero Based Index.
That is; when you set the LCD Cursor Columns or Rows; you start counting with 0.

See Example Bellow:

    lcd.setCursor(0, 2);

The 1st Parameter (Zero) Represents Columns.

The 2nd (Two) Represents Rows.

Therefore on the 1st Parameter: "0" (Column); (Considering you're reading from Left to Right and Top to Bottom); You Set the Cursor on the very 1 Column on the LCD.

The 2nd Parameter (2): you’l be Setting char on the 3rd Row (Line).

**Note:** 3rd and not 2nd; because both Columns and Rows are "Zero Based" Indexed.

**Debugging LCD Issues**

1. Check If your LCD is Properly Wired. You may have switched a wire; wire not properly plugged or broken.
Specially if you’re not using a I2C back module). Wiring without I2C (“I Squared C”) module can be confusing in certain occasions.

2. Check your Library and Hardware.
Make sure you’re using the correct library (I2C library: if your LCD has the module: use a compatible I2C Library; and specify the LCD parameters accordingly).
In case you don’t have a I2C module; then use a library to with a workaround for that situation. (You specify all the Pins).

3. Check you Code:
Check the way you initialize your LCD.
i.e: lcd.begin(16,2); or lcd.begin(20, 4);

4. Make sure you print inside LCD Index.
Setting the cursor outside its bounds can also cause “weird” chars.

5. There can be other situations related with improper wiring or some sort of short circuit with other components connected to your project that can also produce weird characters.

6. In certain circumstances; pressing Reset; Cutting the Power for a little while or Re-Uploading the project fixes the issue.

7. Not clearing the LCD whenever there is New data can simulate the effect of weird characters; but actually they are old data characters that remained there.

**Writing Custom Characters to LCD**

As you've Probably Noticed you are Unable to print the a Custom Character (i.e: Degree Symbol) on your LCD.
That can be solved by Creating your own (Custom) char and Declare it on your Code.
I won't explain every detail, in order to avoid going off topic and to avoid providing an extensive and hard-to-read answer.
Instead will leave an example, that is easy to understand and 2 Links bellow with further information regarding Custom Characters.

**Links:**

- [More Information and Examples for Custom Characters][1].
- [LCD Character Generator][2]

**Example for Degree Character**

    /* LCD Custom Characters
    *******************************************/
    // This is your Char Definition in Bytes:
    byte DegreeDef[8] = { B01100, B10010, B10010, B01100, B00000, B00000, B00000, B00000 };

    // This is the byte Char to be used to write to LCD.
    const byte Degree = 0x2;

    void LCDInitialization()
    {
      // LCD Initialiation Code Here
      // ...

      // Initialize Custom Characters.
      lcd.createChar(2, DegreeDef);

      // Do Something Else...
    }

    void PrintToLCD()
    {
      // Note:
      // "lcd.write" is Different from "lcd.print".
      // Use "write" to Print your Custom LCD Characters.
      lcd.setCursor(0, 1);
      lcd.write(Degree);
    }

I hope this helps debugging your issue.

  [1]: https://www.engineersgarage.com/arduino/making-custom-characters-on-lcd-using-arduino/
  [2]: https://maxpromer.github.io/LCD-Character-Creator/


body:
Hello I had the same problem and noticed that if you setup the lcd screen in this order:

    LiquidCrystal lcd (d7, d6, d5, d4, , en, rs) ;

you get some weird character showing up...
but if you do this way:

    LiquidCrystal lcd (rs, en, d4, d5, d6, d7) ;

you don't get any weird character.


message:
Servo speed in a Toggle Code

I am new to Arduino and am trying to figure out servos. Right now I have a toggle button code for the servos. Although I want to know how to speed them up. Is there a way to do this?

Currently, this is my code:

    #include <Servo.h>
    int button = 5; //button pin, connect to ground to move servo
    int press = 0;
    Servo servo_7;
    Servo servo_8;
    Servo servo_9;
    Servo servo_10;
    boolean toggle = true;

    void setup()
    {

      pinMode(button, INPUT); //arduino monitor pin state
      servo_7.attach(7); //pin for servo control signal
      servo_8.attach(8);
      servo_9.attach(9);
      servo_10.attach(10);
      digitalWrite(5, HIGH); //enable pullups to make pin high
    }

    void loop()
    {
      press = digitalRead(button);
      if (press == LOW)
      {
        if(toggle)
        {

          servo_7.write(180);
          servo_8.write(180);
          servo_9.write(180);
          servo_10.write(180);
          toggle = !toggle;
        }
        else
        {

          servo_7.write(0);
          servo_8.write(0);
          servo_9.write(0);
          servo_10.write(0);

          toggle = !toggle;
        }
      }
      delay(100);  //delay for debounce
    }

body:
Normal servos have a speed. It's their speed, and you can't change it. You can make it appear slower by moving in small increments, but you can't actually change the speed it moves.

With constant rotation servos the "angle" dictates the rotation speed, but even with those there is nothing you can do to change the relationship between "angle" and rotational speed.

Other than buying a different servo with a different degrees-per-second rating.


message:
clear serial buffer not working

Also asked in forum.arduino.cc

    bool receive_command(char answer[]);
    void serial_flush(void);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      for(byte i=0;i<3;i++){
    if(receive_command("OK")) Serial.println("OK found");
     serial_flush();
      }
    }

    void loop() {}

    void serial_flush(void) {
      while (Serial.available()) Serial.read();
    }

    bool receive_command(char answer[]) {
     unsigned long _time = 0;
      const int max_time = 10000;
      bool flag = 0;

    Serial.print("in Serial buffer=");
      Serial.println(Serial.available());
      if(Serial.available()){
      Serial.write(Serial.read());
      Serial.println(" left in serial buffer");}

      while (Serial.available() < 2) {
    if ((millis() - _time) > max_time) {
          Serial.println("waited too long nothing received");
      return flag;
        }
        }
      do {
        if (Serial.findUntil(answer, '\n')) return flag = 1;
      } while (Serial.available());

    return flag;

    }

via serial monitor with CR+LF line ending I`m sending this string:
abcdefghijklmnopqrstuvwxyzOKabcdefghijklmnopqrstuvwxyz
26chars+OK+26chars+CR+LF=56 chars

Output:

    in Serial buffer=0
    OK found
    in Serial buffer=1
    b left in serial buffer
    in Serial buffer=0
    waited too long nothing received

after OK is found serial_flush() is executed but after second run there serial.available() shows there is something in serial buffer. right at that moment it was char 'b' but it also can show char 'd'  and 'c' depending how long it will run.

why serial_flush() is not clearing the buffer?

Thanks.

body:
The processor is somewhat faster than serial input. If you really want to wait for nothing more to arrive you should probably add a short delay (although jsotola's suggestion of looking for a newline is sensible). Something like:

    void serial_flush(void) {
     while (true)
       {
       delay (20);  // give data a chance to arrive
       if (Serial.available ())
         {
         // we received something, get all of it and discard it
         while (Serial.available ())
           Serial.read ();
         continue;  // stay in the main loop
         }
      else
        break;  // nothing arrived for 20 ms
       }
    }


body:
the second parameter of findUntil(target, terminator) is of type char* not char

your `Serial.findUntil(answer, '\n')` doesn't work and you patched it with `do while`.

use `Serial.findUntil(answer, "\n")`

'a' is read by readUntil, then it returns  because  of wrong parameter. serial_flush sees no new character. and next you read 'b' from buffer. the sketch runs fast compared to Serial speed. it sees always no or one new character in buffer if the previous was removed


message:
AT command parsing and listening for incoming SMS Arduino Leonardo SIM800H

I am trying to make a program that receives commands contained in SMS. The commands can be $CMD1 and $CMD2. Of course I need to verify the phone number of the sender by its last 6 digits. Other than this I have to ask and receive rtc clock information from the modem. AT commands format:
+CCLK: "YY/MM/DD,HH:MM:SS+TT" (works properly)
+CMTI: "SM",N (where N is the index number of the sms in the phone mem)
+CMGR: "REC READ","+1234567890","","04/01/01,00:00:00+00" (it reaches only the 15th char and hangs)

My code:

 const long interval = 1000;
 static long currentMillis;

 byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

 char serialdata[256]; //Array to store the chars before parsing

 char rtcy1[3]; //Current year  Format: yy\0
 char rtcm1[3]; //Current month  Format: mm\0
 char rtcd1[3]; //Current day  Format: dd\0
 char rtch1[3]; //Current hour  Format: hh\0
 char rtcmm1[3]; //Current minute  Format: mm\0
 char rtcs1[3]; //Current second  Format: ss\0

 char esemesemes[3];

 byte pointingfinger = 0;

 char enabledtime = 0;

 char cclkenabl = 0;

 char foundchar[6];

 byte cmtienabl = 0;

 byte witdqt = 0;

 byte acceptsms = 0;

 byte ocpos = 0;

 byte occurence = 0;

 byte cmgrenabl = 0;

 byte esemindex[3];

 char phone1[6] = {'5', '6', '7', '8', '9', '0'};

 char phone2[6];

 byte enableclock = 1;

 void setup() {
   Serial.begin(9600); //USB to Computer
   Serial1.begin(9600); //UART to Modem
   Serial1.print("ATE0\r"); //Disable echo
 }

 void loop() {
   if (millis() - currentMillis >= interval) //This is done every second
   {
  if (enableclock == 1) {
    Serial1.print("AT+CCLK?\r");
  }
  Serial.println("=========");
  Serial.print(serialdata[searchcharpos]);
  Serial.print(serialdata[searchcharpos + 1]);
  Serial.print(serialdata[searchcharpos + 2]);
  Serial.print(serialdata[searchcharpos + 3]);
  Serial.print(serialdata[searchcharpos + 4]);
  Serial.print(serialdata[searchcharpos + 5]);
  Serial.print(serialdata[searchcharpos + 6]);
  Serial.print(serialdata[searchcharpos + 7]);
  Serial.print(serialdata[searchcharpos + 8]);
  Serial.print(serialdata[searchcharpos + 9]);
  Serial.print(serialdata[searchcharpos + 10]);
  Serial.print(serialdata[searchcharpos + 11]);
  Serial.print(serialdata[searchcharpos + 12]);
  Serial.print(serialdata[searchcharpos + 13]);
  Serial.print(serialdata[searchcharpos + 14]);
  Serial.print(serialdata[searchcharpos + 15]);
  Serial.print(serialdata[searchcharpos + 16]);
  Serial.print(serialdata[searchcharpos + 17]);
  Serial.print(serialdata[searchcharpos + 18]);
  Serial.print(serialdata[searchcharpos + 19]);
  Serial.print(serialdata[searchcharpos + 20]);
  Serial.print(serialdata[searchcharpos + 21]);
  Serial.print(serialdata[searchcharpos + 22]);
  Serial.print(serialdata[searchcharpos + 23]);
  Serial.print(serialdata[searchcharpos + 24]);
  Serial.print(serialdata[searchcharpos + 25]);
  Serial.print(serialdata[searchcharpos + 26]);
  Serial.print(serialdata[searchcharpos + 27]);
  Serial.print(serialdata[searchcharpos + 28]);
  Serial.print(serialdata[searchcharpos + 29]);
  Serial.print(serialdata[searchcharpos + 30]);
  Serial.print ("=========");
  //Serial1.print("AT+CCLK?\r"); //ask for the time
  //delay(50);
  Serial.println("");
  Serial.println("=====");
  Serial.println(millis());

  if (enableclock == 1) {
    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);
  }
  enabledtime = 1;

  currentMillis = millis();
   }

   if (enabledtime == 1) {
  if (Serial1.available () > 0) {
    foundchar[0] = foundchar[1];
    foundchar[1] = foundchar[2];
    foundchar[2] = foundchar[3];
    foundchar[3] = foundchar[4];
    foundchar[4] = foundchar[5];
    foundchar[5] = Serial1.read();

    if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K' && foundchar[5] == ':' && enableclock == 1) {
   cclkenabl = 1;
   pointingfinger = 0;
    }

    if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'T' && foundchar[4] == 'I' && foundchar[5] == ':') {
   cmtienabl = 1;
   pointingfinger = 0;
   enableclock = 0;
    }

    if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'G' && foundchar[4] == 'R' && foundchar[5] == ':') {
   cmgrenabl = 1;
   pointingfinger = 0;
    }

    if (foundchar[0] == '$' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'D' && foundchar[4] == '1') {
   if (acceptsms == 1) {
     while (true) {
    Serial.println("CMD1");
     }
   }
    }

    if (foundchar[0] == '$' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'D' && foundchar[4] == '2') {
   if (acceptsms == 1) {
     Serial.println("CMD2");
   }
    }

    if (cclkenabl == 1) {
   while (foundchar[0] != '\n') {
     if (Serial1.available() > 0) {
    serialdata[pointingfinger] = foundchar[0];
    serialdata[pointingfinger + 1] = 0;
    pointingfinger++;
    foundchar[0] = foundchar[1];
    foundchar[1] = foundchar[2];
    foundchar[2] = foundchar[3];
    foundchar[3] = foundchar[4];
    foundchar[4] = foundchar[5];
    foundchar[5] = Serial1.read();

     }
   }
   cmgrenabl = 0;
   cclkenabl = 0;
   //pointingfinger = 0;
   enabledtime = 0;
   rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
   rtcy1[1] = serialdata[searchcharpos + 9];
   rtcy1[2] = '\0';
   rtcm1[0] = serialdata[searchcharpos + 11];
   rtcm1[1] = serialdata[searchcharpos + 12];
   rtcm1[2] = '\0';
   rtcd1[0] = serialdata[searchcharpos + 14];
   rtcd1[1] = serialdata[searchcharpos + 15];
   rtcd1[2] = '\0';
   rtch1[0] = serialdata[searchcharpos + 17];
   rtch1[1] = serialdata[searchcharpos + 18];
   rtch1[2] = '\0';
   rtcmm1[0] = serialdata[searchcharpos + 20];
   rtcmm1[1] = serialdata[searchcharpos + 21];
   rtcmm1[2] = '\0';
   rtcs1[0] = serialdata[searchcharpos + 23];
   rtcs1[1] = serialdata[searchcharpos + 24];
   rtcs1[2] = '\0';
    }

    if (cmtienabl == 1) {
   while (foundchar[0] != '\n') {
     if (Serial1.available() > 0) {
    serialdata[pointingfinger] = foundchar[0];
    serialdata[pointingfinger + 1] = 0;
    pointingfinger++;
    foundchar[0] = foundchar[1];
    foundchar[1] = foundchar[2];
    foundchar[2] = foundchar[3];
    foundchar[3] = foundchar[4];
    foundchar[4] = foundchar[5];
    foundchar[5] = Serial1.read();

     }
   }
   cmtienabl = 0;
   //pointingfinger = 0;
   enabledtime = 0;
   enableclock = 0;
   esemesemes[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
   esemesemes[1] = serialdata[searchcharpos + 9];
   esemesemes[2] = '\0';
   esemindex[0] = serialdata[searchcharpos + 12];
   esemindex[1] = '\0';
   Serial.println("CMTI");
   Serial.println(esemesemes[0]);
   Serial.println(esemesemes[1]);
   Serial.println(esemindex[1]);
   if (esemesemes[0] == 'S' && esemesemes[1] == 'M') {
     Serial1.println("AT+CMGF=1");
     Serial.println("AT+CMGF=1");
     delay(100);
     Serial1.println("AT+CMGR=1");
     Serial.println("AT+CMGR=1");
   }
   if (esemesemes[0] != 'S' || esemesemes[1] != 'M') {
     Serial1.println("AT+CMGD=4,1");
     Serial.println("Deleted");
   }
    }

    if (cmgrenabl == 1) {
   while (foundchar[0] != '\n') {
     if (Serial1.available() > 0) {
    serialdata[pointingfinger] = foundchar[0];
    serialdata[pointingfinger + 1] = 0;
    pointingfinger++;
    foundchar[0] = foundchar[1];
    foundchar[1] = foundchar[2];
    foundchar[2] = foundchar[3];
    foundchar[3] = foundchar[4];
    foundchar[4] = foundchar[5];
    foundchar[5] = Serial1.read(); //                       I THINK HERE WE HAVE SOME PROBLEM
    Serial.println("Searching");
    Serial.println(serialdata[pointingfinger]);
    Serial.println(pointingfinger);
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
     }
   }
   //pointingfinger = 0;
   enabledtime = 1;
   occurence = 0;
   ocpos = 0;
   Serial.println("mode1");
   while (occurence < 7) {
     Serial.println("mode2");
     if (serialdata[ocpos] == '\"') {
    Serial.println("mode3");
    occurence++;
    Serial.println(occurence);
     }
     Serial.println("mode4");
     ocpos++;
     Serial.println(ocpos);
   }
   witdqt = ocpos;
   Serial.println("PHONE1: ");
   Serial.print(serialdata[witdqt - 1]);
   Serial.print(serialdata[witdqt - 2]);
   Serial.print(serialdata[witdqt - 3]);
   Serial.print(serialdata[witdqt - 4]);
   Serial.print(serialdata[witdqt - 5]);
   Serial.print(serialdata[witdqt - 6]);
   Serial.println("");
    }
    acceptsms = 0;

    if (serialdata[witdqt - 1] == phone1[5] && serialdata[witdqt - 2] == phone1[4] && serialdata[witdqt - 3] == phone1[3] && serialdata[witdqt - 4] == phone1[2] && serialdata[witdqt - 5] == phone1[1] && serialdata[witdqt - 6] == phone1[0])
    {
   acceptsms = 1;
   Serial.println("Accepted");
    }

    if (serialdata[witdqt - 1] == phone2[5] && serialdata[witdqt - 2] == phone2[4] && serialdata[witdqt - 3] == phone2[3] && serialdata[witdqt - 4] == phone2[2] && serialdata[witdqt - 5] == phone2[1] && serialdata[witdqt - 6] == phone2[0])
    {
   acceptsms = 1;
   Serial.println("Accepted");
    }

    /*Serial.println("");
   Serial.print(foundchar[0]);
   Serial.print(foundchar[1]);
   Serial.print(foundchar[2]);
   Serial.print(foundchar[3]);
   Serial.print(foundchar[4]);
   Serial.print(foundchar[5]);
   Serial.println("");*/

  }
   }
 }

This is the Serial Monitor:
[![enter image description here][1]][1]

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

body:
You should throw away all your own code and read the serial data in a line at a time. Only once a complete line has been received should you then examine it to see what you have.

For example, here's something I just threw together based around a snippet I posted [here](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/):

    int readline(int readch, char *buffer, int len) {
      static int pos = 0;
      int rpos;

      if (readch > 0) {
        switch (readch) {
          case '\r': // Ignore CR
            break;
          case '\n': // Return on new-line
            rpos = pos;
            pos = 0;  // Reset position index ready for next time
            return rpos;
          default:
            if (pos < len-1) {
                buffer[pos++] = readch;
                buffer[pos] = 0;
            }
            break;
        }
      }
      return 0;
    }

    // ... later, in your loop:

    if (Serial1.available()) {
        // Read one character and send it to the readline function.
        if (readline(Serial1.read(), serialdata, 512)) { // do you really need 512 bytes of buffer?!?!

            // readline() told us we got a valid string. Let's
            // parse it.

            // If the string starts with '+CCLK: "'
            if (strncmp(serialdata, "+CCLK: \"", 8) == 0) {
                // Slice it up by the different delimiters
                // starting at the 9th character:
                char *cyear = strtok(serialdata + 8, "/");
                char *cmonth = strtok(NULL, "/");
                char *cday = strtok(NULL, ",");
                char *chour = strtok(NULL, ":");
                char *cmin = strtok(NULL, ":");
                char *csec = strtok(NULL, "+");

                // Check the last slicing worked
                if (sec != NULL) { // It parsed OK
                    // And convert each slice to a number.
                    year = atoi(cyear);
                    month = atoi(cmonth);
                    day = atoi(cday);
                    hour = atoi(chour);
                    minute = atoi(cmin);
                    sec = atoi(csec);

                    // Show the time.
                    Serial.print(F("The time is "));
                    Serial.print(minute);
                    Serial.print(F(" minutes past "));
                    Serial.println(hour);
                }
            }
        }

        // Do similar operations for the different possible messages
        // you may get.

    }


message:
Arduino Uno with Adafruit CC3000

I am using Arduino Uno with Adafruit CC3000 wifi shield to connect to the internet and get data for Arduino. Everything works fine but I can't figure out how to use **HttpClient** library. The code is:

    #include <Adafruit_CC3000.h>
    #include <SPI.h>
    #include "utility/debug.h"
    #include "utility/socket.h"
    #include <HttpClient.h>

    #define ADAFRUIT_CC3000_IRQ   3
    #define ADAFRUIT_CC3000_VBAT  5
    #define ADAFRUIT_CC3000_CS    10
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);

    #define WLAN_SSID       "ssid"
    #define WLAN_PASS       "pwd"
    #define WLAN_SECURITY   WLAN_SEC_WPA2

    void setConnection(){

         Serial.println("Initializing...");
         if (!cc3000.begin())
         {
           Serial.println("Couldn't begin()! Check your wiring?");
           while(1);
         }
         Serial.print("Attempting to connect to ");
         Serial.println(WLAN_SSID);
         if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
           Serial.println("Failed!");
           while(1);
         }
         Serial.println("Connected!");
         Serial.println(F("Request DHCP"));
         while (!cc3000.checkDHCP())
          {
              delay(100);
           }
         Serial.println(F("DHCP success!!"));
     }

    void dweet(){

      int ctr=0;
      char buff[100];
      int x=0;
      const char* host = "https://dweet.io/get/latest/dweet/for/dunebot";

      Serial.println(F("Initializing dweet client ..."));
      HttpClient client;
      client.get(host);
      Serial.println(F("Client Connected !"));

      while (client.available()) {
        char c = client.read();
        Serial.write(c);
        delay(100);
      }

    void setup(){

         Serial.begin(115200);
         while(!Serial);
         Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
         setConnection();

    }

    void loop(){
    dweet();
    }

If all worked fine then I should have got a json string which is:

    {"this":"succeeded","by":"getting","the":"dweets","with":[{"thing":"dunebot","created":"2018-05-12T13:27:56.106Z","content":{"0001":""}}]}

When I run the code, Arduino connects to the wifi network but afterwards when I observe the Serial monitor all I get are garbage values.

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

I need a way to read the key **0001** from the json string. Any help would be appreciated.Thanks.

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

body:
The `HttpClient` object must be instantiated with a `Client` object which will handle the underlying connection. [Source][1]:

> Requires a networking hardware and a library that provides transport specific Client instance, such as:

Refer to the following code:

* https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/examples/DweetGet/DweetGet.ino
* https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/Adafruit_CC3000.h#L86
* https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/src/HttpClient.h#L51

In the above example, it is done like

    WiFiClient wifi;
    HttpClient client = HttpClient(wifi, serverAddress, port);

Which means that for your code, you might want to pull out `client` as global object and instantiate it as:

    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);
    /* Create new Adafruit_CC3000_Client object */
    Adafruit_CC3000_Client cc3000_client;
    /* Feed this into the client */
    HttpClient client (cc3000_client, "dweet.io", 80);

You should also use the example code to see how to print the response after executing `client.get()`:

      // read the status code and body of the response
      statusCode = client.responseStatusCode();
      response = client.responseBody();
      Serial.print("Status code: ");
      Serial.println(statusCode);
      Serial.print("Response: ");
      Serial.println(response);

The example code is pretty much example what you want, you just have to give it a `Adafruit_CC3000_Client` as the `Client`.

Full code:

    #include <Arduino.h>
    #include <Adafruit_CC3000.h>
    #include <SPI.h>
    #include "utility/debug.h"
    #include "utility/socket.h"
    #include <HttpClient.h>

    #define ADAFRUIT_CC3000_IRQ   3
    #define ADAFRUIT_CC3000_VBAT  5
    #define ADAFRUIT_CC3000_CS    10
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);
    /* Create new Adafruit_CC3000_Client object */
    Adafruit_CC3000_Client cc3000_client;
    /* Feed this into the client */
    HttpClient client (cc3000_client, "dweet.io", 80);

    #define WLAN_SSID       "ssid"
    #define WLAN_PASS       "pwd"
    #define WLAN_SECURITY   WLAN_SEC_WPA2

    int statusCode = 0;
    String response;

    void setConnection(){

     Serial.println("Initializing...");
     if (!cc3000.begin())
     {
      Serial.println("Couldn't begin()! Check your wiring?");
      while(1);
     }
     Serial.print("Attempting to connect to ");
     Serial.println(WLAN_SSID);
     if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
      Serial.println("Failed!");
      while(1);
     }
     Serial.println("Connected!");
     Serial.println(F("Request DHCP"));
     while (!cc3000.checkDHCP())
     {
      delay(100);
     }
     Serial.println(F("DHCP success!!"));
    }

    void dweet(){

     int ctr=0;
     char buff[100];
     int x=0;
     const char* host = "https://dweet.io/get/latest/dweet/for/dunebot";

     Serial.println(F("Initializing dweet client ..."));

     client.get(host);
     Serial.println(F("Client Connected !"));

     // read the status code and body of the response
     statusCode = client.responseStatusCode();
     response = client.responseBody();
     Serial.print("Status code: ");
     Serial.println(statusCode);
     Serial.print("Response: ");
     Serial.println(response);

     /*
     Typical response is:
     {"this":"succeeded",
     "by":"getting",
     "the":"dweets",
     "with":[{"thing":"my-thing-name",
       "created":"2016-02-16T05:10:36.589Z",
       "content":{"sensorValue":456}}]}
     You want "content": numberValue
     */
     // now parse the response looking for "content":
     int labelStart = response.indexOf("content\":");
     // find the first { after "content":
     int contentStart = response.indexOf("{", labelStart);
     // find the following } and get what's between the braces:
     int contentEnd = response.indexOf("}", labelStart);
     String content = response.substring(contentStart + 1, contentEnd);
     Serial.println(content);

     //There was a missing brace here. Was the code cut off?!
    }

    void setup(){
     Serial.begin(115200);
     while(!Serial);
     Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
     setConnection();
    }

    void loop() {
     dweet();
    }

[1]: https://github.com/arduino-libraries/ArduinoHttpClient#dependencies


message:
ESP8266 sends data to the website but doesn't return status

I have problem with my esp8266 it connects to my site and sends 89 bytes of data but does return a confirmation status all i get is SEND OK but i don't get any confirmation from my server

This is my code below

     #include <SoftwareSerial.h>
    #include<time.h>

    SoftwareSerial ESP8266(3, 2); // RX, TX
    //DEFINE ALL GLOBAL VAARIABLES HERE
    unsigned int timeout_start_val;
    char scratch_data_from_ESP[20];//first byte is the length of bytes
    char payload[150];
    byte payload_size=0, counter=0;
    char ip_address[16];
    char youtube_subs[10];
    char youtube_views[13];
    char current_temp[5];
    char hi_temp[5];
    char lo_temp[5];

    //MODES
    const char CWMODE = '3';//CWMODE 1=STATION, 2=APMODE, 3=BOTH
    const char CIPMUX = '1';//CIPMUX 0=Single Connection, 1=Multiple Connections
    //PASS word

    const char SSID_ESP[]="Xamel";//"AOTEA TZ";//from constant

    const char SSID_KEY[]="cewu5103";//"wyrnC592";

    //DEFINE KEYWORDS HERE
    const char keyword_OK[]="OK";
    const char keyword_FAIL[]="FAIL";
    const char keyword_Ready[] = "Ready";
    const char keyword_no_change[] = "no change";
    const char keyword_blank[] = "#&";
    const char keyword_ip[] = "192.";
    const char keyword_rn[] = "\r\n";
    const char keyword_quote[] = "\"";
    const char keyword_carrot[] = ">";
    const char keyword_sendok[] = "SEND OK";
    const char keyword_linkdisc[] = "Unlink";
    const char keyword_CHECKCWMODE[] = "+CWMODE:3";
    const char keyword_URL_CONNECTION_ERROR[]="Link typ ERROR";
    const char TEST_URL[]="";

    const char GET_URL[]="GET /ESP8266_BackEnd/SaveDetail.php?Name=";
    int str1=strlen(GET_URL);
    const char Name[]="Alex ";
    int str2=strlen(Name);

    const char TRAILING_URL[]="HTTP/1.1 \\r\\nHost: www.pick2get.com\\r\\n\\r\\n";
    int str3=strlen(TRAILING_URL);
    int strTotal=str1+str2+str3;

    const char AT_CIPSTART[]="AT+CIPSTART=4,\"TCP\",\"pick2get.com\",80 \r\n";
    const char AT_CIPSEND[]="AT+CIPSEND=4,";
    //function prototype
    boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode);
    void serial_dump_ESP();
    boolean setup_ESP(const char SSID_ESP[],const char SSID_KEY);
    String url="&School=4D616B6F6E676F";
    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      //.print("Total string length");Serial.println(strTotal);

      // set the data rate for the SoftwareSerial port
      ESP8266.begin(9600);
      //

      //Serial.println(read_until_ESP(keyword_URL_CONNECTION_ERROR,sizeof(keyword_URL_CONNECTION_ERROR),5000,0));
      setup_ESP(SSID_ESP,SSID_KEY);

      ESP8266.print(AT_CIPSTART);
      ESP8266.print("");
      delay(1000);

      ESP8266.print(AT_CIPSEND);
      ESP8266.print(strTotal);
      ESP8266.print("\r\n");
      delay(1000);
      ESP8266.print("");
      ESP8266.print(GET_URL);
      ESP8266.print(Name);
      ESP8266.print(TRAILING_URL);
      delay(1000);
      ESP8266.print("");
      //ESP8266.println("&Grade=466F726D204F6E65");
      //ESP8266.println("&DeviceIP=3139322E3136382E302E31");
      //ESP8266.println(TRAILING_URL);

    }

    void loop() { // run over and over
      byte buffer[300];
      if (ESP8266.available()) {
       Serial.write(ESP8266.read());
      }
      if (Serial.available()) {
        ESP8266.write(Serial.read());
      }
    }

This is the output generated on the serial monitor

    ESP CHECK OK
    ESP RESET OK
    ESP RESET OK
    timeout
    ESP CWMODE SET FAILED
    CWMODE ALREADY SET
    SETTING SSID_ESP: Xamel
    SETTING SSID_KEY: cewu5103
    ESP SSID SET OK DEVICE CONNECTED
    CHECKING FOR AN IP ADDRESS
    IP ADDRESS = 192.168.4.1
    ESP CIPMUX SET
    AT+CIPSTART=4,"TCP","pick2get.com",80

    OK
    Linked
    AT+CIPSEND=4,89

    > GET /ESP8266_BackEnd/SaveDetail.php?Name=Alex HTTP/1.1 \r\nHost: www.pick2get.com\r\n\r\n
    SEND OK

    OK
    Unlink

Can any one please help here.

When adding ESP8266.print("+IPD\r\n"); this is the output i get

        ESP CHECK OK
    ESP RESET OK
    ESP RESET OK
    timeout
    ESP CWMODE SET FAILED
    CWMODE ALREADY SET
    SETTING SSID_ESP: Xamel
    SETTING SSID_KEY: cewu5103
    ESP SSID SET OK DEVICE CONNECTED
    CHECKING FOR AN IP ADDRESS
    IP ADDRESS = 192.168.4.1
    ESP CIPMUX SET
    AT+CIPSTART=4,"TCP","pick2get.com",80

    AT+CIPSEND=4,89

    busy p...

    OK
    Linked
    GET /ESP8266_BackEnd/SaveDetail.php?Name=Alex HTTP/1.1 \r\nHost: www.pick2get.com\r\n\r\n

    wrong syntax

    ERROR
    AT+IPD

    ERROR

I have managed to fix the lack of server response by removing the \\r\\n \nd replacing them with regular \r\n\r\n

    enter code here
    const char TRAILING_URL[]="HTTP/1.1 \r\nHost: www.pick2get.com \r\n\r\n";
    int str3=strlen(TRAILING_URL);
    int strTotal=str1+str2+str3;

    const char AT_CIPSTART[]="AT+CIPSTART=4,\"TCP\",\"pick2get.com\",80 \r\n";
    const char AT_CIPSEND[]="AT+CIPSEND=4,";
At this lines and was able to get a server response

+IPD,4,392:HTTP/1.1 400 Bad Request
Date: Tue, 15 May 2018 12:07:08 GMT
Server: Apache
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>400 Bad Request</title>
<bod^R
Bad Request

Your browser sent a request that this server could not understand.

finally i have debugged and fixed all the errors and the code works just fine
This and server returns a status 200

turns out it was just me pointing GET request in the wrong folder path with this line code at in the GET_URL variable

const char GET_URL[]="GET pick2get.com/ESP8266_BackEnd/SaveDetail.php?Name=";

I replaced with this

const char GET_URL[]="GET /ESP8266_BackEnd/SaveDetail.php?Name=";

And got the desired result

+IPD,4,166:HTTP/1.1 200 OK
Date: Tue, 15 May 2018 12:2249 GMT
Server: Apache
Upgrade: h2
Connection: Upgrade
Transfer-Encoding: chunked
Content-Type: text/html

2

OK

+IPD,4,191:16
Connected successfully
5c
 DATA TRANSMITTED SUCSSEFULLYSTUDENT NAME RECIVED: Alex
STUDENT SCHOOL NAME RECIVED:

3b
STUDENT GRADE RECIVED:
DEVICE IP ADDREESS RECIVED:

OK

+IPD,4,42:1f
New record created successfully
0
Thanks a lot guys below is the complete working code

        /*
      Software serial multple serial test

     Receives from the hardware serial, sends to software serial.
     Receives from software serial, sends to hardware serial.

     The circuit:
     * RX is digital pin 10 (connect to TX of other device)
     * TX is digital pin 11 (connect to RX of other device)

     Note:
     Not all pins on the Mega and Mega 2560 support change interrupts,
     so only the following can be used for RX:
     10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

     Not all pins on the Leonardo and Micro support change interrupts,
     so only the following can be used for RX:
     8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

     created back in the mists of time
     modified 25 May 2012
     by Nolawi solomon

     */
    #include <SoftwareSerial.h>
    #include<time.h>

    SoftwareSerial ESP8266(3, 2); // RX, TX
    //DEFINE ALL GLOBAL VAARIABLES HERE
    unsigned int timeout_start_val;
    char scratch_data_from_ESP[20];//first byte is the length of bytes
    char payload[150];
    byte payload_size=0, counter=0;
    char ip_address[16];

    //MODES
    const char CWMODE = '3';//CWMODE 1=STATION, 2=APMODE, 3=BOTH
    const char CIPMUX = '1';//CIPMUX 0=Single Connection, 1=Multiple Connections
    //PASS word

    const char SSID_ESP[]="Xamel";//"AOTEA TZ";//from constant

    const char SSID_KEY[]="cewu5103";//"wyrnC592";

    //DEFINE KEYWORDS HERE
    const char keyword_OK[]="OK";
    const char keyword_FAIL[]="FAIL";
    const char keyword_Ready[] = "Ready";
    const char keyword_no_change[] = "no change";
    const char keyword_blank[] = "#&";
    const char keyword_ip[] = "192.";
    const char keyword_rn[] = "\r\n";
    const char keyword_quote[] = "\"";
    const char keyword_carrot[] = ">";
    const char keyword_sendok[] = "SEND OK";
    const char keyword_linkdisc[] = "Unlink";
    const char keyword_CHECKCWMODE[] = "+CWMODE:3";
    const char keyword_URL_CONNECTION_ERROR[]="Link typ ERROR";
    //const char TEST_URL[]="";

    const char GET_URL[]="GET /ESP8266_BackEnd/SaveDetail.php?Name=";
    int str1=strlen(GET_URL);
    const char Name[]="Alex ";
    int str2=strlen(Name);

    const char TRAILING_URL[]="HTTP/1.1\r\nHost: www.pick2get.com \r\n\r\n";
    int str3=strlen(TRAILING_URL);
    int strTotal=str1+str2+str3;

    const char AT_CIPSTART[]="AT+CIPSTART=4,\"TCP\",\"pick2get.com\",80 \r\n";
    const char AT_CIPSEND[]="AT+CIPSEND=4,";
    //function prototype
    boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode);
    void serial_dump_ESP();
    boolean setup_ESP(const char SSID_ESP[],const char SSID_KEY);
    //String url="&School=4D616B6F6E676F";
    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      //.print("Total string length");Serial.println(strTotal);

      // set the data rate for the SoftwareSerial port
      ESP8266.begin(9600);
      //

      //Serial.println(read_until_ESP(keyword_URL_CONNECTION_ERROR,sizeof(keyword_URL_CONNECTION_ERROR),5000,0));
      setup_ESP(SSID_ESP,SSID_KEY);

      ESP8266.print(AT_CIPSTART);
      ESP8266.print("");
      delay(1000);

      ESP8266.print(AT_CIPSEND);
      ESP8266.print(strTotal);
      ESP8266.print("\r\n");
      delay(1000);
      ESP8266.print("");
      ESP8266.print(GET_URL);
      ESP8266.print(Name);
      ESP8266.print(TRAILING_URL);
      //delay(3000);
      //ESP8266.print("");
      //delay(2000);
      //ESP8266.print("\r\n");
      //delay(2000);
      //ESP8266.print("");
      //ESP8266.print("AT+IPD\r\n");
      //ESP8266.println("&Grade=466F726D204F6E65");
      //ESP8266.println("&DeviceIP=3139322E3136382E302E31");
      //ESP8266.println(TRAILING_URL);

    }

    void loop() { // run over and over
      byte buffer[300];
      if (ESP8266.available()) {
       Serial.write(ESP8266.read());
      }
      if (Serial.available()) {
        ESP8266.write(Serial.read());
      }
    }

    boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode){
      timeout_start_val=millis();//for the timeout
      char data_in[20];//this is the buffer - if keyword is longer than 20, then increase this
      int scratch_length=1;//the length of the scratch data array
      key_size--;//since we're going to get an extra charachter from the sizeof()

     //FILL UP THE BUFFER
     for(byte i=0; i<key_size; i++){//we only need a buffer as long as the keyword

                //timing control
                while(!ESP8266.available()){//wait until a new byte is sent down from the ESP - good way to keep in lock-step with the serial port
                  if((millis()-timeout_start_val)>timeout_val){//if nothing happens within the timeout period, get out of here
                    Serial.println("timeout");
                    return 0;//this will end the function
                  }//timeout
                }// while !avail

        data_in[i]=ESP8266.read();// save the byte to the buffer 'data_in[]

        if(mode==1){//this will save all of the data to the scratch_data_from
          scratch_data_from_ESP[scratch_length]=data_in[i];//starts at 1
          scratch_data_from_ESP[0]=scratch_length;// [0] is used to hold the length of the array
          scratch_length++;//increment the length
        }//mode 1

      }//for i

    //THE BUFFER IS FULL, SO START ROLLING NEW DATA IN AND OLD DATA OUT
      while(1){//stay in here until the keyword found or a timeout occurs

         //run through the entire buffer and look for the keyword
         //this check is here, just in case the first thing out of the ESP was the keyword, meaning the buffer was actually filled with the keyword
         for(byte i=0; i<key_size; i++){
           if(keyword1[i]!=data_in[i])//if it doesn't match, break out of the search now
           break;//get outta here
           if(i==(key_size-1)){//we got all the way through the keyword without breaking, must be a match!
           return 1; //return a 1 and get outta here!
           }//if
         }//for byte i

        //start rolling the buffer
        for(byte i=0; i<(key_size-1); i++){// keysize-1 because everthing is shifted over - see next line
          data_in[i]=data_in[i+1];// so the data at 0 becomes the data at 1, and so on.... the last value is where we'll put the new data
        }//for

               //timing control
                while(!ESP8266.available()){// same thing as done in the buffer
                  if((millis()-timeout_start_val)>timeout_val){
                    Serial.println("timeout");
                    return 0;
                  }//timeout
                }// while !avail

        data_in[key_size-1]=ESP8266.read();//save the new data in the last position in the buffer

          if(mode==1){//continue to save everything if thsi is set
          scratch_data_from_ESP[scratch_length]=data_in[key_size-1];
          scratch_data_from_ESP[0]=scratch_length;
          scratch_length++;
        }//mode 1

        /*  JUST FOR DEBUGGING
        if(ESP8266.overflow())
        Serial.println("*OVER");
        */

      }//while 1

    }//read until ESP

    boolean setup_ESP(const char SSID_ESP[],const char SSID_KEY[]){//returns a '1' if successful

      ESP8266.print("AT\r\n");// Send just 'AT' to make sure the ESP is responding
      //this read_until_... function is used to find a keyword in the ESP response - more on this later and in the function itself
      if(read_until_ESP(keyword_OK,sizeof(keyword_OK),5000,0))//go look for keyword "OK" with a 5sec timeout
        Serial.println("ESP CHECK OK");
      else
        Serial.println("ESP CHECK FAILED");
      serial_dump_ESP();//this just reads everything in the buffer and what's still coming from the ESP

       ESP8266.print("AT+RST\r\n");// Give it a reset - who knows what condition it was in, better to start fresh
      if(read_until_ESP(keyword_Ready,sizeof(keyword_Ready),5000,0))//go look for keyword "Ready" - takes a few seconds longer to complete
        Serial.println("ESP RESET OK");//depneding on the FW version on the ESP, sometimes the Ready is with a lowercase r - ready
      else
        Serial.println("ESP RESET FAILED");
      serial_dump_ESP();
      ESP8266.print("AT+RST\r\n");// Give it a reset - who knows what condition it was in, better to start fresh
      if(read_until_ESP(keyword_Ready,sizeof(keyword_Ready),5000,0))//go look for keyword "Ready" - takes a few seconds longer to complete
        Serial.println("ESP RESET OK");//depneding on the FW version on the ESP, sometimes the Ready is with a lowercase r - ready
      else
        Serial.println("ESP RESET FAILED");
      serial_dump_ESP();

       ESP8266.print("AT+CWMODE=");// set the CWMODE
       ESP8266.print(CWMODE);//just send what is set in the constant
       ESP8266.print("\r\n");
      if(read_until_ESP(keyword_OK,sizeof(keyword_OK),1000,0))//go look for keyword "OK"
        Serial.println("ESP CWMODE SET");
      else

        Serial.println("ESP CWMODE SET FAILED");//probably going to fail, since a 'no change' is returned if already set - would be nice to check for two words
        ESP8266.println("AT+CWMODE?");
        if(read_until_ESP(keyword_CHECKCWMODE,sizeof(keyword_CHECKCWMODE),1000,0))
        {
          Serial.println("CWMODE ALREADY SET");
          serial_dump_ESP();
        }
        serial_dump_ESP();

       //Here's where the SSID and PW are set
       Serial.print("SETTING SSID_ESP: ");
       Serial.println(SSID_ESP);
       Serial.print("SETTING SSID_KEY: ");
       Serial.println(SSID_KEY);
       //DEbug poin

       ESP8266.print("AT+CWJAP=");//
       ESP8266.print("\"");
       ESP8266.print(SSID_ESP);//
       ESP8266.print("\",\"");
       ESP8266.print(SSID_KEY);//
       ESP8266.print("\"\r\n");
      if(read_until_ESP(keyword_OK,sizeof(keyword_OK),5000,0)==1)//go look for keyword "OK"
        Serial.println("ESP SSID SET OK DEVICE CONNECTED");
      else if(read_until_ESP(keyword_FAIL,sizeof(keyword_FAIL),5000,0)==1)
        Serial.println("ESP SSID SET FAILED");
      serial_dump_ESP();

      //This checks for and stores the IP address
      Serial.println("CHECKING FOR AN IP ADDRESS");
      ESP8266.print("AT+CIFSR\r\n");//command to retrieve IP address from ESP
      if(read_until_ESP(keyword_rn,sizeof(keyword_rn),10000,0)){//look for first \r\n after AT+CIFSR echo - note mode is '0', the ip address is right after this
      if(read_until_ESP(keyword_rn,sizeof(keyword_rn),1000,1)){//look for second \r\n, and store everything it receives, mode='1'
        //store the ip adress in its variable, ip_address[]
        for(int i=1; i<=(scratch_data_from_ESP[0]-sizeof(keyword_rn)+1); i++)//that i<=... is going to take some explaining, see next lines
           ip_address[i] = scratch_data_from_ESP[i];//fill up ip_address with the scratch data received
    //i=1 because i=0 is the length of the data found between the two keywords, BUT this includes the length of the second keyword, so i<= to the length minus
    //size of teh keyword, but remember, sizeof() will return one extra, which is going to be subtracted, so I just added it back in +1
        ip_address[0] = (scratch_data_from_ESP[0]-sizeof(keyword_rn)+1);//store the length of ip_address in [0], same thing as before
        Serial.print("IP ADDRESS = ");//print it off to verify
        for(int i=1; i<=ip_address[0]; i++)//send out the ip address
        Serial.print(ip_address[i]);
        Serial.println("");
      }}//if first \r\n
      else
      Serial.print("IP ADDRESS FAIL");
      serial_dump_ESP();

       ESP8266.print("AT+CIPMUX=");// set the CIPMUX
       ESP8266.print(CIPMUX);//from constant
       ESP8266.print("\r\n");
      if(read_until_ESP(keyword_OK,sizeof(keyword_OK),5000,0))//go look for keyword "OK" or "no change
        Serial.println("ESP CIPMUX SET");
      else
        Serial.println("ESP CIPMUX SET FAILED");
      serial_dump_ESP();

     //that's it!  Could be done by nesting everything together, so if one thing fails, it returns '0', and if it gets all the way through it returns '1'...oh well

    }//setup ESP

    //pretty simple function - read everything out of the serial buffer and whats coming and get rid of it
    void serial_dump_ESP(){
      char temp;
      while(ESP8266.available()){
        temp =ESP8266.read();
        delay(1);//could play around with this value if buffer overflows are occuring
      }//while

    }//serial dump

body:
You need to have "Connection: keep-alive" in your http header, default is "Connection: close" and that's why you never get anything in return from the server.

I have described it all together with a code sample in https://arduino.stackexchange.com/a/54558/48149

The code sample uses the library WifiEsp to connect to ESP8266.


message:
Using a 3V latching relay to power up ESP8266

I'm trying to use a 2-Coil Latching Relay like [TXS2SA-L2-3V][1] for  powering up a ESP8266. My idea is to activate the relay by setting the first coil to high and deactivate the coil by setting the second coil to high. In my circuit i will set the second coil to high at the end of the code by the esp8266. I need the latching (holding the power) function of it. Because when somebody activtes the Deep Sleep function to early, I have no electricity to power the esp8266.

My question is:

What kind of circuit I must use? I have no idea where I can start.

I have a regulator that can be enabled via de EN signal.

Thanks in advance!

[![TPS61200 regulator][2]][2]

  [1]: https://www.digikey.com/products/en?keywords=255-2347-5-ND
  [2]: https://i.stack.imgur.com/ZIiOe.png

body:
You use a latching relay of this form in the exact same way as a normal relay - it's just there's two of them.

One coil you want to control with a button (power on) and the other with a transistor (and possibly an "off" button as well).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/YlxPM.png)

<!-- End schematic -->

Press ON to latch the relay into the ON position (NO -> COM). Activate M1 or press OFF to latch the relay into the OFF position (NC -> COM).


message:
Arduino SocketIO library not working over HTTPS

I am currently using this [Socket.io library][1] to be able to send data from the Adafruit Feather HUZZAH (based on ESP8266) to my NodeJS server. It works like a charm on my local webserver, never failing me. However, when I try the setup with the proper webapp hosted on Heroku, the command `SocketIOClient::connect(host, port)` fails and no connection is established with the webserver's SocketIO.

Since there is no mention of limitations with HTTPS connections, I assume that I might be doing something wrong. If the impossibility of having HTTPS connection is the case, however, is there any other way to send this kind of data through web sockets to a NodeJS server hosted on Heroku?

  [1]: https://github.com/washo4evr/Socket.io-v1.x-Library

body:
For anyone having the same issues with SocketIO and the ESP8266, [this issue][1] on Github explains how I solved it:

> When specifying the host, avoid including the `http://` or any other trailing slashes.
So it became `String host = "something.herokuapp.com";`

  [1]: https://github.com/washo4evr/Socket.io-v1.x-Library/issues/55


message:
how to send data to 15 meters with KY-005

I am using the LED [KY-005][1] as emitter and the [KY-022][2] as a receiver, according to their specifications they reach 18 meters.
I have performed the tests and it supports more than ten meters, however after the 6 meters the data is not received correctly. For example, I send 0xa90 but any other value except the desired one arrives at the receiver.
Here I leave the connection diagram:
[![enter image description here][3]][3]

This is the code that I use to send data:

    #include <IRremote.h>
    IRsend irsend;

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

    void loop()
    {
       for (int i = 0; i < 50; i++) {
         irsend.sendSony(0xa90, 12); // Sony TV power code
         delay(40);
       }
    }

  [1]: https://arduinomodules.info/ky-005-infrared-transmitter-sensor-module/
  [2]: https://arduinomodules.info/ky-022-infrared-receiver-module/
  [3]: https://i.stack.imgur.com/D3tCx.png

body:
In the emitter breakout board there is only a LED, nothing more. Comments in the linked page of the supplier states, that the 5V pin of it is not connected to anything. This means you are driving the LED directly from the Arduinos pin, which cannot provide more than 40mA. The supplier states a forward current from 30 to 60mA. You can use a small MOSFET in combination with a resistor, that limits the current to maybe 55mA, to drive the LED indirectly.

With this you won't fry the pins hardware and can provide more current, which means the LED can shine brighter. If you can find out, what LED is actually used for this board, you can refer directly to its datasheet. I couldn't find a part number at the site.


message:
Connect one HC-05 "master" to two slaves at the same time

Does any one know what `AT+CMODE=2` "slave loop" used for. As I try to connect one HC-05 master to two slaves using it, but it didn't work.
i donot know if AT+cmode=2 is used for connecting to multiple slaves or not as i want to know what is used for , i tried to understand what it do from the HC-05 datasheet but i didnot find anything useful about it excpet for what is this image

[![][1]][1]

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

body:
 `AT+CMODE`is mainly used for setting the address pairing purpose. What [chrisl][1] stated is exactly true, you cannot connect more than 1 slave to the master at a time. When you set the parameter as `2` you actually set a passive connection, a connection between master and slave to receive the remote Bluetooth master device data and send it back to the master device. It is like a feedback-loop, and is mainly related for testing the connectivity and other features of the PAN (Personal Area Network). So actually whatever is received from the master, is sent back again to the master by the slave.

  [1]: https://arduino.stackexchange.com/questions/52723/connect-one-hc-05-master-to-two-slaves-at-the-same-time


body:
Based on the documentation :

Slave (slave role)----Passive connection;

Slave-Loop----Passive connection, receive the remote Bluetooth master device data and send it back to the master device;

Master (master role)----Inquire the near SPP Bluetooth slave device, build connection with it positively, and build up the transparent data transmission between master and slave device.

More info here : http://www.linotux.ch/arduino/HC-0305_serial_module_AT_commamd_set_201104_revised.pdf

So if you want your HC-05 master send : AT+ROLE=1

If you want it to connect to a device safely send : AT+CMODE=0 but you have then to specify what address ( AT+BIND=<address> )

If you want it to connect to all devices available send : AT+CMODE=1


message:
PWM should be applied to ENA or IN1/IN2 for L298N board for speed control

I am new to the Arduino stuff and I am using L298N to drive two DC motors. When I searched online for sample code, I noticed that there are two types of design.

One type uses analogWrite(pin, pwmOutput) to control PWM on IN1/IN2 pin to adjust speed, and the other uses digitalWrite(pin, HIGH/LOW) to control IN1/IN2 but use analogWrite(enA, pwmOutput) to control speed.

I guess probably both can work, but I just feel it is not right to apply PWM on the enable pin. Any suggestion from the experts?

One more thing, many people say L298N is obsolete. Would anyone please recommend a replacement motor drive module?

body:
I'd use `PWM` on `EN` input. Motor will be driven in `HIGH` and left floating in `LOW`. The other method means it'll be shorted (= full on brake).

`L298N` is based on bipolar transistors. That means relatively big voltage drop between drivers Emitter and Collector (about `2V` on each transistor), so there are big power losses (= heat).

Maybe something like `LMD18200` could be used as unipolar replacement.


message:
Arduino Mega resets when DFPlayer speaker plugged into amp!

I have a MP3 DFPlayer Mini connected to a Mega2560. I'm using serial to control it. The Mega is powering/grounding the DFPlayer, and USB is powering the Mega. If I plug a small speaker directly to the DFPlayer speaker pins, I hear the audio as expected. Tracks play correctly, at the proper volume, etc.

I also have a 20w audio amplifier (MAX9744, and 20w speaker ofc), powered separately by a 12v DC wall plug. If I plug an iPod into that via the stereo jack, I hear nice loud audio, as expected. Everything is fine.

For months, I have had the DFPlayer speaker pins supplying audio into the headphone jack on the amplifier. It has been working perfectly. Until recently...

Now, for some reason, the Mega2560 instantly resets, and will continue to reset every couple of seconds *while the speakers are plugged in to the amplifier*. As soon as the line in stereo jack is removed from the amplifier, the Mega works again.

This has me completely stumped. This setup has previously been working perfectly, for several months. The amplifier is clearly affecting the Mega somehow (via the DFPlayer!), even when no audio is actively playing. But I'm stuffed if I can figure out where the problem is!

I appreciate any ideas and suggestions you may have.

body:
For externally amplified speakers, you should be feeding the DAC and GND pins to the amp's inputs.  Those DAC pins provide a signal that varies by a small number of volts and is shifted so that they're always positive.  This is in the range expected by small headphones (ear buds) and [line level][1] inputs to audio components like an amplifier.

The speaker pins on the DF Player mini are pre-amplified (a little tiny bit) to directly drive a very small speaker (like 2 Watts at 8 Ohms).  They are a differential signal that includes both positive and negative voltages (relative to GND).  Note that the two speaker outputs (SPK+ and SPK-) are not left and right, but two sides of a differential signal.  Based on the [schematic on page 11 of the datasheet][2] (Chinese), it's a mono output made from mixing the outputs of the left and right DACs.

I could see how you might have gotten away with sending those to the amp, since the pre-amped speaker outputs are low power, and a good amp probably has input protection.

I don't know enough about electronics to know why it's failing now when it seemed to be working before.  It could be sensitive to the amplifier's gain or a ground loop between the power sources, but I'm just shooting in the dark.  Somehow, I suspect the DF Player Mini struggled to provide enough current to your amp, and since the DF Player Mini was powered from your Arduino, the Arduino essentially browned out, triggering a reset.

[1]: https://en.wikipedia.org/wiki/Line_level#Nominal_levels
[2]: https://github.com/0xcafed00d/yx5300/blob/master/docs/YX5300-24SS DEBUG manual V1.0.pdf


body: As Adrian McCarthy pointed out, you don't want to be running the speaker outputs into an amp like that. Use a DAC pin and Ground. As to why its stopped working - I've had trouble powering an arduino plus dfplayer from USB. The combination can quite easily draw more current than USB is designed to give. It's a bit fuzzy because not all USB supplies work exactly to proper spec. and exactly how much current you need can depend on factors as unpredictable as how much bass there is in your piece of music. If definitely nothing at all has changed in your setup, I would check in case you've got a joint going bad and shorting in the connection from the dfplayer to the amp...


message:
How to digital read and send the data through serial to PC with speed around 2 MHz?

I would like to read analog data with frequency sampling around 2 MHz and send it to PC to be processed with python for digital oscilloscope. I use Arduino Nano. I have found ADC (AD9057, [PDF][1]) that can handle up to 40 MSPS into 8 bits parallel, but I still face some problems

1. How could I read digital pin data quickly around 2-4 MHz? I read that it is possible using direct port manipulation.

2. How could I send the data to PC with that sampling rate? I know that the maximum baud rate of arduino is around 2.000.000 or let say 2 MegaBytes/s, so for 2 MHz sampling, i could only send one character per micro second, could it be more faster?

Thank you

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/AD9057.pdf

body:
In short? You can't.

To have a 2MHz transmission you need 2*Nbit MHz of serial clock to send it to the PC, where Nbit is the number of bits per sample. Since the minimum is 8, englecting the synchronization or additional bits the serial clock has to be at least 16MHz. Which is the system clock of the nano. So no way.

Now, with the alternatives. First question: what is your ADC's interface? I found the LTC2204. It is a parallel ADC, so you need something to convert it to anything readable by the PC.

I'm not sure about the feasibility of this, but a nano is not enough. I'd use an STM32 (because I have their Nucleo boards, but you can search for other 32-bit boards) and a high speed serial interface. Since even SPI can be slow, maybe ethernet needs to be used. I was not able to search for boards with native ethernet interface; anyway the STM32F4 microcontrollers should (see [this article][1]) have an ethernet interface and you will "only" need the PHY. I think that this is the only applicable way to follow..

  [1]: http://andybrown.me.uk/2012/09/01/ethernet-phy-stm32f107/