Advertisement
microrobotics

18B20 Raspberry Pi Python

Mar 30th, 2023 (edited)
6,777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. #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:
  2. #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.
  3.  
  4. import os
  5. import glob
  6. import time
  7.  
  8. # initialize the 1-Wire bus
  9. os.system('modprobe w1-gpio')
  10. os.system('modprobe w1-therm')
  11.  
  12. # find the file name of the 18B20 sensor
  13. base_dir = '/sys/bus/w1/devices/'
  14. device_folder = glob.glob(base_dir + '28*')[0]
  15. device_file = device_folder + '/w1_slave'
  16.  
  17. def read_temp_raw():
  18.     """Read the raw temperature data from the 18B20 sensor"""
  19.     f = open(device_file, 'r')
  20.     lines = f.readlines()
  21.     f.close()
  22.     return lines
  23.  
  24. def read_temp():
  25.     """Read the temperature in Celsius from the 18B20 sensor"""
  26.     lines = read_temp_raw()
  27.     while lines[0].strip()[-3:] != 'YES':
  28.         time.sleep(0.2)
  29.         lines = read_temp_raw()
  30.     equals_pos = lines[1].find('t=')
  31.     if equals_pos != -1:
  32.         temp_string = lines[1][equals_pos+2:]
  33.         temp_c = float(temp_string) / 1000.0
  34.         return temp_c
  35.  
  36. # read the temperature from the sensor and print it
  37. temp = read_temp()
  38. print('Temperature: {:.1f}°C'.format(temp))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement