Both Threads Doesn't Work simultaneously Python3 , Raspberry PI











up vote
0
down vote

favorite












Here's My code I want to start both Thread together But it isn't starting.First Thread helps me in posting my data taken from sensor to ".csv" file and the second thread takes data from that file and plots a graph by using matplotlib.SO they should run simultaneously to give a proper live graph output. Please Help.



My Code:



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()


New Code



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()


Please Tell me in the simple format.I think I might be having some minor mistake. Tried by simple method Also but didn't ran. Help!










share|improve this question




























    up vote
    0
    down vote

    favorite












    Here's My code I want to start both Thread together But it isn't starting.First Thread helps me in posting my data taken from sensor to ".csv" file and the second thread takes data from that file and plots a graph by using matplotlib.SO they should run simultaneously to give a proper live graph output. Please Help.



    My Code:



    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()


    New Code



    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()


    Please Tell me in the simple format.I think I might be having some minor mistake. Tried by simple method Also but didn't ran. Help!










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      Here's My code I want to start both Thread together But it isn't starting.First Thread helps me in posting my data taken from sensor to ".csv" file and the second thread takes data from that file and plots a graph by using matplotlib.SO they should run simultaneously to give a proper live graph output. Please Help.



      My Code:



      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()


      New Code



      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()


      Please Tell me in the simple format.I think I might be having some minor mistake. Tried by simple method Also but didn't ran. Help!










      share|improve this question















      Here's My code I want to start both Thread together But it isn't starting.First Thread helps me in posting my data taken from sensor to ".csv" file and the second thread takes data from that file and plots a graph by using matplotlib.SO they should run simultaneously to give a proper live graph output. Please Help.



      My Code:



      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()


      New Code



      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()


      Please Tell me in the simple format.I think I might be having some minor mistake. Tried by simple method Also but didn't ran. Help!







      python-3.x raspberry-pi3






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 at 7:32

























      asked Nov 22 at 5:23









      Raj Pandey

      34




      34





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424364%2fboth-threads-doesnt-work-simultaneously-python3-raspberry-pi%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424364%2fboth-threads-doesnt-work-simultaneously-python3-raspberry-pi%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Berounka

          Fiat S.p.A.

          Type 'String' is not a subtype of type 'int' of 'index'