How to check if the arduino ethernet shield has a cable connected or not.

Hi guys.

I’m new to arduino here and making a small test project. It’s basically an arduino uno, with a dht temp sensor + ethernet shield that puts my room temperature “online” in my local lan network.

I hooked up an RGB LED and trying to get it to light up in differnt colours to tell me the status of my project.

So far I got “Green” for everything working, “Blue” when DHT sensor does not transmit data to the arduino and “Yellow” when clients connect/disconnect to the IP via a webbrowser, and …

TLDR:
I want to “hook up” RED for when the ethernet cable gets disconnected. Not quite how to do this so I was wondering if anyone could help out or point me in the right direction.

My code so far:

#include <DHT.h>

#define DHTPIN 7     // what pin we're connected to
int redPin= 3;
int greenPin = 2;
int bluePin = 4;

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht(DHTPIN, DHTTYPE);

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

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x00, 0x23, 0x36 }; //MAC address found on the back of your ethernet shield.
IPAddress ip(192,168,1,207); // IP address dependent upon your network addresses.

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup() {
// Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  dht.begin();

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  Serial.print("subnetmask is ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("gateway is ");
  Serial.println(Ethernet.gatewayIP());
}


void loop() {
 
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (isnan(t) || isnan(h)) {
    Serial.println("Failed to read from DHT");
    setColor(170, 0, 255); // Purple Color
  } else {
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
    setColor(0, 255, 0); // Green Color
  }
 
  // listen for incoming clients
  
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
   client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
        
          // output the value of the DHT-11
         client.println("<H2>");
            client.print("Humidity: ");
            client.println("</H2>");
            client.println("<p />");
            client.println("<H1>");
            client.print(h);
            client.print(" %\t");
            client.println("</H1>");
            client.println("<p />"); 
            client.println("<H2>");
            client.print("Temperature: ");
            client.println("</H2>");
            client.println("<H1>");
            client.print(t);
            //*1.8+32 etter t
            client.println(" °");
            client.println("C");
            client.println("</H1>");
           
                
         
          client.println("</html>");
          break;
        }     
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
    setColor(255, 255, 0); // Yellow Color
  }
}
void setColor(int redValue, int greenValue, int blueValue) {
  analogWrite(redPin, redValue);
  analogWrite(greenPin, greenValue);
  analogWrite(bluePin, blueValue);
}

I've done this in the past. It worked to a degree, but this is a tricky area
Some pseudo-code in here - as it refers to project specific variables...

Call this when you initially startup, and again later if the network fails for any reason, call it again

bool usingDHCP, weWantoUseDHCP;
bool networkAvailable = false;

//==================================================
bool connect_to_network(void) {
//==================================================
  networkAvailable = false;
  usingDHCP = false; // assume the worst
  if (weWantoUseDHCP) {
    Serial.print("DHCP... ");
    // DHCP timeout is set in Dhcp.h - note uppercase D
    if (Ethernet.begin(myMAC_address) != 0) {
      Serial.print("OK ");
      usingDHCP = true;
    } else {
      Serial.print("not responding. ");
    }
  }


  if (!usingDHCP) {   // DHCP not in use, or failed to init
    Serial.print("Use STATIC IP... ");
    Ethernet.begin( myMAC_address, mySTATIC_IP, mySTATIC_NS, mySTATIC_GW, mySTATIC_NM);
  }
  networkAvailable = true;
  return true;
}

Hi lastchancename.

Thanks for your reply, but it went a bit over my head :slight_smile: Not used to programming languagues so I probably did something wrong when trying to execute your suggestion.

I pasted the code above the void setup area without changing it, so I kinda got your pseudo code there (I’m basically not quite sure what to change it with, I’m way over my head with this).

Code now, with your suggestion, including your pseudo code:

#include <DHT.h>

#define DHTPIN 7     // what pin we're connected to
int redPin= 3;
int greenPin = 2;
int bluePin = 4;

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht(DHTPIN, DHTTYPE);

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

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x00, 0x23, 0x36 }; //MAC address found on the back of your ethernet shield.
IPAddress ip(192,168,1,207); // IP address dependent upon your network addresses.

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);




bool usingDHCP, weWantoUseDHCP;
bool networkAvailable = false;

//==================================================
bool connect_to_network(void) {
//==================================================
  networkAvailable = false;
  usingDHCP = false; // assume the worst
  if (weWantoUseDHCP) {
    Serial.print("DHCP... ");
    // DHCP timeout is set in Dhcp.h - note uppercase D
    if (Ethernet.begin(myMAC_address) != 0) {
      Serial.print("OK ");
      usingDHCP = true;
    } else {
      Serial.print("not responding. ");
    }
  }


  if (!usingDHCP) {   // DHCP not in use, or failed to init
    Serial.print("Use STATIC IP... ");
    Ethernet.begin( myMAC_address, mySTATIC_IP, mySTATIC_NS, mySTATIC_GW, mySTATIC_NM);
  }
  networkAvailable = true;
  return true;
}




