Microcontroladores PIC en Linux.
¿Quieres reaccionar a este mensaje? Regístrate en el foro con unos pocos clics o inicia sesión para continuar.

manejo del puerto serie con Python

2 participantes

Ir abajo

puerto - manejo del puerto serie con Python Empty manejo del puerto serie con Python

Mensaje por aztk Lun 8 Jun 2009 - 3:26

Aquí mi primer tema con intenciones de aportar algo a estos foros que he estado visitando recientemente.

Lo pongo en este subforo ya que no encontré alguno de 'desarrollo' o algo relacionado con aplicaciones en el ordenador.

--------------------------------

Este tema ya lo he publicado en otros foros, pero aquí dejo una versión más reciente de la aplicación:

Como una continuación del manejo del puerto paralelo con Python que realice como una contribución a un programa de munguis,
ahora presento el manejo del puerto Serie con Python.
Como hardware de comunicación pueden usar cualquiera que permita recibir información por USART (el transmitir no lo usaremos ahora) a una baudrate de 9600 bauds (o puede ser cualquier otra modificando lo correspondiente en el código en Python). Como ejemplo anexo el código en assembly para un PIC 16f876 con un cristal de 4MHz y el PORTB como salida donde se imprimira la información recibida desde el PC.

Código:

;      readf.asm
;
;      CopyLeft 2008 Aztk
;
;      This program is free software; you can redistribute it and/or modify
;      it under the terms of the GNU General Public License as published by
;      the Free Software Foundation; either version 2 of the License, or
;      (at your option) any later version.
;
;      This program is distributed in the hope that it will be useful,
;      but WITHOUT ANY WARRANTY; without even the implied warranty of
;      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;      GNU General Public License for more details.
;
;      You should have received a copy of the GNU General Public License
;      along with this program; if not, write to the Free Software
;      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
;      MA 02110-1301, USA.
; -----------------------------------------------------------------------
;  Este programa configura al PIC para leer 1 byte enviado del PC a
;  una velocidad de 9600 bauds con un cristal de 4MHz.
;  El dato se imprimirá en el PORTB.

processor    16f877
; -----------------------------------------------------------------------
; Template source file generated by piklab

    #include
; -----------------------------------------------------------------------
; Bits de configuración:

    __CONFIG    0x3F71
; -----------------------------------------------------------------------
; inicio

        org    0x00        ; Respetamos vector de
    goto    start        ; interrupción
    org    0x05
start:    bsf    STATUS,RP0    ; Bank01
    clrf    TRISB        ; PORTB = 'ssss ssss'
    movlw    .25        ; Fosc = 4MHz
    movwf    SPBRG        ; BaudRate = 9600
    bsf    TXSTA,BRGH    ; High-Speed
    bcf    TXSTA,SYNC    ; Modo asíncrono
    bcf    STATUS,RP0    ; Bank00
    bsf    RCSTA,SPEN
    bsf    RCSTA,CREN    ; Habilitar recepción
    clrf    PORTB        ; Limpiar primero el PORTB
readf:
wait:    btfss    PIR1,RCIF    ; ¿Dato recibido?
    goto    wait        ; No, esperar
    movf    RCREG,W        ; Si, cargar dato a W
    movwf    PORTB        ; imprimir dato de W al PORTB
    goto    readf        ; Regresar para esperar
          ; otro dato
end

Para el programa en Python utilizaremos el modulo PySerial, Python, las librerías del escritorio GTK+ y las librerías PyGTK, todas las dependencias las pueden descargar/instalar desde Sinaptyc (para usuarios de Debian y derivados).

Código:

#!/usr/bin/env python
#
#      serialfor.py
#     
#      CopyLeft 2008 aztk
#     
#      This program is free software; you can redistribute it and/or modify
#      it under the terms of the GNU General Public License as published by
#      the Free Software Foundation; either version 2 of the License, or
#      (at your option) any later version.
#     
#      This program is distributed in the hope that it will be useful,
#      but WITHOUT ANY WARRANTY; without even the implied warranty of
#      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#      GNU General Public License for more details.
#     
#      You should have received a copy of the GNU General Public License
#      along with this program; if not, write to the Free Software
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#      MA 02110-1301, USA.

