Skip to main content
1 of 2

Couldn't connect to local server using Ethernet Shield and Arduino Mega 2560

I'm trying to connect the arduino mega and ethernet shield and try to send some data to a php script. I have connect the ethernet shield to the laptop. Lap is connected to router through wi-fi. But it's failing at mac assignment checking IF and getting the following assigned error message, "Failed to configure Ethernet using DHCP". Any help in advance please.

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

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD9 };   //physical mac address
byte ip[] = { 192, 168, 1, 5 };                   // ip in lan
byte subnet[] = { 255, 255, 255, 0 };              //subnet mask
byte gateway[] = { 192, 168, 0, 1 };              // default gateway
IPAddress server(192,168,1,2);
EthernetClient client;

String data;

void setup() {
  Serial.begin(9600);
  // start the Ethernet connection:
  while (!Serial);
  Ethernet.begin(mac,ip,gateway,subnet);     // initialize Ethernet device
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    for (;;)
    ;
  }

  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }

  delay(4000); // GIVE THE SENSOR SOME TIME TO START
  data = "";
}

void loop(){
  data = "&temp1=10&hum1=20";
  if (client.connect(server,1234)) { // REPLACE WITH YOUR SERVER ADDRESS
    Serial.println("Server connection OK");
    client.println("POST /add.php HTTP/1.1");
    client.println("Host:" + server);// SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
  }
  
  if (client.connected()) {
    client.stop();// DISCONNECT FROM THE SERVER
  }
  
  delay(5000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}