DS18B20 for Arduino

šŸ“’ Datasheet PDF

There are many libraries for DS18B20 sensors. This write-up will use the most common set.

1.

šŸ”½ Get Arduino

Install the Arduino IDE

2.

šŸ“¦ Install the library

Start the Arduino IDE, press the Sketch menu, and then Include Library > Manage Libraries

  1. Search for DallasTemperature and install the library called DallasTemperature.

3.

šŸ”Œ Connections

There are two ways to connect a DS18B20 sensor. Check the datasheet for more information. This write-up will use the most straightforward.

  1. The DS18B20 red wire connects to power, 3.3 to 5-volt
  2. The DS18B20 black wire is ground
  3. The DS18B20 yellow wire is the signal wire and connects to any capable GPIO pin on the controller
  4. A pull-up resistor must be present, connecting the DS18B20 power wire to the signal wire. On our carrier boards, this resistor is present. No further components are needed.

4.

šŸ”° Write some code

Below is the Simple example. It can be found in File > Examples > Dallas Temperature > Simple in the Arduino IDE.

// Include the libraries we need
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

/*
 * The setup function. We only start the sensors here
 */
void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
}

/*
 * Main function, get and show the temperature
 */
void loop(void)
{ 
  // call sensors.requestTemperatures() to issue a global temperature 
  // request to all devices on the bus
  Serial.print("Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");
  // After we got the temperatures, we can print them here.
  // We use the function ByIndex, and as an example get the temperature from the first sensor only.
  float tempC = sensors.getTempCByIndex(0);

  // Check if reading was successful
  if(tempC != DEVICE_DISCONNECTED_C) 
  {
    Serial.print("Temperature for the device 1 (index 0) is: ");
    Serial.println(tempC);
  } 
  else
  {
    Serial.println("Error: Could not read temperature data");
  }
}

Pay attention to the line that reads define ONE_WIRE_BUS 2. 2 is the pin the yellow signal wire is connected to. It is the only change you should need to make to the code.

5.

āž”ļø Upload the code

  1. Tell the Arduino IDE what board you are using. Press Tools > Board and find yours in the menu
  2. Press the upload button

6.

šŸ”Ž View the output

  1. Open the Serial Monitor by pressing Tools > Serial Monitor
  2. The measurements should be displayed in the monitor, with updates every second