5101+ reviews
Order by 16:00 for same day shipping
14 days return
GB
EN
Individual
Business
In this project, you will learn how to use aDS18B20 temperature sensor to measure the ambient temperature and display this value on a16x2 LCD display with I2C interface. This is a great application to present data visually.
GPIO | Pin # | Function | Connection |
GPIO 4 | Pin 7 | Temperature sensor data | DS18B20-yellow wire |
GPIO 2 | Pin 3 | I2C SDA | LCD SDA |
GPIO 3 | Pin 5 | I2C SCL | LCD SCL |
3.3V | Pin 1 | Nutrition | DS18B20-red wire |
5V | Pin 2 | Nutrition | LCD VCC |
GND | Pin 6 | Earth (Ground) | DS18B20 and LCD |
Run the following commands in the terminal to install the libraries for the DS18B20 and LCD:
sudo apt-get update
sudo apt-get install python3-pip
pip3 install RPLCD
Activate the 1-Wire interface for the DS18B20:
sudo raspi-config
Check if the DS18B20 is recognized:
ls /sys/bus/w1/devices/
You would see an address like 28-XXXXXXXXXXXX.
Open the Thonny Python IDE and enter the following code:
import os
import glob
from time import sleep
from RPLCD.i2c import CharLCD
# DS18B20-instellingen
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
# LCD-instellingen
lcd = CharLCD(i2c_expander='PCF8574', address=0x27, cols=16, rows=2)
def read_temp_raw():
"""Lees ruwe data van de DS18B20."""
with open(device_file, 'r') as f:
lines = f.readlines()
return lines
def read_temp():
"""Verwerk de data en retourneer de temperatuur in graden Celsius."""
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
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
return temp_c
try:
while True:
temp = read_temp()
print(f"Temperatuur: {temp:.1f} °C")
# Toon de temperatuur op het LCD
lcd.clear()
lcd.write_string("Temp: {:.1f} C".format(temp))
sleep(2)
except KeyboardInterrupt:
print("\nProgramma gestopt.")
lcd.clear()
Click File > Save As and name the file lcd_temperature.py.
Click the greenRun button (▶) at the top the Thonny interface.
with open("temp_log.txt", "a") as log:
log.write(f"{temp:.1f} °C\n")