Skip to content
We have moved: pcb.esp32s.com → pcb32.comSame store. Existing accounts, orders and affiliate commission records are unchanged.
Номер заказа: USD
Номер заказа: USD
pcb32.com
Cart 0

Полное руководство по использованию датчиков температуры DS18B20 с ESP32 (Arduino IDE)

The DS18B20 digital temperature sensor is a versatile and precise component for your ESP32 projects, offering simplicity through its one-wire communication protocol and the unique ability to network multiple sensors on a single GPIO pin. This comprehensive guide, drawing from extensive hands-on experience in IoT development, will walk you through everything from basic wiring to building a professional web server dashboard. Whether you’re monitoring a single room or creating a multi-point temperature logging system, this tutorial provides the updated code and practical know-how for 2026.

Why the DS18B20 is Ideal for ESP32 Projects

Он DS18B20 stands out in the world of microcontroller-compatible sensors. Its one-wire digital interface means you only need one data pin (plus ground) from your ESP32 for communication, drastically simplifying wiring, especially for multiple sensors. Each sensor has a factory-programmed unique 64-bit address, allowing many devices to share the same data bus without conflict. With an operating range from -55°C to +125°C and a typical accuracy of ±0.5°C, it is suitable for applications ranging from environmental monitoring to industrial processes.

Key Technical Specifications

  • Communication Protocol: One-Wire (1-Wire)

  • Источник питания: 3.0V to 5.5V (Compatible with ESP32‘s 3.3V logic)

  • Диапазон температур: -55°C to +125°C (-67°F to +257°F)

  • Accuracy: ±0.5°C (from -10°C to +85°C)

  • Conversion Time: Up to 750ms for 12-bit resolution

Hardware Setup: Wiring Your DS18B20 to the ESP32

You can power the DS18B20 in two ways: Обычный режим (recommended for stability) or Parasite Power Mode. The following table outlines the connections for each method using ESP32 GPIO 4 as the data pin.

Connection Normal Mode (with External 3.3V) Parasite Power Mode
DS18B20 VDD (Red Wire) ESP32 3.3V Pin Not Connected
DS18B20 DATA (Yellow Wire) ESP32 GPIO 4 (via 4.7kΩ resistor) ESP32 GPIO 4 (via 4.7kΩ resistor)
DS18B20 GND (Black Wire) ESP32 GND Pin ESP32 GND Pin
Pull-up Resistor 4.7kΩ between DATA and 3.3V 4.7kΩ between DATA and 3.3V

⚠️ The Pull-up Resistor is Crucial: Он 4.7kΩ resistor between the data line and 3.3V is mandatory for stable communication in both configurations. Omitting it is a common reason for sensor read failures.

Software Setup: Installing Required Libraries

Before you can write code, you need to install two essential libraries in your Arduino IDE via Sketch > Добавить библиотеку > Управление библиотеками:

  1. OneWire by Paul Stoffregen: Provides the low-level protocol to communicate with one-wire devices.

  2. DallasTemperature by Miles Burton: Offers a simplified, high-level API specifically for DS18B20 and similar sensors, built on top of the OneWire library.

After installation, restart the Arduino IDE to complete the process.

Part 1: Reading from a Single DS18B20 Sensor

Let’s start with the foundational code to read temperature from one sensor. This sketch will print readings in both Celsius and Fahrenheit to the Serial Monitor every 5 seconds.

Complete Arduino Sketch

cpp
/*********
 * ESP32 with Single DS18B20 Sensor
 * Reads and prints temperature to Serial Monitor
 * Complete project details: https://RandomNerdTutorials.com
 *********/

#включать <OneWire.h>
#включать <DallasTemperature.h>

// GPIO where the DS18B20 data wire is connected
константа инт ONE_WIRE_BUS = 4;

// Setup instances for OneWire and DallasTemperature
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature датчики(&oneWire);

пустота настраивать(пустота) {
  Серийный номер.начинать(115200); // Start serial communication
  датчики.начинать();      // Initialize the sensor library
  Серийный номер.println("DS18B20 Temperature Sensor Initialized");
}

пустота петля(пустота) {
  датчики.requestTemperatures(); // Send command to get temperatures

  // Read temperature in Celsius (Index 0 for first sensor)
  плавать tempC = датчики.getTempCByIndex(0);
  // Convert to Fahrenheit
  плавать tempF = датчики.getTempFByIndex(0);

  // Check for valid reading (sensors return -127.00 on error)
  если (tempC != DEVICE_DISCONNECTED_C) {
    Серийный номер.печать("Temperature: ");
    Серийный номер.печать(tempC);
    Серийный номер.печать(" °C  |  ");
    Серийный номер.печать(tempF);
    Серийный номер.println(" °F");
  } еще {
    Серийный номер.println("Error: Could not read temperature data");
  }

  задерживать(5000); // Wait 5 seconds between readings
}

