Skip to content

Files

Latest commit

 

History

History
104 lines (74 loc) · 3.27 KB

DS18B20.md

File metadata and controls

104 lines (74 loc) · 3.27 KB

DS18B20 Temperature Sensor

  • KEYWORDS: Module,OneWire,DS18B20,DS18S20,Temperature,Sensor

DS18B20 Cable

One of the most common 1-Wire devices is the DS18B20/DS18S20 thermometer, which can be read with the [[DS18B20.js]] module.

Note: The DS18B20 comes in a cable, SMD, and transistor-style package. We're only covering the cable here, but for others see the Datasheet.

Connect as in the table below, with a 4.7k resistor between data and the 3.3v line.

There seem to be three types of cabled sensor (listed below - please tell us if you find more!). Note: there are two types of Green/Red/Yellow sensor so please check with the seller which one you have (type 2 is the most common).

Sensor type 1 Sensor type 2 Sensor type 3 Espruino 4.7k Resistor
Black Green Yellow GND
Red Red Red 3.3v 1st wire
White/Blue/Yellow Yellow Green Data - any GPIO 2nd wire

To use it (assuming you connected to pin A1), simply write the following on the right-hand side:

var ow = new OneWire(A1);
var sensor = require("DS18B20").connect(ow);
setInterval(function() {
  sensor.getTemp(function (temp) {
    console.log("Temp is "+temp+"°C"); 
  });
}, 1000);

And the current temperature will be displayed every second.

27.625

You can also call the getTemp function directly (for instance console.log(sensor.getTemp())) however in this case it will immediately return with the last temperature reading and will start another. This means the first time getTemp is called, an incorrect temperature will be returned.

Multiple sensors

The DS18B20 communicates over a 1-Wire bus, which allows connecting multiple thermometers on the same data line.

To create an array containing three sensors, simply use:

var ow = new OneWire(A1);
var sensor1 = require("DS18B20").connect(ow, 0);
var sensor2 = require("DS18B20").connect(ow, 1);
var sensor3 = require("DS18B20").connect(ow, 2);
var sensors = [sensor1, sensor2, sensor3];

Alternatively, you can create the same array with a little help of the Array.map() function:

var sensors = ow.search().map(function (device) {
  return require("DS18B20").connect(ow, device);
});

Now make a function that will be called repeatedly by Espruino:

setInterval(function() {
  sensors.forEach(function (sensor, index) {
    sensor.getTemp(function (temp) {
      console.log((index + ": " + temp + "°C"); 
    });
  });
}, 1000);

And the current temperature of each sensor will be displayed every second:

0: 25.3125
1: 21.0625
2: 24.1875

Module reference

  • APPEND_JSDOC: DS18B20.js

Using

  • APPEND_USES: DS18B20

Buying

DS18B20 modules can be purchased from many places: