Save data to an SD card with the Ethernet Shield

FunduinoPublished on

Messwerte auf SD-Karte speichern und im Browser anzeigen

Das Ethernet-Shield bringt nicht nur einen Netzwerkanschluss mit, sondern auch einen Slot für eine SD-Karte. Damit kann dein Arduino Messwerte speichern oder sie als Webseite in deinem Heimnetz anzeigen.

In drei Projekten speicherst du zuerst eine einfache Zahlenreihe, dann die Messwerte eines DHT11 als CSV-Datei für die Tabellenkalkulation. Zum Schluss baust du mit dem TMP36 ein Thermometer, das du im Browser abrufst.

A DHT11 sensor is connected to the Ethernet shield.
DHT11 sensor on Ethernet shield

You need this

W5100 Ethernet Shield - RJ45, 10 Mbit/s, for Arduino W5100 Ethernet Shield - RJ45, 10 Mbit/s, for Arduino 18,90 € *Item no. F23106788About the product — W5100 Ethernet Shield - RJ45, 10 Mbit/s, for Arduino
DHT11 temperature sensor - humidity, 3.3-5.5 V, without breakout board DHT11 temperature sensor - humidity, 3.3-5.5 V, without breakout board 2,32 € *Item no. F23106840About the product — DHT11 temperature sensor - humidity, 3.3-5.5 V, without breakout board
Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino 11,12 € *Item no. F23107480About the product — Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino
Breadboard cables male-female - 40 pieces, 20 cm Breadboard cables male-female - 40 pieces, 20 cm 1,74 € *Item no. FUN-1010554About the product — Breadboard cables male-female - 40 pieces, 20 cm

All 4 parts together 34,08 € *Ready to ship immediately · Delivery time: 1-3 business days

* All prices include statutory VAT, plus shipping costs.

Required components

For the first two projects, you need:

For the third project, the thermometer in the browser, you also need a TMP36 temperature sensor, an Ethernet cable, and a 9 V power supply or a 9 V battery.

Prepare the SD card

You can set up a web server with the Ethernet Shield. You can also use it as a data storage device independently: Save sensor readings to an SD card in the Shield’s card slot.

Important: The SD card must be formatted as FAT32. In Windows, right-click the removable drive and select “Format”. In the window that opens, select “FAT32” under “File system” and format the card.

Formatting will erase all data on the card. Back up anything you still need first.

Project 1: Store a sequence of numbers

In the first sketch, the Arduino generates just two sequences of numbers and saves them to the SD card. To set it up, simply plug the Ethernet shield onto the microcontroller.

If the sketch can read the SD card, the LED on pin 13 blinks twice. It then writes a new line to the file zaehlen.csv every second: the first number increases by 1 each time, and the second by 2. A semicolon separates the two values. All further explanations are included as comments in the sketch.

The SD card is accessed via pin 4. If you are using an Arduino MEGA, change the 4 to 53 in both places in the sketch.

Save sequences of numbers to the SD card
#include <SD.h>      //Add the SD library
int a=0; // Variable for a counting operation
int b=0; // Variable for a counting operation
const int chipSelect = 4; //Chip pin for the SD card (4 on UNO, 53 on MEGA)
void setup() {
pinMode (13, OUTPUT);
  if (startSDCard() == true) //The "startSDCard" function block is used to check the SD card. If the SD card can be read, the onboard LED on pin 13 should blink twice.
  {
  digitalWrite(13, HIGH); //on
  delay(500);
  digitalWrite(13, LOW); //off
  delay(500);
  digitalWrite(13, HIGH); //on
  delay(500);
  digitalWrite(13, LOW); //off
  delay(500);
  }
}
void loop()
{
  File dataFile = SD.open("zaehlen.csv", FILE_WRITE); //Create a file on the SD card named "zaehlen"
a=a+1; //The value a+1 is now stored in the variable "a". This increases the value of "a" by 1 on each iteration.
b=b+2; //The value b+2 is now stored in the variable "b". This increases the value of "b" by 2 on each iteration.
dataFile.print(a); //The value of "a" is saved to the SD card
dataFile.print(";"); //A semicolon is saved in the CSV file, allowing the values to be displayed separately in a table later.
dataFile.println(b); //The value of "b" is saved to the SD card
dataFile.close(); //The file is temporarily closed.
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500); //Here the loop ends and then starts again from the beginning. The values of "a" and "b" are saved to the table on the SD card every second.
}
boolean startSDCard() //This function block is needed to check whether the SD card is ready.
{
  boolean result = false;
  pinMode(4, OUTPUT); //4 on UNO, change to 53 on MEGA
  if (!SD.begin(chipSelect)) //Check whether the SD card can be read
  {
    result = false;
  }
  else //If so, create a file as in the loop
  {
  File dataFile = SD.open("datalog.csv", FILE_WRITE);
   if (dataFile)
    {
      dataFile.close();
      result = true;
    }
  }
  return result;
}

Evaluate the result

If you open the file zaehlen.csv with a text editor, it looks like this:

1;2 · 2;4 · 3;6 · 4;8 · 5;10 · 6;12 …