import serial

import pygtk
pygtk.require('2.0')
import gtk

s = serial.Serial(0)    # Open port '/dev/tty0', BaudRate 9600
pdatax = 0

class SerialX:
   
    # This callback write a data in serial port
    def writex(self, widget, data):
        global pdatax
       
        # When a button is hold on
        if (widget.get_active()):
            pdatax = pdatax + data
            print "data = %s" %(pdatax)
            s.write(chr(pdatax))
       
        # When a button is hold off
        else:
            pdatax = pdatax - data
            print "data = %s" %(pdatax)
            s.write(chr(pdatax))
   
    # This callback quits the program
    def delete_event(self, widget, event):
        s.write('\x00')    # Clear the seril port
        s.close()        # Close the seril port
        print "data = 0"
        print "Good Wave!!! :)"
        gtk.main_quit()
   
    def destroy(self, widget):
        s.write('\x00')
        s.close()
        print "data = 0"
        print "Good Wave!!! :)"
        gtk.main_quit()
   
    def __init__(self):
       
        # Create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("SerialX")
        self.window.connect("delete_event", self.delete_event)
        self.window.set_border_width(20)
        self.window.set_resizable(gtk.FALSE)
       
        # Create a vertical box
        vbox = gtk.VBox(gtk.TRUE, 2)
        self.window.add(vbox)
       
        for i in range(8):
            bx = "D%d" % i
            dx = gtk.ToggleButton(bx)
            dx.connect("toggled", self.writex, 2**i)
            vbox.pack_start(dx, gtk.TRUE, gtk.TRUE, 2)
       
        # Add a separator for the quitbutton
        separator = gtk.HSeparator()
        separator.set_size_request(90, 1)
        vbox.pack_start(separator, gtk.FALSE, gtk.TRUE)
       
        # Create the "Quit" button
        buttonq = gtk.Button("Quit")
        buttonq.connect("clicked", self.destroy)
        vbox.pack_start(buttonq, gtk.TRUE, gtk.TRUE, 2)
       
        self.window.show_all()
       
        print "Hey Hoo, Let's go!"

def main():
    gtk.main()
    return 0

if __name__ == '__main__':
    SerialX()
    main()


puerto - manejo del puerto serie con Python Serialx

No se les olvide hacer las modificaciones a sus necesidades (como el BaudRate o el PortName) y darle permisos de ejecución al programita.
Cualquier duda, pregunten Smile

Nota: Versión original

aztk
Participante Activo
Participante Activo

Mensajes : 52
Fecha de inscripción : 08/06/2009
Edad : 35
Localización : Tenochtitlan

Volver arriba Ir abajo

puerto - manejo del puerto serie con Python Empty Re: manejo del puerto serie con Python

Mensaje por Pikitin Lun 8 Jun 2009 - 6:59

Gracias aztk. Interesante aporte.

Si te apetece también podrías añadir la parte para el PIC a un tema que hay por ahí de ejemplos en asm... la verdad es que andamos escasos de cosas en asm... Smile

El tema es este: https://pic-linux.forosactivos.net/gputils-asm-f9/que-les-parece-algunos-ejemplos-en-asm-t58.htm

Veo que tienes conocimientos de Python.. no? es que estoy trabado con algunas cosillas y quizás tu me puedas echar una mano; es un programita hecho con WxGlade y hay un par de cosas que no sé como solucionar, a ver si abro un tema aparte con las pregauntas; aunque eso lo tengo un poco parado, pero cualquier día de estos me pongo a ello.
De todas formas... conoces algún sitio en español donde se puedan hacer consultas sobre Python?

Saludos RAMONEros... jeje...

Pikitin
veterano
veterano

Mensajes : 623
Fecha de inscripción : 26/11/2008

http://linuxmicros.blogspot.com/

Volver arriba Ir abajo

Volver arriba

- Temas similares

 
Permisos de este foro:
No puedes responder a temas en este foro.