Arduino Ethernet Shield + DS18S20

In this post, using a temperature sensor DS18S20 and an Arduino Ethernet Shield, we will build a thermometer that can be read in the local network, and that will show the current temperature and the maximum and minimum temperature. First, we need to have the library ‘One Wire’ in Arduino which is necessary to use the sensor. You can download it here. You can find some help here for installing it, in case you need.

We will need a 4.7kΩ resistor for the DS18S20 connection. The way to connect it, is shown in the following image. The code we will use is the following one:

/*
 Temperature Web Server
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * DS18S20 attached to pins D2
 */
 
#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
 
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 
 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,2, 11);
 
// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80);
 
int DS18S20_Pin=2;
OneWire ds(DS18S20_Pin);
 
float maxtemp = -100;
float mintemp = 100;
 
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
 }
 
 
 // start the Ethernet connection and the server:
 Ethernet.begin(mac, ip);
 server.begin();
 Serial.print("server is at ");
 Serial.println(Ethernet.localIP());
}
 
 
void loop() {
 float temperature = getTemp();
 if (temperature > maxtemp){
 maxtemp = temperature;
 }
 if (temperature < mintemp){
 mintemp = temperature;
 }
 
 // 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>");
 client.println("<title>");
 client.println("TempWebServer");
 client.println("</title>");
 client.println("<meta http-equiv=\"refresh\" content=\"10\">");
 client.print("<h1> <center>");
 client.print("La temperatura es de ");
 client.print(temperature);
 client.print(" &degC");
 client.print("</h1> </center>");
 client.print("<h1> <center>");
 client.print("Max ");
 client.print(maxtemp);
 client.print(" &degC");
 client.print("</h1> </center>");
 client.print("<h1> <center>");
 client.print("Min ");
 client.print(mintemp);
 client.print(" &degC");
 client.print("</h1> </center>");
 client.println("<br />"); 
 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");
 }
}
 
float getTemp(){ //returns the temperature from one DS18S20 in DEG Celsius
 
 byte data[12];
 byte addr[8];
 
 if ( !ds.search(addr)) {
 //no more sensors on chain, reset search
 ds.reset_search();
 return -1000;
 }
 
 if ( OneWire::crc8( addr, 7) != addr[7]) {
 Serial.println("CRC is not valid!");
 return -1000;
 }
 
 if ( addr[0] != 0x10 && addr[0] != 0x28) {
 Serial.print("Device is not recognized");
 return -1000;
 }
 
 ds.reset();
 ds.select(addr);
 ds.write(0x44,1); // start conversion, with parasite power on at the end
 
 byte present = ds.reset();
 ds.select(addr); 
 ds.write(0xBE); // Read Scratchpad
 
 
 for (int i = 0; i < 9; i++) { // we need 9 bytes
 data[i] = ds.read();
 }
 
 ds.reset_search();
 
 byte MSB = data[1];
 byte LSB = data[0];
 
 float tempRead = ((MSB << 8) | LSB); //using two's compliment
 float TemperatureSum = tempRead / 16;
 
 return TemperatureSum;
 
}

After the code is loaded in Arduino, a web, like the one in the image, will be shown when we enter the IP of the Ethernet Shield.

10 thoughts on “Arduino Ethernet Shield + DS18S20

  1. Raúl Agámez

    Buenas tardes, yo me encuentro realizando un proyecto que invulucra visualizar los valores de la temperatura en nua GUI de MATLAB pero solo me entrega valores que no logro interpretar de manera correcta para mostrarlos y actualizarlos en la misma GUI, lo he conectado como pin digital y la verdad no se como lograr estos datos apropiados cuando desde el IDE de arduinoo obtenia buenos resultados.

    Agradezco colaboración

  2. matambilli

    hola, interesante proyecto, una pregunta si deseo incluir otro tipo de sensor de temperatura como por ejemplo el Dht11 es necesario cambiar a otra libreria o solo es modificar los valores por la nomeclatura del sensor ?

    1. guille Post author

      En el caso de que quieras reemplazar el sensor DS18S20 por el DHT11 es necesario cambiar de librería. Tienes más información sobre el DHT11 aquí.

  3. Gloria

    Buen día.
    Excelente aporte… una duda, ¿alguien sabe cómo mandar esos datos a una BD?
    Tengo todo xampp instalado, he leído y muchos usan la función GET pero no me queda clara.

  4. Pingback: Arduino Ethernet Shield | WnGeek

  5. juan

    me sale este error
    sketch_may02a.cpp: In function ‘void setup()':
    sketch_may02a:32: error: no match for ‘operator!’ in ‘!Serial’
    sketch_may02a.cpp:37: note: candidates are: operator!(bool)

  6. Felipe

    me salen estos errores favor necesito ayuda

    ReadWrite:25: error: ‘OneWire’ does not name a type
    ReadWrite.ino: In function ‘float getTemp()':
    ReadWrite:122: error: ‘ds’ was not declared in this scope
    ReadWrite:128: error: ‘OneWire’ has not been declared
    ReadWrite:138: error: ‘ds’ was not declared in this scope

  7. Jose Maria

    Hola. Queria preguntarte si sabes si es posible agregar mas de 1 sensor DS18S20. Es porque quiero utilizar Arduino para monitorizar la temperatura de un datacenter en varios puntos. Desde ya muchas gracias.

    1. guille Post author

      Si, es posible usar varios sensores a la vez ya que ésta librería permite que cada sensor tenga un código único que los identifique. Para ello habría que modificar el código para que tome lecturas del número de sensores deseados y que posteriormente muestre sus lecturas.

Comments are closed.