两个线程不能同时运行Python3和Raspberry PI

时间:2018-11-22 05:23:13

标签: python-3.x raspberry-pi3

这是我的代码,我想同时启动两个线程,但没有启动。第一个线程帮助我将从传感器获取的数据发布到“ .csv”文件中,第二个线程从该文件中获取数据并绘制图形通过使用matplotlib.SO,它们应该同时运行以提供适当的实时图形输出。请帮忙。

我的代码:

import Adafruit_DHT
import time
import csv
import sys
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.animation as animation
from datetime import datetime
from threading import Thread 

csvfile ="temp.csv"

fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#0079E7')
count = "0"

class Graph:

    def __init__(self):
        self.count = ""

    def storeD(self):
        while True:
            humidity, temperature=Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 17) # gpio pin 4 or pinnumber 7 
            if humidity is not None and temperature is not None:
                humidity= round(humidity, 17)
                temperature = round(temperature, 17)
                print('Temperature = {0:0.1f}*C  Humidity = {1:0.1f}%'.format(temperature,humidity))
            else:
                print('can not connect to the sensor!')
            timeC =time.strftime("%I")+':' +time.strftime("%M")+':'+time.strftime("%S")
            data = [temperature, timeC]

            with open(csvfile, "a")as output:
                writer =csv.writer(output, delimiter=",", lineterminator = '\n')
                writer.writerow(data)
            time.sleep(5)


    def animates(self,i):
        print("test")
        ftemp = 'temp.csv'
        fh = open(ftemp)
        temp = list()
        timeC= list()
        for line in fh:
            pieces = line.split(',')
            degree = pieces[0]
            timeB=  pieces[1]
            timeA= timeB[:8]  #print timeA
            time_string =datetime.strptime(timeA,'%H:%M:%S')  #print time_string
            try:
                temp.append(float(degree))
                timeC.append(time_string)
            except:
                print("dont know")

            ax1 = fig.add_subplot(1,1,1,axisbg='white')
            ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
            ax1.clear()
            ax1.plot(timeC,temp, 'c', linewidth = 3.3)
            plt.title('Temperature')
            plt.xlabel('Time')
        ani = animation.FuncAnimation(fig, test_obj.animates(), interval = 6000)
        plt.show()



if __name__=="__main__":
    test_obj = Graph()
    Thread1=Thread(target=test_obj.storeD())
    Thread2=Thread(target=test_obj.animates(),arg=(i))
    Thread1.start()
    Thread2.start()

新代码

import Adafruit_DHT
import time
import csv
import sys
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.animation as animation
from datetime import datetime
from threading import Thread 

csvfile ="data2.csv"

fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#0079E7')
count = "0"
i = 0
sensor =11
pin= 17
class Graph:

    def __init__(self):
        self.count = ""

    def storeD(self):
        print("Testing")
        while True:
            humidity, temperature =Adafruit_DHT.read_retry(sensor,pin)# gpio pin 4 or pinnumber 7
            if humidity is not None and temperature is not None:
                humidity= round(humidity, 17)
                temperature = round(temperature, 17)
                print('Temperature = {0:0.1f}*C  Humidity = {1:0.1f}%'.format(temperature,humidity))
            else:
                print('can not connect to the sensor!')
            timeC =time.strftime("%I")+':' +time.strftime("%M")+':'+time.strftime("%S")
            data = [temperature, timeC]

            with open(csvfile, "a")as output:
                writer =csv.writer(output, delimiter=",", lineterminator = '\n')
                writer.writerow(data)

        time.sleep(5)

    def animates(self,i):
        print("test")
        ftemp = 'data2.csv'
        fh = open(ftemp)
        temp = list()
        timeC= list()
        time.sleep(5)
        for line in fh:
            pieces = line.split(',')
            degree = pieces[0]
            timeB=  pieces[1]
            timeA= timeB[:8]  #print timeA
            time_string =datetime.strptime(timeA,'%H:%M:%S')  #print time_string
            try:
                temp.append(float(degree))
                timeC.append(time_string)
            except:
                print("dont know")

            ax1 = fig.add_subplot(1,1,1,axisbg='white')
            ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
            ax1.clear()
            ax1.plot(timeC,temp, 'c', linewidth = 3.3)
            plt.title('Temperature')
            plt.xlabel('Time')

if __name__=="__main__":
        test_obj = Graph()

        Thread1=Thread(target=test_obj.storeD())

        Thread2=Thread(target=test_obj.animates, args=(i))
        ani = animation.FuncAnimation(fig, test_obj.animates, interval = 6000)
        plt.show()
        for r in range(5):
            Thread1.start()

        Thread2.start()

请以简单的格式告诉我。我想我可能有一些小错误。用简单的方法试过也没跑。救命!

0 个答案:

没有答案