void setup() {
  

// Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  dht.begin();

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  Serial.print("subnetmask is ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("gateway is ");
  Serial.println(Ethernet.gatewayIP());
}


void loop() {


  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (isnan(t) || isnan(h)) {
    Serial.println("Failed to read from DHT");
    setColor(170, 0, 255); // Purple Color
  } else {
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
    setColor(0, 255, 0); // Green Color
  }
 
  // listen for incoming clients
  
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
   client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
        
          // output the value of the DHT-11
         client.println("<H2>");
            client.print("Humidity: ");
            client.println("</H2>");
            client.println("<p />");
            client.println("<H1>");
            client.print(h);
            client.print(" %\t");
            client.println("</H1>");
            client.println("<p />"); 
            client.println("<H2>");
            client.print("Temperature: ");
            client.println("</H2>");
            client.println("<H1>");
            client.print(t);
            //*1.8+32 etter t
            client.println(" °");
            client.println("C");
            client.println("</H1>");
           
                
         
          client.println("</html>");
          break;
        }     
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
    setColor(255, 255, 0); // Yellow Color
  }
}
void setColor(int redValue, int greenValue, int blueValue) {
  analogWrite(redPin, redValue);
  analogWrite(greenPin, greenValue);
  analogWrite(bluePin, blueValue);
}
'

Error message: I am guessing it’s because of the psuedo code I did not change:

_222.ino.ino.ino:49: error: 'myMAC_address' was not declared in this scope

     if (Ethernet.begin(myMAC_address) != 0) {

                        ^

_222.ino.ino.ino:60: error: 'myMAC_address' was not declared in this scope

     Ethernet.begin( myMAC_address, mySTATIC_IP, mySTATIC_NS, mySTATIC_GW, mySTATIC_NM);

                     ^

_222.ino.ino.ino:60: error: 'mySTATIC_IP' was not declared in this scope

     Ethernet.begin( myMAC_address, mySTATIC_IP, mySTATIC_NS, mySTATIC_GW, mySTATIC_NM);

                                    ^

_222.ino.ino.ino:60: error: 'mySTATIC_NS' was not declared in this scope

     Ethernet.begin( myMAC_address, mySTATIC_IP, mySTATIC_NS, mySTATIC_GW, mySTATIC_NM);

                                                 ^

_222.ino.ino.ino:60: error: 'mySTATIC_GW' was not declared in this scope

     Ethernet.begin( myMAC_address, mySTATIC_IP, mySTATIC_NS, mySTATIC_GW, mySTATIC_NM);

                                                              ^

_222.ino.ino.ino:60: error: 'mySTATIC_NM' was not declared in this scope

     Ethernet.begin( myMAC_address, mySTATIC_IP, mySTATIC_NS, mySTATIC_GW, mySTATIC_NM);

                                                                           ^

exit status 1
'myMAC_address' was not declared in this scope

Sorry I am kinda hopeless with this and probably need way more guidance than most people are willing to give :stuck_out_tongue:

Read about MAC addresses in the ethernet tutorials.
Because most Arduino shields don’t have a hardware MAC, it needs to be defined in your code.
The MAC must be unique for every device on ‘your network’ (strictly on the ‘planet’), but locally will get you started.

The routers and switches use the MAC to determine the paths through your LAN to reach that individual device. IP addresses are a higher level, but used in a different way.

lastchancename:
Read about MAC addresses in the ethernet tutorials.
Because most Arduino shields don’t have a hardware MAC, it needs to be defined in your code.
The MAC must be unique for every device on ‘your network’ (strictly on the ‘planet’), but locally will get you started.

The routers and switches use the MAC to determine the paths through your LAN to reach that individual device. IP addresses are a higher level, but used in a different way.

Thanks!! I think I got it sorted.

I checked out the tutorials on the arduino website for the ethernet shield, and I used that "Make repeated HTTP request". It goes to arduino.cc and if it connects, it works, if it doesnt it doesnt.

I implemented that in my code and now it lights up Red if it does not have internet access to that website or if the cable goes out. I guess I should modify it so it tries to connect to my router instead of a random website :stuck_out_tongue:

Had some problems with duplicate veriable names, but after I found out I could just rename them to something else, it kinda worked :stuck_out_tongue: Time to start checking the tutorials again :stuck_out_tongue:

hi im doing a project to check whether the ethernet is connected to arduino or not and to senda message to mobile phone about this status through GSM module. your post and coding really seems helpful. but it will be so much helpful if u give me the codings that u used finally to make the red LED glow if the ether net is not connected .I'm also not much familiar with coding.so help me with this.

I have commercially manufactured networked hardware that is not tolerant of the public IP address changing (and requires a reboot if it does). It is designed to work in a fixed IP environment and I needed it to operate reliably in a DHCP environment. The following code will detect the ethernet cable being detached and a change in the public IP address. Stubbed functions are available for acting upon the acquisition or change in the public IP address. I use the stubbed methods to assert a RESET to the target device and then post data to a log that resides on a MySQL database table through a web page (located on the local network and behind the firewall). I’m using a W5500 board that is hardwired to an Arduino PRO (i.e. not a shield), and this works well. Feel free to use this as you please.

Source code uses 4-character tab stops.

EthernetHotPlugging.zip (17.8 KB)

codebits:
I have commercially manufactured networked hardware that is not tolerant of the public IP address changing (and requires a reboot if it does). It is designed to work in a fixed IP environment and I needed it to operate reliably in a DHCP environment. The following code will detect the ethernet cable being detached and a change in the public IP address. Stubbed functions are available for acting upon the acquisition or change in the public IP address. I use the stubbed methods to assert a RESET to the target device and then post data to a log that resides on a MySQL database table through a web page (located on the local network and behind the firewall). I’m using a W5500 board that is hardwired to an Arduino PRO (i.e. not a shield), and this works well. Feel free to use this as you please.

Source code uses 4-character tab stops.

Here’s a state machine diagram for the above posted code…

BTW, I would encourage the developer of the Ethernet library to fix the problem with the Ethernet.hardwareStatus () method not functioning correctly until after execution of Ethernet.begin ( mac ). If proper hardware status was available prior to invoking begin ( mac ), the 60-second blocking of execution could be avoided. This is a correctable situation.

1 Like