Arduino Tutorial: Temperature Sensor

An Arduino Tutorial on building a temperature sensor – and an iPhone app to connect with it! By Tony Dahbura.

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 5 of this article. Click here to view the first page.

Talking to the Network

Let’s get this circuit talking to your network!

As I mentioned in the beginning of this tutorial, you’ll need a port available on your network switch or wireless hub and to be close enough to run a cable from it to your Ethernet shield. So go ahead and run an Ethernet cable from the RJ-45 jack on the Ethernet Shield to your switch or hub.

The LED next to the Ethernet jack will glow orange if a link has been detected on your network.

Now that the physical wiring is done, you need to write some code to get the Ethernet Shield online.

Select File/New in the Arduino IDE. A new blank sketch window should appear.

Type the following code into the blank sketch window:

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

const int ledPin = 7;
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x7D, 0x54 };  //1

EthernetServer server(80);  //2

The first two lines declare some header files you need to use the Ethernet Shield. The line after that declares the pin of your status LED, just as the previous code block did. Furthermore:

  1. This refers to the MAC address you recorded earlier, which is unique to your Ethernet Shield. Replace the value shown with your value.
  2. Here you create a server object and instruct it to listen on port 80.

A server object? On a microcontroller? Yes, most libraries for the Arduino are written in C++. If you’re curious about how it works, you can peruse the source where you installed the other libraries earlier – look for the folder called Ethernet.

Note: If you would like to review the APIs for the included libraries with the Arduino IDE you can get to them here.

Note: If you would like to review the APIs for the included libraries with the Arduino IDE you can get to them here.

OK, now that you’ve defined your variables and headers, add your trusty setup code to the bottom of the file:

void setup(void) {
  pinMode(ledPin, OUTPUT);  //1
  Serial.begin(9600);
  Serial.println("LED Pin setup for output on pin ");
  
  digitalWrite(ledPin, HIGH);  //2
  
  // start the Ethernet connection and the server:
  Serial.println("Trying to get an IP address using DHCP");

  if (Ethernet.begin(mac) == 0) { //3
    Serial.println("Failed to configure Ethernet using DHCP");
    while (true) {
      digitalWrite(ledPin, HIGH);
      delay(200);
      digitalWrite(ledPin, LOW);
      delay(200);
    }
  }
  Serial.println();
  // start listening for clients
  Serial.print("server is at "); //4
  Serial.println(Ethernet.localIP());
  
  digitalWrite(ledPin, LOW);
  
}

void loop(void) {  //5
  return;
}

Here’s what’s happening step-by-step:

  1. This sets your LED control pin to output, as before. The two Serial lines turn on a handy function of the Arduino SDK: a Serial window where you can dump messages and see what’s happening.
  2. You turn on the LED to signal that the system is attempting to acquire a DHCP address, while also dumping a handy message to the console.
  3. The Ethernet.begin() instruction attempts to obtain a DHCP address. If it doesn’t get one, it will return zero. You trap this by displaying a message and sitting in a permanent loop, blinking the LED at a faster pace as a warning that something happened.
  4. If the program does obtain a DHCP address, the server will output its address to the terminal window and turn off the status LED.
  5. The loop method doesn’t do anything yet! :]

Select File/Upload to compile and load your code into the Arduino.

Once it’s done, select Tools/Serial Monitor and make sure the window has a baud rate of 9600. You should see some messages coming into the window as the system executes your code:

serialmonitordhcp

Note: If you do not have DHCP services on your network, you can assign an IP address to the server using the following code right after the line declaring your MAC address:

Then replace Ethernet.begin(mac) with this:

Note: If you do not have DHCP services on your network, you can assign an IP address to the server using the following code right after the line declaring your MAC address:

IPAddress ip(192,168,1, 121);  //pick some value on your network

Then replace Ethernet.begin(mac) with this:

Ethernet.begin(mac, ip); 
IPAddress ip(192,168,1, 121);  //pick some value on your network
Ethernet.begin(mac, ip); 

Now let’s get the server to handle inbound requests! This is where loop() comes to life. Add the following after the end of setup(), replacing the current function stub:

void loop(void) {

  // 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("Connnection: close");
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html><body>HELLO</body></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");
    blinkLED();
  }

}

loop() checks if a connection has come in and displays all the connection data send by the client. This includes dumping all the HTTP headers and finally responding with a simple HELLO.

The code reads one character at a time, looking for the blank line on the request. At the conclusion of all this, you quickly blink the LED and return to listening for more connections.

Enter the following subroutine after loop() to blink the LED:

void blinkLED(void)
{
  digitalWrite(ledPin, HIGH);
  delay(500);
  digitalWrite(ledPin, LOW);
  delay(500);
  
  return;
}

Compile and upload the code by selecting File/Upload.

Let’s give the web server a spin! First reopen the Serial Monitor window by selecting Tools/Serial Monitor. Then using a browser on your Mac, open the URL: http://[the IP displayed in the Serial Monitor].

Your Serial Monitor output should show something similar to the following:

serialmonitorhtmloutput

And your browser should say HELLO, which is what you put in the loop code to display!

htmlbrowserhello

Tony Dahbura

Contributors

Tony Dahbura

Author

Over 300 content creators. Join our team.