How the Code Works

  1. Library & Pin Definition: Он OneWire и DallasTemperature libraries are included. The data pin (GPIO 4) is defined, and library instances are created.

  2. Setup Routine: Serial communication starts at 115200 baud for debugging. sensors.begin() initializes the one-wire bus.

  3. Reading Temperature: sensors.requestTemperatures() sends a command to all sensors on the bus to perform a temperature conversion. sensors.getTempCByIndex(0) fetches the value from the first (index 0) sensor found.

  4. Error Handling: The code checks if the reading equals DEVICE_DISCONNECTED_C (-127°C), which indicates a communication problem, and prints an error message instead.

Part 2: Reading from Multiple DS18B20 Sensors on One Wire

The real power of the DS18B20 shines when you connect multiple sensors. Wire all sensors in parallel: connect all ВДД pins to 3.3V, all НД pins to GND, and all DATA pins to GPIO 4 (with a single 4.7kΩ pull-up resistor).

Code for Multiple Sensors

The following sketch automatically discovers all connected sensors, prints their unique addresses, and displays each one’s temperature.

cpp
/*********
 * ESP32 with Multiple DS18B20 Sensors
 * Scans the bus and prints temperature for each device
 *********/

#включать <OneWire.h>
#включать <DallasTemperature.h>

#определять ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature датчики(&oneWire);

инт deviceCount = 0;
DeviceAddress tempDeviceAddress; // Array to hold device address

пустота настраивать(пустота) {
  Серийный номер.начинать(115200);
  датчики.начинать();

  // Count and list all devices on the bus
  deviceCount = датчики.getDeviceCount();
  Серийный номер.печать("Found ");
  Серийный номер.печать(deviceCount);
  Серийный номер.println(" device(s).");

  // Loop to print each device's address
  для (инт i = 0; i < deviceCount; i++) {
    если (датчики.getAddress(tempDeviceAddress, i)) {
      Серийный номер.печать("Device ");
      Серийный номер.печать(i);
      Серийный номер.печать(" Address: ");
      printAddress(tempDeviceAddress); // Call helper function
      Серийный номер.println();
    }
  }
}

пустота петля(пустота) {
  датчики.requestTemperatures();

  // Loop through each device and print its temperature
  для (инт i = 0; i < deviceCount; i++) {
    если (датчики.getAddress(tempDeviceAddress, i)) {
      плавать tempC = датчики.getTempC(tempDeviceAddress); // Read by address
      Серийный номер.печать("Device ");
      Серийный номер.печать(i);
      Серийный номер.печать(" Temp: ");
      Серийный номер.печать(tempC);
      Серийный номер.println("" °C"");
    }
  }
  Серийный номер.println("-----");
  задерживать(10000); // Wait 10 seconds
}

// Helper function to print a device's 64-bit address
пустота printAddress(DeviceAddress deviceAddress) {
  для (uint8_t i = 0; i < 8; i++) {
    если (deviceAddress[i] < 16) Серийный номер.печать("0");
    Серийный номер.печать(deviceAddress[i], HEX);
  }
}

Part 3: Building an Asynchronous Web Server Dashboard

To access your temperature readings from any browser on your local network, you can turn your ESP32 into a web server. We’ll use the efficient ESPAsyncWebServer и AsyncTCP libraries for smooth performance.

Step 1: Install Additional Libraries

In the Library Manager, install:

  • ESPAsyncWebServer by dvarrel

  • AsyncTCP by dvarrel (for ESP32)

Step 2: Complete Web Server Code

This code creates a responsive web page that automatically updates the temperature every 10 seconds without requiring a page refresh.

cpp
/*********
 * ESP32 DS18B20 Asynchronous Web Server
 * Displays temperature on a auto-updating web page
 *********/

#включать <WiFi.h>
#включать <ESPAsyncWebServer.h>
#включать <OneWire.h>
#включать <DallasTemperature.h>

// Replace with your network credentials
константа чар* SSID = "YOUR_SSID";
константа чар* пароль = "YOUR_PASSWORD";

#определять ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature датчики(&oneWire);

AsyncWebServer сервер(80); // Server object on port 80

Нить readTemperature() {
  датчики.requestTemperatures();
  плавать tempC = датчики.getTempCByIndex(0);
  если (tempC == DEVICE_DISCONNECTED_C) {
    возвращаться "Sensor Error";
  }
  возвращаться Нить(tempC);
}

