Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino Ethernet Shield client.connect() always returns error

I have been searching around for this problem for a couple of days but still do not find an answer.

I am trying to make a simple Webclient connection with the arduino shield based on the sample code provided by Arduino IDE. Here is a simplified version of what I am trying to execute:

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


byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte server[] = { 173 ,194, 46, 34 }; // Google

EthernetClient client;

void setup()
{
  Ethernet.begin(mac);
  Serial.begin(9600);

  delay(1000);

  Serial.println(Ethernet.localIP());

  Serial.println("connecting...");

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /search?q=arduino HTTP/1.0");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

and always get the answer:

192.168.0.103
connecting...
connection failed

disconnecting.

That means that client.connect(server, 80) is failing. I have tried several IP addresses and same results. The shield is working properly as I have tried the WebServer example and that seems to work flawlessly.

PS on hardware: I am using Arduino UNO R3 and ethernet shield based on W5100

Any suggestions?

like image 835
Ben Quan Avatar asked Nov 23 '25 02:11

Ben Quan


1 Answers

I took a look at the source code of the Ethernet library, assuming that you have a recent version of the libraries. It seems to me that Arduino EthernetClient connect() function wants either an IPAddress object or a string (char *) with the name of the remote host. You are passing a byte array to it, and my guess is that it probably interprets it as a string. Try to declare the server global variable as follows instead:

IPAddress server(173 ,194, 46, 34);

If it works, then it is an indication that the official documentation, from which you probably took the code, is obsolete.

Also, you could try giving to the begin() function all the other parameters as IPAddress objects, so that DHCP is not used and you can rule out problems of automatic configuration. The prototype is:

void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet);
like image 167
Balau Avatar answered Nov 24 '25 22:11

Balau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!