#The 18B20 sensor is a digital temperature sensor that communicates over a 1-Wire interface. Here's an example code in Python that #reads the temperature from an 18B20 sensor connected to a Raspberry Pi:
#Note: This code assumes that the 18B20 sensor is connected to GPIO4 (pin 7) of the Raspberry Pi. If you're using a different pin, #you'll need to modify the device_folder variable accordingly.
import os
import glob
import time
# initialize the 1-Wire bus
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
# find the file name of the 18B20 sensor
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
"""Read the raw temperature data from the 18B20 sensor"""
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
"""Read the temperature in Celsius from the 18B20 sensor"""
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
return temp_c
# read the temperature from the sensor and print it
temp = read_temp()
print('Temperature: {:.1f}°C'.format(temp))