Heating system interface for communication with Arduino and data graphing
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

157 lines
4.9 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Feb 15 10:44:49 2023
  4. @author: david
  5. """
  6. from threading import Thread
  7. import collections #Colección de datos para graficarlos
  8. import matplotlib.pyplot as plt #Gráficación de datos
  9. import matplotlib.animation as animation #Animar la gráfica
  10. import time
  11. import serial
  12. #import numpy as np
  13. from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg #Crear una figura para insertar en tkinter
  14. import tkinter as tk #Para la interfaz
  15. #from matplotlib.lines import Line2D
  16. def leer_datos():
  17. time.sleep(1.0)
  18. arduino.reset_input_buffer()
  19. print("leyendo")
  20. while(isRun):
  21. global isReceiving
  22. global dato1
  23. print("RECIBIENDO...")
  24. dato1 = float(arduino.readline().decode("utf-8").strip())
  25. print(dato1)
  26. var.set("TEMPERATURA: " + str(dato1) + " °C")
  27. isReceiving = True
  28. def iniciarGrafica(self, muestras,lines):
  29. global dato1
  30. data.append(dato1)
  31. lines.set_data(range(muestras), data)
  32. global isRun
  33. isReceiving = False
  34. isRun = True
  35. dato1 = 0.0
  36. serialPort = 'COM3'
  37. baudRate = 9600
  38. def conectar_serial():
  39. global arduino
  40. try:
  41. arduino = serial.Serial(serialPort, baudRate)
  42. arduino.timeout = 0.5
  43. time.sleep(0.5)
  44. print("CONECTADO")
  45. btnStart.config(state = "normal")
  46. btnConectar.config(state = "disabled")
  47. except:
  48. print("Error de conexión")
  49. def iniciar_hilo():
  50. global thread
  51. thread = Thread(target=leer_datos)
  52. thread.start()
  53. btnStart.config(state = "disabled")
  54. btnPause.config(state = "normal")
  55. def guardarGrafica():
  56. plt.savefig('miFigura.png')
  57. def control1():
  58. window2 = tk.Toplevel()
  59. window2.resizable(width = 0, height = 0)
  60. window2.title('Control Manual')
  61. window2.geometry('500x300')
  62. def control2():
  63. window3 = tk.Toplevel()
  64. window3.resizable(width = 0, height = 0)
  65. window3.title('Control ON/OFF')
  66. window3.geometry('500x300')
  67. def pausar():
  68. anim.event_source.stop()
  69. btnResume.config(state = "normal")
  70. btnPause.config(state = "disabled")
  71. def reanudar():
  72. anim.event_source.start()
  73. btnResume.config(state = "disabled")
  74. btnPause.config(state = "normal")
  75. def desconectar_serial():
  76. global isRun
  77. anim.event_source.stop()
  78. isRun = False
  79. arduino.close()
  80. btnPause.config(state = "disabled")
  81. btnResume.config(state = "disabled")
  82. muestras = 100
  83. data = collections.deque([0] * muestras, maxlen = muestras)
  84. tiempoMuestreo = 100
  85. fig = plt.figure(facecolor = '0.94')
  86. ax = plt.axes(xlim=(0,100), ylim=(-40, 150))
  87. plt.title("Sensor 1 - Arduino")
  88. ax.set_xlabel("Muestras")
  89. ax.set_ylabel("Voltaje")
  90. lines = ax.plot([], [])[0]
  91. root= tk.Tk()
  92. root.title("Sistema de calentamiento")
  93. var = tk.StringVar()
  94. frame = tk.Frame(root, bd=2)
  95. frame.grid(column=0, row=3, columnspan=2, sticky="nsew")
  96. frame1 = tk.Frame(root)
  97. frame1.grid(column=0, row=1, columnspan=2, sticky="EW")
  98. frame2 = tk.Frame(root)
  99. frame2.grid(column=0, row=2, columnspan=2, sticky="EW")
  100. frame0 = tk.Frame(root)
  101. frame0.grid(column=0, row=0, columnspan=2, sticky="EW")
  102. root.columnconfigure(0, weight=1)
  103. root.columnconfigure(1, weight=1)
  104. #self.master.rowconfigure(0, weigh=1)
  105. #self.master.rowconfigure(1, weigh=1)
  106. #self.master.rowconfigure(2, weigh=1)
  107. root.rowconfigure(3, weigh=5)
  108. canvas = FigureCanvasTkAgg(fig, master=frame)
  109. canvas.get_tk_widget().pack(padx=0, pady=0, expand=True, fill='both')
  110. btnManual = tk.Button(frame2, text = "Manual", command = control1)
  111. btnManual.grid(row=0, column=0, pady=2, padx=10)
  112. btnOnOff = tk.Button(frame2, text = "ON/OFF", command = control2)
  113. btnOnOff.grid(row=0, column=1, pady=2, padx=10)
  114. btnConectar = tk.Button(frame1, text = "Connect", command = conectar_serial, bg="#00F1FC")
  115. btnConectar.grid(row=0, column=0, pady=2, padx=10)
  116. btnStart = tk.Button(frame1, text = "Start", command = iniciar_hilo, bg="#008C17", state="disabled")
  117. btnStart.grid(row=0, column=1, pady=2, padx=10)
  118. btnPause = tk.Button(frame1, text = "Pause", command = pausar, bg="#E2E200", state="disabled")
  119. btnPause.grid(row=0, column=2, pady=2, padx=10)
  120. btnResume = tk.Button(frame1, text = "Resume", command = reanudar, bg="#00F428", state="disabled")
  121. btnResume.grid(row=0, column=3, pady=2, padx=10)
  122. btnDesconectar = tk.Button(frame2, text='Disconnect', command = desconectar_serial, bg="#FE5E5E")
  123. btnDesconectar.grid(row=0, column=3, pady=2, padx=10)
  124. labelData = tk.Label(frame2, textvariable=var)
  125. labelData.grid(row=0, column=4, pady=2, padx=500)
  126. barraMenu = tk.Menu(frame0)
  127. barra1 = tk.Menu(barraMenu)
  128. barra1.add_command(label="Guardar gráfica", command=guardarGrafica)
  129. barraMenu.add_cascade(label="Archivo", menu=barra1)
  130. root.config(menu=barraMenu)
  131. anim = animation.FuncAnimation(fig, iniciarGrafica, fargs=(muestras, lines), interval = tiempoMuestreo)
  132. root.geometry('1000x600')
  133. root.mainloop()