arduino-libraries / ArduinoHttpClient

Arduino HTTP Client library
288 stars 172 forks source link

Loop getting called before previous loop finishes? What is going on? #92

Open flagoworld opened 4 years ago

flagoworld commented 4 years ago

I am using a nano 33 IoT with WifiNINA 1.3 and this library. I am noticing some very strange behavior and I am wondering if this is normal and I am doin it wrong, or if something is actually wrong.

I have a simple program based on the example project. It makes a call to a URL (over https) repeatedly.

First

I noticed is that often the "get(/)" line will be printed to the serial monitor multiple times before ever receiving a response, if a response ever comes in. So I might ne "get(/)" 2-4 times and then finally "Status code", "Response", and "complete" are printed.

I thought there must be something wrong,... maybe some kind of issue with the serial monitor receiving things out of order. So I added the digitalWrite before and after the request. And then I added a log on the server to show whenever requests come in.

Sure enough, I am receiving every request made on the server, but the light will sometimes stay lit up for 2 or more requests before it shuts down, which reflects what I am seeing in the serial monitor.

How is this possible? It's as if loop() is firing before the previous loop() finished.

Second

Requests seem to be very, very slow. A simple plain text response whose body is 15 bytes and with only a few barebones HTTP headers seems to take between 2 and 5 seconds. What gives?

Code

void loop() {

// if ten seconds have passed since your last connection,
// then connect again and send data:
Serial.println("get(/)");
digitalWrite(13, HIGH);

http.get("/");

// read the status code and body of the response
int statusCode = http.responseStatusCode();
String response = http.responseBody();

Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);

Serial.println("complete");

digitalWrite(13, LOW);

delay(1000);

}

Maybe there is something about Arduino that I am misunderstanding, but I have never seen anything like this happen before which is why I am quite confused. I was under the impression that Arduino code ran synchronously, except for when an interrupt pulls it away to run another bit of code to return right back where it was and continue execution.