Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python I/O threading
#1
Good morning. I am a starter. I hope your understanding becuz my English is not good.

I made simple code with Python. It reads the values ​​[A, B, C, D ...] through serial communication every 1 second with Arduino.

However, after about 20 seconds, a delay occurs. I have asked several places and got answer 'threading function'. But I can make it. Here is the code. Does anyone help me?

Sincerely.

import serial
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as anim

plt.close('all')

fig = plt.figure()
ax1 = fig.add_subplot(3,1,1)
ax2 = fig.add_subplot(3,1,2)
ax3 = fig.add_subplot(3,1,3)

serial_port = '/dev/cu.usbmodem1441';
baud_rate = 38400; #In arduino, Serial.begin(baud_rate)

ser = serial.Serial(serial_port, baud_rate)
write_to_file_path = "data_2.txt";
#output_file = open(write_to_file_path, "w+");

lines = np.ones(100)
etime =[]
temp = []
RH = []
N2 = []
H2O = []
N2M = []
H2OM = []

def animate(i):

    output_file = open(write_to_file_path, "a")
    line = ser.readline()
    line = line.decode("utf-8")
    print(line)
    output_file.write(line)
    output_file.close()
    newline = np.fromstring(line,dtype=float,sep=',')

    for line in lines:
        if len(newline) >1:
            etimeC = newline[0]
            etime.append(etimeC)
            tempC = newline[7]
            temp.append(tempC)
            RHC = newline[8]
            RH.append(RHC)
            N2C = newline[5]*2000/255 #0 to 255 -> 0 to 2000 sccm
            N2MC = newline[9]*2000/1023 #0 to 1023 -> 0 to 2000 sccm
            H2OC = newline[6]*2000/255 #0 to 255 -> 0 to 2000 sccm
            H2OMC = newline[10]*2000/1023 #0 to 1023 -> 0 to 2000 sccm
            N2.append(N2C)
            H2O.append(H2OC)
            N2M.append(N2MC)
            H2OM.append(H2OMC)

    ax1.clear()
    ax2.clear()
    ax3.clear()
    ax1.set_ylim(0,40)
    ax2.set_ylim(0,100)
    ax3.set_ylim(0,2000)
    ax1.set_ylabel('Temp. (oC)')
    ax2.set_ylabel('RH (%)')
    ax3.set_xlabel('Time (s)')
    ax3.set_ylabel('Flow rate (sccm)')
    ax1.annotate(str(tempC)+'oC',xy=(10,10))
    ax2.annotate(str(RHC)+'%',xy=(10,10))
    ax3.annotate('N2 '+str(int(N2MC)),xy=(10,1800))
    ax3.annotate('H2O '+str(int(H2OMC)),xy=(10,20))
    ax1.plot(etime, temp, 'r-', label='temp')
    ax2.plot(etime, RH, 'b-', label='RH')
    ax3.plot(etime,N2,'m',etime,H2O,'g',etime,N2M,'m.',etime,H2OM,'g.')
    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.setp(ax2.get_xticklabels(), visible=False)

ani = anim.FuncAnimation(fig,animate,interval=1000)
plt.show()
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020