Lesson 17 DS18B20 Temperature Sensor

Share for us
Share on facebook
Share on twitter
Share on pinterest
Share on whatsapp

Introduction

Temperature Sensor DS18B20 is a commonly used digital temperature sensor featured with small size, low-cost hardware, strong anti-interference capability and high precision. The digital temperature sensor is easy to wire and can be applied a various occasions after packaging. Different from conventional AD collection temperature sensors, it uses a 1-wire bus and can directly output temperature data.

Components

– 1 * Raspberry Pi

– 1 * Network cable (or USB wireless network adapter)

– 1 * DS18B20 Temperature Sensor module

– Several jumper wires

Experimental Principle

With a unique single-wire interface, DS18B20 requires only one pin for a two-way communication with a microprocessor. It supports multi-point networking to measure multi-point temperatures. Eight DS18B20s can be connected at most, because too many of them will consume too much of the power supply and cause low voltage thus instability of signal transmission.

Experimental Procedures

Step 1Build the circuit

                                     Raspberry Pi                              DS18B20 Module

                                              GPIO7  ——————————  S

                                               +5V   ——————————– 5V

                                              GND  ———————————  –

Step 2: Upgrade your kernel

              sudo apt-get update

       sudo apt-get upgrade

Step 3: Mount the device drivers and confirm whether the device is effective or not

                     sudo modprobe w1-gpio

              sudo modprobe w1-therm

cd  /sys/bus/w1/devices/

              ls

28-00000495db35 is an external temperature sensor device, but it may vary with every client. This is the serial number of your DS18b20.

Step 4: Check the current temperature

cd  28-00000495db35

               ls

               cat  w1_slave

The second line t=26187 is current temperature value. If you want to convert it to degree Celsius, you can divide by 1000, that is, the current temperature is 26187/1000=26.187 ℃.

Step 5: After the device is confirmed to work normally, you can read the temperature by programming

 Reference code: path/16_ds18b20/ds18b20_2.c

Step 6: Compile

              gcc  ds18b20_2.c

Step 7: Run

              ./a.out

Now, you should see the current temperature value displayed on the screen.

ds18b20_2.c 

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <wiringPi.h>

#define  BUFSIZE  128

int main(void)
{
	float temp;
	int i, j;
    int fd;
	int ret;

	char buf[BUFSIZE];
	char tempBuf[5];

	while(1){	
		fd = open("/sys/bus/w1/devices/28-00000495db35/w1_slave", O_RDONLY);

		if(-1 == fd){
			perror("open device file error");
			return 1;
		}

		while(1){
			ret = read(fd, buf, BUFSIZE);
			if(0 == ret){
				break;	
			}
			if(-1 == ret){
				if(errno == EINTR){
					continue;	
				}
				perror("read()");
				close(fd);
				return 1;
			}
		}

		for(i=0;i<sizeof(buf);i++){
			if(buf[i] == 't'){
				for(j=0;j<sizeof(tempBuf);j++){
					tempBuf[j] = buf[i+2+j]; 	
				}
			}	
		}

		temp = (float)atoi(tempBuf) / 1000;

		printf("%.3f C\n",temp);

		close(fd);

		delay(500);

	}

	return 0;
}

Python Code

#!/usr/bin/env python
import os
import time

#----------------------------------------------------------------
#	Note:
#		ds18b20's data pin must be connected to pin7.
#----------------------------------------------------------------

# Reads temperature from sensor and prints to stdout
# id is the id of the sensor
def readSensor(id):
	tfile = open("/sys/bus/w1/devices/"+id+"/w1_slave")
	text = tfile.read()
	tfile.close()
	secondline = text.split("\n")[1]
	temperaturedata = secondline.split(" ")[9]
	temperature = float(temperaturedata[2:])
	temperature = temperature / 1000
	print "Sensor: " + id  + " - Current temperature : %0.3f C" % temperature


# Reads temperature from all sensors found in /sys/bus/w1/devices/
# starting with "28-...
def readSensors():
	count = 0
	sensor = ""
	for file in os.listdir("/sys/bus/w1/devices/"):
		if (file.startswith("28-")):
			readSensor(file)
			count+=1
	if (count == 0):
		print "No sensor found! Check connection"

# read temperature every second for all connected sensors
def loop():
	while True:
		readSensors()
		time.sleep(1)

# Nothing to cleanup
def destroy():
	pass

# Main starts here
if __name__ == "__main__":
	try:
		loop()
	except KeyboardInterrupt:
		destroy()