Programming Raspberry Pi to Temperature using DS18B20 Sensor
Programming Raspberry Pi to Temperature using DS18B20 Sensor
temperature sensor
AIM: Programming Raspberry Pi to detect temperature using DS18B20 temperature sensor.
OBJECTIVES:
a. To understand the basics of GPIO Pins of Raspberry Pi.
b. To study the basic temperature sensor DS18B20.
c. To write a python program to display temperature sensor reading on LCD display.
1|Page
GPIO Pin Connection:
Pins on Kit Pins on Raspberry Pi
GPIO Pin Pin Number
DS 18B20 GPIO 4 7
LCD_RS GPIO 21 40
LCD_EN GPIO 20 38
D4 GPIO 14 8
D5 GPIO 15 10
D6 GPIO 18 12
D7 GPIO 23 16
+ 3.3V - 1
+ 5V - 2
GND - 6
Procedure:
Note: The Raspbian operating system comes with Python already installed in it.
a. Start Raspberry Pi in desktop mode, open the Applications Menu in the top left of
your screen, and navigate to Programming > Python 3 (IDLE) /. This will open the
Python-shell.
2|Page
b. Write a program for DS18B20 temperature sensor with raspberry pi and save it as
“DS18B20.py” file name.
3|Page
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
lcd_byte(0X01,LCD_CMD) # clear LCD
lcd_byte(LCD_LINE_1, LCD_CMD)
lcd_string("Temp : " + '{0:.2f}'.format(temp_c) + " C")
lcd_byte(LCD_LINE_2, LCD_CMD)
lcd_string("Temp : " + '{0:.2f}'.format(temp_f) + " F")
print("Temp : " + '{0:.2f}'.format(temp_c) + " C\t" + '{0:.2f}'.format(temp_f) + " F")
return temp_c
def lcd_init():
GPIO.setmode(GPIO.BCM)
GPIO.setup(LCD_E, GPIO.OUT)
GPIO.setup(LCD_RS,
GPIO.OUT)GPIO.setup(LCD_D4,
GPIO.OUT) GPIO.setup(LCD_D5,
GPIO.OUT) GPIO.setup(LCD_D6,
GPIO.OUT) GPIO.setup(LCD_D7,
GPIO.OUT)
lcd_byte(0X33,LCD_CMD)
lcd_byte(0X32,LCD_CMD)
lcd_byte(0X28,LCD_CMD)
lcd_byte(0X0C,LCD_CMD)
lcd_byte(0X06,LCD_CMD)
lcd_byte(0X01,LCD_CMD) # clear LCD
def lcd_string(msg):
msg = msg.ljust(LCD_WIDTH, ' ')
for i in range(LCD_WIDTH):
lcd_byte(ord(msg[i]),LCD_CHR)
def lcd_byte(bits, mode):
set4bitMSB(bits, mode)
set4bitMSB(bits << 4, mode)
def set4bitMSB(bits,mode):
GPIO.output(LCD_RS, mode)
GPIO.output(LCD_D4, False)
GPIO.output(LCD_D5, False)
GPIO.output(LCD_D6, False)
GPIO.output(LCD_D7, False)
4|Page
if bits&0x10==0x10:
GPIO.output(LCD_D4, True)
if bits&0x20==0x20:
GPIO.output(LCD_D5, True)
if bits&0x40==0x40:
GPIO.output(LCD_D6, True)
if bits&0x80==0x80:
GPIO.output(LCD_D7, True)
time.sleep(E_DELAY)
GPIO.output(LCD_E, True)
time.sleep(E_PULSE)
GPIO.output(LCD_E, False)
time.sleep(E_DELAY)
lcd_init()
lcd_byte(LCD_LINE_1, LCD_CMD)
lcd_string(":*: FCT Pune :*:")
lcd_byte(LCD_LINE_2, LCD_CMD)
lcd_string(":DC18B20 Sensor:")
time.sleep(2)
while True:
temp = read_temp()
time.sleep(2)
5|Page