2

I'm trying to make a HTTP GET Request using arduino Mega 2560 with ESP82660, but it's always restarting my esp8266.

this is my approach:

    char *hello = "GET /api/bus/register?code=";
    strcat(hello,test);
    strcat(hello," HTTP/1.1\r\nHost: 192.168.88.233\r\nConnection:close\r\n\r\n");

    wifi.send((const uint8_t*)hello, strlen(hello));
    uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
    if (len > 0) {
    Serial.print("Received:[");
    for(uint32_t i = 0; i < len; i++) {
        Serial.print((char)buffer[i]);
    }
    Serial.print("]\r\n");
    }
0

1 Answer 1

4

You need to allocate a buffer large enough to hold your entire concatenated string, e.g:

char hello[256];
strcpy(hello, "GET /api/bus/register?code=");
strcat(hello, test);
strcat(hello," HTTP/1.1\r\nHost: 192.168.88.233\r\nConnection:close\r\n\r\n");

(The above code is still not safe, you will also need to check the size of test or use strncat)

The way you are doing it will cause an array overflow and possible memory corruption. This might be the cause of resetting your ESP82660, if corrupted data is sent with wifi.send.

Also you might need to strcat a newline after test if there isn't one there already.

Sign up to request clarification or add additional context in comments.

4 Comments

In Addition: malloc() a buffer of length strlen("GET ..") + strlen(test) + strlen(" HTTP...") + 1, then use strncat() or snprintf(buf, len, "%s%s%s", "GET..", test, " HTTP") on it and check the return value. This way you will know that you can allocate a buffer of the required length when malloc gives you a NON-NULL pointer, and also has the benefit of supporting an "arbitrary"-length test string.
malloc on Arduino is very inefficient and probably not even set up. Could be (I'm not sure) but it is very inefficient on AVR. Before you do malloc you still need to know string size for copy first. I'm not sure if malloc is great idea.
thank you so much this works fine for me :) thanks alot ;)
@MaximilianGerhardt remember that the total RAM available on the ATmega2560 is only 8Kb (on the 328 it's only 2Kb). In addition to string buffers there will be memory used by libraries (e.g. wifi library), serial buffers, call stack, other variables etc. In such a case it's simpler to have a hard limit for the string size. You could use malloc (if it's available) but the maximum length will be quite low, you might get fragmentation from repeated malloc and free, large allocations might cause subsequent allocations to fail etc etc. It's easier just to keep it simple when doing embedded coding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.