1-Wire sensors

1-Wire sensors connect to GPIO-4 on the Raspberry Pi (pin 7 of the 40-pin header).

To use the 1-Wire sensors, add the following line to /boot/config.txt:


Now connect the sensors and reboot the Raspberry Pi.
After reboot, the devices will become available in /sys/bs/w1/devices. Each device will get its own directory with a number of files.
Just read the /sys/bus/w1/devices/<device-id>/w1_slave file to access the sensor

DS18B20 temperature sensor

The DS18B20 is a 1-Wire temperature sensor. It allows temperature measurements from -55 to +125°C with ± 0.5°C accuracy. The full datasheet is available at the Maxim website.

On the Raspberry Pi, the sensor can be read by opening an reading the w1_slave file in the device's directory (in my case /sys/bus/w1/devices/28-800000036599. The simplest way of reading the file is by performing a cat command in the shell.
The result of this is:

pi@RPi-3-2:/sys/bus/w1/devices/28-800000036599 $ cat w1_slave
2c 01 ff ff 7f ff ff ff 61 : crc=61 YES
2c 01 ff ff 7f ff ff ff 61 t=18750
pi@RPi-3-2:/sys/bus/w1/devices/28-800000036599 $

The actual output is shown in green and consists of 2 lines. Both lines start with the binary data from the sensor, followed by an explanatory text. crc=61 YES gives the CRC with YES stating the CRC checks out ok. t=18750 is the temperature in 1/1000 °C increments.

From C, the temperature can be read from the file and converted into a floating point number using the following lines of code:

int fd;
ssize_t numRead;
char buf[256];
char tmpData[8];
float temp;

fd = open("/sys/bus/w1/devices/28-800000036599/w1_slave", O_RDONLY);

numRead = read(fd, buf, 256)) > 0)

strncpy(tmpData, strstr(buf, "t=")+2, 7);
temp = strtof(tmpData, NULL) / 1000;

The read operation will read the full content of the file, strstr is used to locate the position of "t=" in the file and strncpy then copies only the numeric value into the tmpData string. Finally strtof converts that string into a floating point number.