If, on the other hand, you open the file with a spreadsheet program such as Excel or LibreOffice Calc, each value after a semicolon ends up in the next cell. You can use this to create a chart, for example.

Chart of the saved number sequences in a spreadsheet program
Analysis of the measurement data in a spreadsheet program

Project 2: Connecting the DHT11

In the second project, you use the DHT11 to measure temperature and humidity and save the readings to the SD card. Then you analyze them with a spreadsheet program.

Plug the Ethernet Shield into the microcontroller and connect the DHT11 as follows:

  • Pin “−” to GND on the Ethernet Shield
  • Pin “S” to D2 on the Ethernet Shield
  • middle pin to 5V on the Ethernet Shield

The pin labels “−”, “S” and Center belong to the DHT11 on a module board. The linked sensor without a breakout board has four pins: viewed from the front, the left pin is VCC, the second is Data, the third is unused, and the right pin is GND. The data line also needs a pull-up resistor, for example 10 kΩ, to 5V.

A DHT11 sensor is connected to the Ethernet shield.
DHT11 sensor on Ethernet shield

Required libraries

For this sketch, you need Adafruit's DHT sensor library, which you can install via the Library Manager. The SD library is already included with the Arduino IDE.

Current versions of the DHT library also require the Adafruit Unified Sensor library. The Library Manager offers to install it as well.

Save measured values

The sketch first checks the SD card and then starts the DHT11. In the loop section, it reads the humidity and temperature, writes both values separated by a semicolon to the file werte.csv, and also displays them in the Serial Monitor.

Using println instead of print ensures that a new row in the table begins after the temperature.

Add the line pinMode(13, OUTPUT); to setup() so the blinking works reliably during the card test. With delay(1000), the sketch stores a value about once per second.

Save DHT11 readings to the SD card
#include "SD.h"     //SD Library hinzufügen
#include "DHT.h"      //DHT Library hinzufügen
#define DHTPIN 2      //Pin an dem der DHT angeschlossen ist festlegen
#define DHTTYPE DHT11   //DHT Typ festlegen: Hier DHT11
#define TEMPERATURE 1
#define HUMIDITY 0
int feuchte;
int temperatur;
DHT dht(DHTPIN, DHTTYPE); //Sensor initializieren
const int chipSelect = 4; //Chip Pin für die SD Karte(bei UNO 4,bei MEGA 53)
void setup() {
  if (startSDCard() == true) // Durch den Rückgriff auf den Programmblock "startSDCard" wird die SD-Karte geprüft. Wenn die SD Karte gelesen werden kann dann soll die onboard-LED an Pin13 zweimal blinken
  {
  digitalWrite(13, HIGH); //an
  delay(500);
  digitalWrite(13, LOW); //aus
  delay(500);
  digitalWrite(13, HIGH); //an
  delay(500);
  digitalWrite(13, LOW); //aus
  delay(500);
  }
  Serial.begin(9600); //Serielle Verbindung starten
  dht.begin();       //DHT Sensor starten
}
void loop()
{
  File dataFile = SD.open("werte.csv", FILE_WRITE); //Excel Datei mit dem Namen „werte“ auf der SD-Karte anlegen
  feuchte = dht.readHumidity(); //Feuchtigkeit auslesen
  temperatur = dht.readTemperature(); //Temperatur auslesen
  dataFile.print(feuchte); //Feuchtigkeit in die Excel Datei eintragen
  dataFile.print(";"); // Es wird ein Semikolon in die CSV-Datei gespeichert, daduch lassen sich die Werte später als Tabelle getrennt darstellen.
  dataFile.println(temperatur); //Temperatur in die Excel Datei eintragen. Durch den Befehl mit der Endung „ln“ („LN“ in Kleinbuchstaben) wird ein Zeilenumsprung in der Wertetabelle erzeugt.
  dataFile.close(); // Die Datei wird vorrübergehend geschlossen.
  delay(1000);
   Serial.print("Luftfeuchtigkeit: "); //Im seriellen Monitor den Text und
  Serial.print(feuchte); //die Dazugehörigen Werte anzeigen
  Serial.println(" %");
  Serial.print("Temperatur: ");
  Serial.print(temperatur);
  Serial.println(" Grad Celsius");
}
boolean startSDCard() {
  boolean result = false;
  pinMode(4, OUTPUT); // 4 bei UNO, bei MEGA in 53 ändern
  if (!SD.begin(chipSelect)) { //Überprüfen ob die SD Karte gelesen werden kann
    result = false;
  }
  else {  // Wenn ja Datei wie im Loop anlegen
      File dataFile = SD.open("datalog.csv", FILE_WRITE);
    if (dataFile) {
      dataFile.close();
      result = true;
    }
  }
  return result;
}
float readSensor( int thisValue) {
  float result;
  if (thisValue == TEMPERATURE) {
    result = dht.readTemperature(); //Sensorwert auslesen und unter Temperature              speichern
  }
  else if (thisValue == HUMIDITY)  //Sensorwert auslesen und unter Humidity                   speichern
 {
 result = dht.readHumidity();
  }
  if (isnan(result))  // Die Library des DHT Sensors sendet beim Verlust des Signals vom DHT11 den Befehl „isnan“. Die passiert bspw. wenn das Kabel der Datenleitung zum Sensor den Kontakt verliert. In dem Fall soll als „Messwert“ die Zahl -273 angezeigt und gespeichert werden. Da dies der tiefste zu erreichende Punkt ist, dürfte jedem klar sein, dass mit den Werten etwas nicht stimmt, und dass der Aufbau überprüft werden muss.
 {
result = -273.0;
  }
  return result;
}

Analyze measurement data

Open the file werte.csv in a spreadsheet program, as you did in the first project. The first column contains the humidity, and the second contains the temperature. The result could look like this as a chart.

Diagram of DHT11 temperature and humidity readings in a spreadsheet program
The DHT11 measurement data in a spreadsheet program

Project 3: The Ethernet Shield as a Web Server

In the third project, you’ll read the room temperature with the TMP36 temperature sensor and display it on a webpage on your home network. The setup is based on the instructions Measuring temperature with the TMP36.

Plug the Ethernet Shield into the microcontroller and connect it to your router with a LAN cable. Then connect the TMP36 as shown in the wiring diagram, with the signal output connected to A3. Use an external power supply with a 9 V adapter or a 9 V battery; this significantly improves the sensor’s accuracy.

The Ethernet shield uses digital pins 10, 11, 12, and 13, plus pin 4 for the SD card slot. You cannot use these pins for other components.

Schematic: Ethernet shield on the Arduino, TMP36 temperature sensor on A3

Set the IP address

Every device on a local network has its own IP address. Usually, the router’s DHCP server (Dynamic Host Configuration Protocol) assigns these addresses automatically; less often, they are entered manually. Each device also has a unique MAC address. In the sketch, it is 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED.

In the sketch, the statischeIP switch determines which option you use:

  • true: You set the IP address yourself.
  • false: The IP address is assigned via DHCP.

If you want to use a static IP address, you need one that is not already in use on the network. To find one, open the Command Prompt in Windows (press the Windows key, type “cmd”) and enter the command arp -a. The first line shows your computer’s IP address, followed by all devices and their IP and MAC addresses. These addresses are already in use.

Output of the arp -a command with the IP addresses in use on the network

The thermometer in the browser

First, you set the port for the webpage and start the EthernetServer. In the loop section, the sketch reads the sensor value and converts it to a temperature using the map command, just like in the TMP36 instructions.

When a browser loads the page, the sketch sends the temperature as an HTML page. After a short pause, client.stop() disconnects the connection.

After uploading, the serial monitor displays the IP address of the Ethernet shield. Enter this address in the address bar of a browser of your choice.

The serial monitor displays the IP address of the Ethernet shield.
The Funduino thermometer website with the measured temperature in the browser
1 / 2
The Ethernet shield as a web server thermometer
// Loading the required library
#include "Ethernet.h"
int TMP36 = A3;  // Variable declaration
int sensorwert;
int temperatur = 0;
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};  // MAC address of the Arduino board  !IMPORTANT! MAC address may only appear once on the home network
// statischeIP = false -> Assign IP address via DHCP
// statischeIP = true -> Set a static IP address
bool statischeIP = false;
// static IP
IPAddress ip(192, 168, 1, 200);
EthernetServer server(80);  // Port setting (standard for HTML: 80)
void setup()
{
  Serial.begin(9600);
  // Start Ethernet with a static IP
  if (statischeIP) Ethernet.begin(mac, ip);
  // Start Ethernet with DHCP
  else Ethernet.begin(mac);
  server.begin();  // Wait for clients
  // Display the IP address in the Serial Monitor for verification
  // localIP -> address to enter in the browser
  Serial.print(F("IP address of the Ethernet shield: "));
  Serial.println(Ethernet.localIP());
}
void loop()
{
  sensorwert = analogRead(TMP36);                  //Read the sensor value on pin A3
temperatur = map(sensorwert, 0, 410, -50, 150);  // Convert the sensor value using the "map" command
  delay(500);
  EthernetClient client = server.available();  //Check whether a client is accessing the page
  if (client) {                                //Page accessed by user
    // Output in HTML
    server.print("HTTP/1.0 200 OK\r\nServer: arduino\r\nContent-Type: text/html\r\n\r\n");
    server.print("<HTML><HEAD><TITLE>");
    server.print("Funduino Thermometer");
    server.print("</TITLE>");
    server.print("</HEAD><BODY>");
    server.print("<h2 align=center><font size=7><b>Funduino Thermometer </b></font></h2>");
    server.print("<center><font size=5><b>The temperature is </font>");
    server.print(temperatur);  // Output the temperature
    server.print("<font size=5> degrees Celsius. </font");
    delay(500);     // Brief delay to send the data
    client.stop();  // Disconnect from the client
  }
}
Rate the instructions

Comments

Ask a question or share an experience

Contact us if something doesn’t work. Please include your board and the error message.

We review every comment before publication. Your email address remains with us.