Siguiendo con las practicas de aprendizaje en Python y mas aun con el proyecto serialPyInterface (que va lento pero hay va) toca el turno de hace una interfaz grafica (GUI), así que me di a la tarea de buscar en la red y encontré el proyecto UART Controller With Tkinter and Python (GUI) en instructables, bueno decidí probarlo y de principio no me funciono así realice varios cambios y medio me funciono, bueno fue una primera base para iniciar. Después de un rato desmenuce algunas cosas y es como he podido hacer funcionar la sección que conecta con el puerto, para la parte del circuito que envía los datos retome el post que manda datos de un DHT22 con Stellaris al monitor serial de energia.
Código Stellaris:
Para este ejemplo use casi el mismo código del anterior post, solo omití algunos mensajes, en esencia manda los datos cada tres segundos una vez que se pulso SW1, si se vuelve a pulsar se detiene el envió de datos.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************************************************************* | |
* | |
* Enviar datos del DHT22 a través del puerto serie a Python | |
* | |
******************************************************************************* | |
* FileName: LM4F_E011.ino | |
* Processor: EX-LM4F120XL | |
* Complier: Energia 1.6.10E18 | |
* Author: Pedro Sánchez (MrChunckuee) | |
* Blog: http://mrchunckuee.blogspot.com/ | |
* Email: mrchunckuee.psr@gmail.com | |
* Description: Este ejemplo se basa en la libreria de Adafruit para el | |
* sensor de temperatura y humedad DHT22, cuando sepulsa SW1 | |
* envia los datos a Python y realiza un blink en el | |
* LED Azul, si se vuelve a pulsar SW1 el envio se detiene. | |
******************************************************************************* | |
* Rev. Date Comment | |
* v0.0.0 31/07/2019 Creación del firmware | |
******************************************************************************/ | |
#include "DHT.h" | |
#define DHTPIN PB_5 // what digital pin we're connected to | |
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 | |
DHT dht(DHTPIN, DHTTYPE); | |
const int pinButton = PUSH1; | |
const int pinLed = BLUE_LED; | |
// Variables will change: | |
int ledState = LOW; // ledState used to set the LED | |
long previousMillis = 0; // will store last time LED was updated | |
long interval = 1500; // interval at which to blink (milliseconds) | |
int buttonState = 0; | |
int buttonTicks = 0; | |
int currentButtonState = 0; | |
int lastButtonState= 0; | |
int buttonFlag = LOW; | |
void setup() { | |
pinMode(pinButton, INPUT_PULLUP); | |
pinMode(pinLed, OUTPUT); | |
Serial.begin(9600); | |
dht.begin(); | |
delay(3000); | |
} | |
void loop(){ | |
GetInput(); | |
if(buttonFlag == HIGH){ | |
unsigned long currentMillis = millis(); | |
if(currentMillis - previousMillis > interval) { | |
// save the last time you blinked the LED | |
previousMillis = currentMillis; | |
// if the LED is off turn it on and vice-versa: | |
if (ledState == LOW){ | |
ledState = HIGH; | |
//Se lee temperatura y humedad | |
float h = dht.readHumidity(); | |
float t = dht.readTemperature(); | |
Serial.print("Humedad: "); | |
Serial.print(h); | |
Serial.print(" % "); | |
Serial.print(" Temperatura: "); | |
Serial.print(t); | |
Serial.println(" *C"); | |
} | |
else | |
ledState = LOW; | |
// set the LED with the ledState of the variable: | |
digitalWrite(pinLed, ledState); | |
} | |
} | |
} | |
void GetInput(void){ | |
// Push Button debounce | |
if (buttonState != digitalRead(pinButton)){ | |
if (buttonTicks > 20){ | |
buttonState = digitalRead(pinButton); | |
buttonTicks = 0; | |
} | |
else buttonTicks++; | |
} | |
else buttonTicks = 0; | |
// Process the push button | |
currentButtonState = buttonState; | |
if (currentButtonState == 0 && lastButtonState == 1){ | |
if (buttonFlag == LOW){ | |
buttonFlag = HIGH; | |
Serial.println("Enviando datos cada 3 segundos!!"); | |
} | |
else{ | |
buttonFlag = LOW; | |
digitalWrite(pinLed, LOW); | |
Serial.println("Se detuvo el envio de datos!!"); | |
Serial.println(" "); | |
} | |
} | |
lastButtonState = currentButtonState; | |
} |
Código Python:
Como se dijo antes se reuso el código, pero se cambiaron algunas cosas para que funcionara adecuadamente y pudiera procesar los datos recibidos.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
******************************************************************************* | |
* | |
* Recepción datos del DHT22 a través del puerto serie | |
* | |
******************************************************************************* | |
* FileName: PY_003.py | |
* Complier: EPython 3.7.1 | |
* Author: Pedro Sánchez (MrChunckuee) | |
* Blog: http://mrchunckuee.blogspot.com/ | |
* Email: mrchunckuee.psr@gmail.com | |
* Description: Ejemplo de recepcion de datos atravez de un puerto COM | |
* usando la libreria pySerial. | |
******************************************************************************* | |
* Rev. Date Comment | |
* v0.0.0 22/02/2019 - Creación del firmware | |
* v0.0.1 14/03/2019 - Se modifico para leer datos en una sola linea | |
* - Se paso de byte a ASCII o UTF-8 y se elimino \r\n | |
* v0.0.2 31/07/2019 - Se realizo la GUI para conectarse a un puerto | |
******************************************************************************* | |
""" | |
import time | |
import threading | |
import serial | |
import tkinter | |
from tkinter import * | |
from tkinter import ttk | |
serial_data = '' | |
filter_data = '' | |
update_period = 5 | |
serial_object = None | |
gui = Tk() | |
gui.title("SerialPyInterface") | |
def connect(): | |
""" | |
La función inicia la conexión del dispositivo UART con los datos establecidos en | |
la GUI: | |
- BaudRate | |
- Numero de puerto | |
- Linux o Windows | |
""" | |
global serial_object | |
version_ = button_var.get() | |
port = port_entry.get() | |
baud = baud_entry.get() | |
try: | |
if version_ == 2: | |
print("Esta usando Linux") | |
try: | |
serial_object = serial.Serial('/dev/tty' + str(port), baud) | |
print('Se ha conectado a ' + serial_object.portstr) | |
except: | |
print ("Cant Open Specified Port") | |
elif version_ == 1: | |
print("Esta usando Windows") | |
serial_object = serial.Serial('COM' + str(port), baud) | |
print('Se ha conectado a ' + serial_object.portstr) | |
except ValueError: | |
print ("Enter Baud and Port") | |
return | |
serial_object.flushInput() | |
time.sleep(1) | |
t1 = threading.Thread(target = get_data) | |
t1.daemon = True | |
t1.start() | |
def get_data(): | |
""" | |
Esta función sirve para recopilar datos del UART y almacenar los datos filtrados | |
en una variable global. | |
""" | |
global serial_object | |
global filter_data | |
while(1): | |
try: | |
serial_data = serial_object.readline() | |
temp_data = serial_data.decode('utf-8') | |
#filter_data = temp_data[:-2] # Removes last two characters (\r\n) | |
filter_data = temp_data.strip('\n').strip('\r') | |
print ('%s' %filter_data) | |
except TypeError: | |
pass | |
if __name__ == "__main__": | |
""" | |
The main loop consists of all the GUI objects and its placement. | |
The main loop handles all the widget placements. | |
""" | |
#Frames | |
frame_2 = Frame(height = 150, width = 480, bd = 3, relief = 'groove').place(x = 7, y = 5) | |
#Labels | |
baud = Label(text = "Baud").place(x = 100, y = 53) | |
port = Label(text = "Port").place(x = 200, y = 53) | |
#Entry | |
baud_entry = Entry(width = 7) | |
baud_entry.place(x = 100, y = 70) | |
port_entry = Entry(width = 7) | |
port_entry.place(x = 200, y = 70) | |
#Radio button | |
button_var = IntVar() | |
radio_1 = Radiobutton(text = "Windows", variable = button_var, value = 1).place(x = 10, y = 20) | |
radio_2 = Radiobutton(text = "Linux", variable = button_var, value = 2).place(x = 110, y = 20) | |
#Button | |
connect = Button(text = "Connect", command = connect).place(x = 15, y = 65) | |
#mainloop | |
gui.geometry('500x200') | |
gui.mainloop() |
Descargas:
Aquí el enlace directo para DESCARGAR los archivos disponibles, también puedes revisar o descargar la información desde mi repositorio en GitHub, si no sabes como descargarlo puedes checar aquí, bueno por el momento es todo si tienes dudas, comentarios, sugerencias, inquietudes, traumas, etc. dejarlas y tratare de responder lo mas pronto posible.
Donaciones:
Si te gusta el contenido o si los recursos te son de utilidad, comparte el enlace en tus redes sociales o sitios donde creas que puede ser de interés y la otra puedes ayudarme con una donación para seguir realizando publicaciones y mejorar el contenido del sitio. También puedes hacer donaciones en especie, ya sea con componentes, tarjetas de desarrollo o herramientas. Ponte en contacto para platicar, o puedes volverte uno de nuestros sponsors.
Pido una retroalimentación avisando cada que un enlace no sirva o tenga errores al momento de abrirlo, así también si una imagen no se ve o no carga, para corregirlo en el menor tiempo posible.
Referencias:
- pgurudatt, "UART Controller With Tkinter and Python (GUI)", https://www.instructables.com/id/UART-Controller-With-Tkinter-and-Python-GUI/
- Adafruit, "DHT sensor library", https://github.com/adafruit/DHT-sensor-library
- Pedro Sánchez (MrChunckuee), "Stellaris LaunchPad & Energia: Probando sensor digital DHT22 (temperatura y humedad relativa) - Envió de datos al monitor serial de Energia", https://mrchunckuee.blogspot.com/2019/06/EK-LM4F120XL-E010.html
0 Comentarios