luisa88
Posts: 13
Joined: Wed Oct 09, 2019 2:26 pm

How to plot real time multiple one wire temperature sensors and collect data in csv file in python using RPi 3 B+

Wed Oct 30, 2019 3:33 pm

Hi,
I don't know much about python, but I am working on this project where I need to add 30+ one wire temperature sensors to Raspberry Pi 3 B+.
So far I have added 5 sensors and connected as the image suggested:
Image

I have added label to my sensors using

Code: Select all

cd
ls -1 /sys/bus/w1/devices/ | grep "28" >DS18B20.conf
created the config file and then

Code: Select all

nano DS18B20.conf
added label at the end of each sensor with a space in between

I have this code right now

Code: Select all

#!/usr/bin/env python

import glob
import time


# Typical reading
# 73 01 4b 46 7f ff 0d 10 41 : crc=41 YES
# 73 01 4b 46 7f ff 0d 10 41 t=23187

while True:

   for sensor in glob.glob("/sys/bus/w1/devices/28-00*/w1_slave"):
      id = sensor.split("/")[5]

      try:
         f = open(sensor, "r")
         data = f.read()
         f.close()
         if "YES" in data:
            (discard, sep, reading) = data.partition(' t=')
            t = float(reading) / 1000.0
            print("{} {:.1f}".format(id, t))
         else:
            print("999.9")

      except:
         pass

   time.sleep(3.0)
But it didn't work, can you help me with the code, and how can I plot real time graph of the 5 sensors in one graph.
I was able to plot a real time graph with one sensor :

Code: Select all

import time
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from w1thermsensor import W1ThermSensor
sensor=W1ThermSensor()

#create figure for plotting
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
xs=[]
ys=[]

def animate (i,xs,ys):
    
    temperature = sensor.get_temperature()
    
    fahrenheit = temperature * 9 / 5 + 32
    

    #add x and y to lists
    xs.append(dt.datetime.now().strftime('%H:%M:%S'))
    ys.append(fahrenheit)

    #limit x and y lists to 20 items
    xs=xs[-30:]
    ys=ys[-30:]
    
    #draw x and y list
    ax.clear()
    ax.plot(xs,ys)
    

    #format plot
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.title('Temperature over Time')
    plt.ylabel('Temperature (deg F)')

#set up plot to call animate() function periodically
ani=animation.FuncAnimation(fig,animate, fargs=(xs,ys),interval=4000)

#draw the graph
plt.show()
But I have no idea how to plot 5 or more sensors, and with identification of each sensor and maybe assign different color?
And I also need to store those data in a CSV file with time and label of each sensor, I have the following:

Code: Select all

#save to csv file
def write_csv():
    while True:
        with open ("/home/pi/test_temp.csv","a")as log:
                temperature = sensor.get_temperature()
                fahrenheit = temperature * 9 / 5 + 32
                log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(fahrenheit)))
                sleep(5)
write_csv()
But I don't know how to get it work together with the plotting, neither do I know how to make it work for 30+ sensors.
Any help would be appreciated! Thanks

Return to “Beginners”