// HTML & CSS for the web page (stored in PROGMEM to save RAM)
константа чар index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ESP32 Temperature Monitor</title>
  <style>
    body { font-family: Arial; text-align: center; margin: 50px; }
    .reading { font-size: 48px; font-weight: bold; color: #059e8a; }
    .unit { font-size: 24px; }
    .label { font-size: 20px; color: #555; }
  </style>
</head>
<body>
  <h1>🌡️ ESP32 Temperature Server</h1>
  <div>
    <p class="label">Current Temperature</p>
    <span class="reading" id="temp">%TEMPERATURE%</span>
    <span class="unit">°C</span>
  </div>
</body>
<script>
// JavaScript to update temperature every 10 seconds
setInterval(function() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temp").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 10000);
</script>
</html>)rawliteral";

// Processor to replace placeholder in HTML with actual sensor value
Нить processor(константа Нить& var) {
  если (var == "TEMPERATURE") {
    возвращаться readTemperature();
  }
  возвращаться Нить();
}

пустота настраивать() {
  Серийный номер.начинать(115200);
  датчики.начинать();

  // Connect to WiFi
  Wi-Fi.начинать(SSID, пароль);
  пока (Wi-Fi.статус() != WL_CONNECTED) {
    задерживать(1000);
    Серийный номер.println("Connecting to WiFi...");
  }
  Серийный номер.печать("Server IP Address: ");
  Серийный номер.println(Wi-Fi.локальный IP()); // <- You will access the page at this IP

  // Define server routes
  сервер.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send_P(200, "text/html", index_html, processor);
  });
  сервер.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send_P(200, "text/plain", readTemperature().c_str());
  });

  сервер.начинать(); // Start the server
}

пустота петля() {
  // Nothing needed here - the server runs asynchronously
}

Устранение распространенных проблем

If your project isn’t working, consult this table to diagnose and fix common problems:

Symptom Possible Cause Решение
Sensor reads -127°C (or 85°C) Missing 4.7kΩ pull-up resistor, loose connection, or incorrect GPIO pin. 1. Verify the 4.7kΩ resistor is between DATA and 3.3V.
2. Check all wiring connections.
3. Ensure the correct GPIO is defined in ONE_WIRE_BUS.
Web server fails to connect Incorrect WiFi credentials, weak signal, or library conflict. 1. Перепроверьте. SSID и пароль.
2. Ensure you installed ESPAsyncWebServer и AsyncTCP, not the similarly named synchronous libraries.
Multiple sensors not detected Wiring error in parallel connection or power issue. 1. Confirm all VDD, GND, and DATA lines are connected in parallel.
2. Use an external 3.3V power supply if connecting more than 3-4 sensors to avoid overloading the ESP32.
“Failed to read from DS18B20” Parasite power mode instability or long wires. 1. Switch to Normal Mode (connect VDD to 3.3V) for better reliability.
2. Keep wires as short as possible, especially for multiple sensors.

Project Ideas and Next Steps

With a working temperature monitoring system, you can expand your project:

  • Data Logging: Modify the web server code to save temperature readings with timestamps to a microSD card.

  • Home Automation: Send temperature data to platforms like Домашний помощник или Node-RED via MQTT to trigger alerts or control heaters/AC units.

  • Weather Station: Combine the DS18B20 with a humidity sensor (like DHT22) and the web server to create a full-featured local weather station.

This guide provides a robust, tested foundation for integrating the DS18B20 with your ESP32. By following the wiring diagrams, using the updated 2026 code examples, and applying the troubleshooting tips, you’ll be able to implement reliable temperature sensing for any application.

======================================

О сайте ESP32S.com

С 2016 года, ESP32S.com Наша компания превратилась в полноценного партнера по экосистеме для вашего развития в сфере Интернета вещей. Расположенная в Шэньчжэне, глобальном центре инноваций в электронике, мы помогли сотням разработчиков и компаний реализовать свои проекты. ESP32Воплощаем идеи в жизнь. Наша команда стремится оказывать исключительную поддержку и предлагать инновационные решения, которые помогут вам достичь ваших целей в области Интернета вещей.
В ESP32S.com, мы осваиваем тонкости разработки ESP32Разработка продукта, основанного на концепции, включает в себя множество этапов, от разработки до вывода на рынок. Именно поэтому мы предлагаем комплексные решения, охватывающие весь жизненный цикл продукта. ESP32Устройства на базе [технологии]. Независимо от того, нужна ли вам помощь в проектировании печатных плат, создании прототипов, производстве или даже маркетинге и доставке, мы вам поможем.

Свяжитесь с нами

Готовы вывести свой IoT-проект на новый уровень? Свяжитесь с ESP32S.com Узнайте больше о наших комплексных решениях уже сегодня! ESP32Устройства на базе [технологии]. Позвольте нам стать вашим надежным партнером в воплощении ваших инновационных идей в жизнь. Свяжитесь с нами прямо сейчас для начала.