As you should know, DS18x20 family members are relatively accurate digital temperature sensors. They use MAXIM’s 1-wire bus protocol, which requires only 1 wire for receiving and transmitting data (A ground line is also required). Moreover, DS18x20 support so-called parasite power mode, when they drain energy from data bus when it’s high – to charge sensor’s integrated capacitors that will be used as a power source. Sure, they also support normal power scheme, with external supply (and this scheme is used in this article).
You can have up to 127 devices on 1-Wire line. To use one of them, a master device initiates a reset pulse, and them receives presence pulse from slave devices. Then he searches ROMs (each produced device has a unique 64-bit ROM code, like serial number. Tiny first part of it defines a family of device, like 0x10 for DS18S20, 0x28 for DS18B20, 0x01 for iButton-DS1990A etc., and all remaining bits are a unique item number. Finally, master device selects the necessary slave device with MATCH ROM [55h] command. (Or transmits broadcast commands).
By the way: to us all data transfer on 1-wire bus seems to be organized in bytes. Since OneWire library for Arduino takes charge of all low-level operations, we just send and receive bytes.
All data and commands are transmitted least significant bit first over the 1-Wire bus.
To get a temperature measurement, we need to issue CONVERT [44h] command. When our sensors receive it, they will initiate data conversion process - to produce 2 bytes with the measurement. This is relatively slow process, and it can take up to 750 milliseconds, so we have to wait for some time after issuing the command.
All that measurements are stored in a so-called scratchpad – a piece of sensor’s RAM. We can read it – to get the data, and we can also write to it – to set alarm thresholds, to specify sensor resolution (but it’s more advanced topic, and it will not be discussed in this article).
To read a scratchpad, we issue a READ SCRATCHPAD [BEh] command. After that, we should receive 9 bytes of data (see figure above).
Then we can get a temperature according to the following formulae:
Temp = ((HighByte << 8) + LowByte ) *0.0625
A multiplier of 0.0625 is a conversion coefficient between sensor’s internal values and real temperature – according to 12-bit resolution, each “tick” on sensor’s scale stands for 0.0625 °C.
(do not forget that Temp should be float variable)
To sum up all above, let us write a function that stores the temperature in a global variable, and return true of false depending whether measurement was successful or not:
If there are several sensors in the scheme, this function will give values from each of them in cycles.
Do not forget also to create OneWire object at the beginning of the program:
(And do not forget to download the library and put it to necessary folder)
And here is small circuit schematic for getting started with digital temperature sensors: