2

Currently I can read the temperature reading from a file for both sensor. import os import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

temp_sensor = '/sys/bus/w1/devices/28-0316004f1fff/w1_slave'

def temp_raw():
  f = open(temp_sensor,'r')
  lines = f.readlines()
  f.close()
  return lines

def read_temp():
  lines = temp_raw()
  while lines[0].strip()[-3:] != 'YES':
    time.sleep(0.2)
    lines = temp_raw()
  temp_output = lines[1].find('t=')
  if temp_output != -1:
    temp_string = lines[1][temp_output+2:]
    temp_c = float(temp_string)/1000.0
    return temp_c

while True:
  print(read_temp())
  time.sleep(1)

Now I am trying to read two sensors at once but have no idea how to do it.

  • 1
    This is a general programming question, not specific to the Raspberry Pi. Mind you I have posted scripts in answer to questions on this site which do what you want. – joan Oct 11 '17 at 9:49
  • Connect the second sensor and check under /sys/bus/w1/devices/28-0316004f1fff/w1_slave and you will see how to do it. – MatsK Oct 11 '17 at 15:20
3

You are now only looking for a single slave device (/sys/bus/w1/devices/28-0316004f1fff/w1_slave), but you ought to also look at the other /sys/bus/w1/devices/28*/w1_slave device.

Better try something like:

#!/usr/bin/python

import sys
import glob

sensors = glob.glob("/sys/bus/w1/devices/28*/w1_slave")

for sensor in sensors:
  tfile = open(sensor)
  text = tfile.read()
  tfile.close()
  secondline = text.split("\n")[1]
  temperaturedata = secondline.split(" ")[9]
  temperature = float(temperaturedata[2:])/1000
  print "sensor", sensor, "=", temperature, " degrees."
1

You can get a list of all the one-wire sensors from the w1_master_slaves file.

def get_slaves():
    """Return the IDs for all one-wire sensors available to the system."""
    slaves = []
    slaves_file = '/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves'
    with open(slaves_file, 'r') as f:
        slaves = [slave.strip() for slave in f]
    return slaves

For example:

>>> get_slaves()
['28-000004d12260', '28-000004d01bf3']

Then use these ids to open the specific device files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.