Autor Tema: Generador automático de código [registros de configuración]  (Leído 3075 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado Picuino

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 5878
    • Picuino
Generador automático de código [registros de configuración]
« en: 05 de Septiembre de 2014, 12:01:26 »
Quiero compartir en esta ocasión un generador automático de código c para programar los registros de configuración de cualquier microprocesador PIC.

El programa realiza automáticamente una conversión de el texto de un Datasheet para convertirlo en algo parecido a esto:

Código: [Seleccionar]
  // INTCON: REGISTER (ADDRESS 0Bh, 8Bh, 10Bh, 18Bh)
   INTCON = (unsigned char)
     +(1<<7) // GIE: Global Interrupt Enable bit
             //   1 = Enables all unmasked interrupts
             //   0 = Disables all interrupts
     +(0<<6) // PEIE: Peripheral Interrupt Enable bit
             //   1 = Enables all unmasked peripheral interrupts
             //   0 = Disables all peripheral interrupts
     +(0<<5) // TMR0IE: TMR0 Overflow Interrupt Enable bit
             //   1 = Enables the TMR0 interrupt
             //   0 = Disables the TMR0 interrupt
     +(0<<4) // INTE: RB0/INT External Interrupt Enable bit
             //   1 = Enables the RB0/INT external interrupt
             //   0 = Disables the RB0/INT external interrupt
     +(1<<3) // RBIE: RB Port Change Interrupt Enable bit
             //   1 = Enables the RB port change interrupt
             //   0 = Disables the RB port change interrupt
     +(0<<2) // TMR0IF: TMR0 Overflow Interrupt Flag bit
             //   1 = TMR0 register has overflowed (must be cleared in software)
             //   0 = TMR0 register did not overflow
     +(0<<1) // INTF: RB0/INT External Interrupt Flag bit
             //   1 = The RB0/INT external interrupt occurred (must be cleared
             //       in software)
             //   0 = The RB0/INT external interrupt did not occur
     +(0);   // RBIF: RB Port Change Interrupt Flag bit
             //   1 = At least one of the RB7:RB4 pins changed state; a
             //       mismatch condition will continue to set the bit. Reading
             //       PORTB will end the mismatch condition and allow the bit
             //       to be cleared (must be cleared in software).
             //   0 = None of the RB7:RB4 pins have changed state



Frente al código tradicional, mucho más críptico:
Código: [Seleccionar]
  INTCON = 0b10001000;


A partir de este código, es sencillo activar o desactivar los distintos bits de un registro de configuración conociendo qué bits se están activando y qué significan.

La ventaja de este código respecto a otro que trabaje a nivel de bit, es que es mucho más rápido y compacto al cargar los 8 bits de una vez.


El programa está escrito en Python y aprovecho este hilo para defender su gran simplicidad y facilidad de uso para realizar este tipo de tareas frente a otros lenguajes.


Programa Python:
doc_to_code.py
Código: Python
  1. # -*- coding: cp1252 -*-
  2. """
  3. Convierte texto de un datasheet en código c para programar los
  4. registros de configuración de un microcontrolador PIC cualquiera.
  5.  
  6. Entrada: copiar texto del datasheet y pegarlo en un archivo de texto
  7.         Por ejemplo: "timer1.txt"
  8. Salida: archivo de texto con el código: "timer1.c"
  9. """
  10.  
  11. import re
  12. import os
  13.  
  14. class empty_class:
  15.    """empty class"""
  16.  
  17. out = []
  18. bit = empty_class()
  19. estado = 0
  20. line_lenght_max = 80
  21.  
  22.  
  23. # Función principal
  24. def main():
  25.    for filename in os.listdir("."):
  26.       if filename[-4:].lower() == ".txt":
  27.          print filename
  28.          procesa(filename)
  29.  
  30.  
  31. # Procesado de datos
  32. def procesa(filename):
  33.    global estado, bit
  34.    lines = read(filename)
  35.  
  36.    for line in lines:
  37.       line = line.strip("\n\t ")
  38.      
  39.       if estado == 0:
  40.          if is_new_register(line):
  41.             estado = 1
  42.             out_reg(line)
  43.  
  44.       elif estado == 1:
  45.          if is_new_bit(line):
  46.             estado = 2
  47.             out_bit(line)
  48.          elif is_new_register(line):
  49.             out_reg(line)
  50.            
  51.  
  52.       elif estado == 2:
  53.          if len(line) < 2 or re.match("Legend:", line):
  54.             estado = 0
  55.          elif is_new_bit(line):
  56.             out_bit(line)
  57.          elif is_new_register(line):
  58.             out_reg(line)
  59.             print "Error, bit inacabado"
  60.             estado = 1
  61.          else:
  62.             out_bit_comment(line);
  63.            
  64.    write(filename, out)
  65.  
  66.  
  67. # Comprueba si es el comienzo de un nuevo registro
  68. def is_new_register(line):
  69.    if re.match("REGISTER [0-9]{1,2}-[1-9]{1,2}: ", line):
  70.       return True
  71.    return False
  72.  
  73. # Imprime el comienzo de un registro nuevo
  74. def out_reg(line):
  75.    line = line.split(":", 1)[1].strip(" \t")
  76.    register = line.split(" ")[0].strip(":")
  77.    register_comment = line.split(" ", 1)[1]
  78.    out.append("\n\n")
  79.    out.append("   // %s: %s" % (register, register_comment))
  80.    out.append("   %s = (unsigned char)" % register)
  81.    print "   Register =", register
  82.  
  83.    
  84. # Comprueba si es el comienzo de un nuevo bit
  85. def is_new_bit(line):
  86.    if re.match("bit[ \t]+[0-9]+(-[0-9]{1,2})? ", line) and not re.match("bit [715] bit 0", line):
  87.       return True
  88.    return False
  89.  
  90.    
  91. def out_bit(line):
  92.    global bit, estado
  93.    bit.pos = line.split(" ")[1].split("-")[-1]
  94.    bit.name = line.split(" ", 3)[-2]
  95.    if len(re.findall("[0-9]:", bit.name)) > 1:
  96.       bit.name = bit.name.split(":")[0][:-1] + ":"
  97.    bit.comment = line.split(" ", 3)[-1]
  98.  
  99.    if (int(bit.pos) > 9):
  100.       out.append("     +(0<<%s)// %s %s" % (bit.pos, bit.name, bit.comment))
  101.    elif (int(bit.pos) > 0):
  102.       out.append("     +(0<<%s) // %s %s" % (bit.pos, bit.name, bit.comment))
  103.    else:
  104.       out.append("     +(0);   // %s %s" % (bit.name, bit.comment))
  105.  
  106.    if re.search("unimplemented", line.lower()) and bit.pos == "0":
  107.       bit = empty_class()
  108.       estado = 1
  109.  
  110.  
  111. def out_bit_comment(line):
  112.    if re.match("[01]+ = ", line):
  113.       out.append("             //   %s" % bin_dec(line))
  114.    else:
  115.       out[-1] = out[-1] + " %s" % line
  116.      
  117.    while len(out[-1]) > line_lenght_max:
  118.       string = out[-1]
  119.       i = line_lenght_max - 1
  120.       while i > 20:
  121.          if string[i] == " ":
  122.             break
  123.          i = i - 1
  124.       out[-1] = string[:i]
  125.       out.append("             //       %s" % string[i+1:])
  126.  
  127.  
  128.  
  129. # Leer fichero de entrada
  130. def read(filename):
  131.    fi = open(filename, "rt")
  132.    lines = [line for line in fi]
  133.    fi.close()
  134.    return lines
  135.  
  136.  
  137. # Escribir lineas en un fichero de salida
  138. def write(filename, lines):
  139.    filename = re.sub(".txt$", ".c", filename.lower())
  140.    fo = open(filename, "wt")
  141.    fo.write("\n".join(lines))
  142.    fo.write("\n");
  143.    fo.close()
  144.  
  145.          
  146. # Traducir de binario a decimal
  147. def bin_dec(string):
  148.    strbin_dec = [["00", 0], ["01", 1], ["10", 2], ["11", 3]]
  149.    for i in range(4):
  150.       new = []
  151.       for b, d in strbin_dec:
  152.          new.append( ["0" + b, d] )
  153.          new.append( ["1" + b, d + 2**len(b)] )
  154.       for n in new:
  155.          strbin_dec.append(n)                  
  156.    for b, d in strbin_dec:
  157.       if re.match("%s =" % b, string):
  158.          string = re.sub("%s = " % b, "%d = " % d, string, 1)
  159.    return string
  160.        
  161. main()


Para utilizar el programa hay que seguir estos pasos:

1.- Instalar Python 2.7  
     https://www.python.org/download/releases/2.7

2.- Guardar el programa Python anterior (o el que adjunto) en una carpeta

3.- Crear un nuevo archivo de texto, con cualquier nombre pero terminado en ".txt"

4.- Ejecutar el programa en Python

5.- Abrir el programa recien creado de código, con extensión ".c"


Saludos.
« Última modificación: 05 de Septiembre de 2014, 12:04:33 por Picuino »

Desconectado Picuino

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 5878
    • Picuino
Re: Generador automático de Código c para programar registros de configuración
« Respuesta #1 en: 05 de Septiembre de 2014, 12:03:58 »
Ejemplo de uso:

Registros del 16f876A que necesita Miquel para manejar el CCP.

Código: [Seleccionar]



   // INTCON: REGISTER (ADDRESS 0Bh, 8Bh, 10Bh, 18Bh)
   INTCON = (unsigned char)
     +(0<<7) // GIE: Global Interrupt Enable bit
             //   1 = Enables all unmasked interrupts
             //   0 = Disables all interrupts
     +(0<<6) // PEIE: Peripheral Interrupt Enable bit
             //   1 = Enables all unmasked peripheral interrupts
             //   0 = Disables all peripheral interrupts
     +(0<<5) // TMR0IE: TMR0 Overflow Interrupt Enable bit
             //   1 = Enables the TMR0 interrupt
             //   0 = Disables the TMR0 interrupt
     +(0<<4) // INTE: RB0/INT External Interrupt Enable bit
             //   1 = Enables the RB0/INT external interrupt
             //   0 = Disables the RB0/INT external interrupt
     +(0<<3) // RBIE: RB Port Change Interrupt Enable bit
             //   1 = Enables the RB port change interrupt
             //   0 = Disables the RB port change interrupt
     +(0<<2) // TMR0IF: TMR0 Overflow Interrupt Flag bit
             //   1 = TMR0 register has overflowed (must be cleared in software)
             //   0 = TMR0 register did not overflow
     +(0<<1) // INTF: RB0/INT External Interrupt Flag bit
             //   1 = The RB0/INT external interrupt occurred (must be cleared
             //       in software)
             //   0 = The RB0/INT external interrupt did not occur
     +(0);   // RBIF: RB Port Change Interrupt Flag bit
             //   1 = At least one of the RB7:RB4 pins changed state; a
             //       mismatch condition will continue to set the bit. Reading
             //       PORTB will end the mismatch condition and allow the bit
             //       to be cleared (must be cleared in software).
             //   0 = None of the RB7:RB4 pins have changed state



   // T1CON: TIMER1 CONTROL REGISTER (ADDRESS 10h)
   T1CON = (unsigned char)
     +(0<<6) // Unimplemented: Read as ‘0’
     +(0<<4) // T1CKPS: Timer1 Input Clock Prescale Select bits
             //   3 = 1:8 prescale value
             //   2 = 1:4 prescale value
             //   1 = 1:2 prescale value
             //   0 = 1:1 prescale value
     +(0<<3) // T1OSCEN: Timer1 Oscillator Enable Control bit
             //   1 = Oscillator is enabled
             //   0 = Oscillator is shut-off (the oscillator inverter is turned
             //       off to eliminate power drain)
     +(0<<2) // T1SYNC: Timer1 External Clock Input Synchronization Control bit
             //       When TMR1CS = 1:
             //   1 = Do not synchronize external clock input
             //   0 = Synchronize external clock input When TMR1CS = 0: This
             //       bit is ignored. Timer1 uses the internal clock when
             //       TMR1CS = 0.
     +(0<<1) // TMR1CS: Timer1 Clock Source Select bit
             //   1 = External clock from pin RC0/T1OSO/T1CKI (on the rising
             //       edge)
             //   0 = Internal clock (FOSC/4)
     +(0);   // TMR1ON: Timer1 On bit
             //   1 = Enables Timer1
             //   0 = Stops Timer1



   // CCP1CON: REGISTER/CCP2CON REGISTER (ADDRESS 17h/1Dh)
   CCP1CON = (unsigned char)
     +(0<<6) // Unimplemented: Read as ‘0’
     +(0<<4) // CCPxX:CCPxY: PWM Least Significant bits Capture mode: Unused.
             //       Compare mode: Unused. PWM mode: These bits are the two
             //       LSbs of the PWM duty cycle. The eight MSbs are found in
             //       CCPRxL.
     +(0);   // CCPxM: CCPx Mode Select bits
             //   0 = Capture/Compare/PWM disabled (resets CCPx module)
             //   4 = Capture mode, every falling edge
             //   5 = Capture mode, every rising edge
             //   6 = Capture mode, every 4th rising edge
             //   7 = Capture mode, every 16th rising edge
             //   8 = Compare mode, set output on match (CCPxIF bit is set)
             //   9 = Compare mode, clear output on match (CCPxIF bit is set)
             //   10 = Compare mode, generate software interrupt on match
             //       (CCPxIF bit is set, CCPx pin is unaffected)
             //   11 = Compare mode, trigger special event (CCPxIF bit is set,
             //       CCPx pin is unaffected); CCP1 resets TMR1; CCP2 resets
             //       TMR1 and starts an A/D conversion (if A/D module is
             //       enabled) 11xx = PWM mode




En el programa se puede configurar con mucha facilidad el número máximo de columnas que debe tener el resultado. En este caso se están utilizando un máximo de 80 columnas



Todo el texto original está sacado del datasheet tal cual, sin quitar ni modificar nada:

Código: [Seleccionar]
REGISTER 2-3: INTCON REGISTER (ADDRESS 0Bh, 8Bh, 10Bh, 18Bh)
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-x
GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF
bit 7 bit 0
bit 7 GIE: Global Interrupt Enable bit
1 = Enables all unmasked interrupts
0 = Disables all interrupts
bit 6 PEIE: Peripheral Interrupt Enable bit
1 = Enables all unmasked peripheral interrupts
0 = Disables all peripheral interrupts
bit 5 TMR0IE: TMR0 Overflow Interrupt Enable bit
1 = Enables the TMR0 interrupt
0 = Disables the TMR0 interrupt
bit 4 INTE: RB0/INT External Interrupt Enable bit
1 = Enables the RB0/INT external interrupt
0 = Disables the RB0/INT external interrupt
bit 3 RBIE: RB Port Change Interrupt Enable bit
1 = Enables the RB port change interrupt
0 = Disables the RB port change interrupt
bit 2 TMR0IF: TMR0 Overflow Interrupt Flag bit
1 = TMR0 register has overflowed (must be cleared in software)
0 = TMR0 register did not overflow
bit 1 INTF: RB0/INT External Interrupt Flag bit
1 = The RB0/INT external interrupt occurred (must be cleared in software)
0 = The RB0/INT external interrupt did not occur
bit 0 RBIF: RB Port Change Interrupt Flag bit
1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set
the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared
(must be cleared in software).
0 = None of the RB7:RB4 pins have changed state
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown





REGISTER 6-1: T1CON: TIMER1 CONTROL REGISTER (ADDRESS 10h)
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON
bit 7 bit 0
bit 7-6 Unimplemented: Read as ‘0’
bit 5-4 T1CKPS1:T1CKPS0: Timer1 Input Clock Prescale Select bits
11 = 1:8 prescale value
10 = 1:4 prescale value
01 = 1:2 prescale value
00 = 1:1 prescale value
bit 3 T1OSCEN: Timer1 Oscillator Enable Control bit
1 = Oscillator is enabled
0 = Oscillator is shut-off (the oscillator inverter is turned off to eliminate power drain)
bit 2 T1SYNC: Timer1 External Clock Input Synchronization Control bit
When TMR1CS = 1:
1 = Do not synchronize external clock input
0 = Synchronize external clock input
When TMR1CS = 0:
This bit is ignored. Timer1 uses the internal clock when TMR1CS = 0.
bit 1 TMR1CS: Timer1 Clock Source Select bit
1 = External clock from pin RC0/T1OSO/T1CKI (on the rising edge)
0 = Internal clock (FOSC/4)
bit 0 TMR1ON: Timer1 On bit
1 = Enables Timer1
0 = Stops Timer1
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown




REGISTER 8-1: CCP1CON REGISTER/CCP2CON REGISTER (ADDRESS 17h/1Dh)
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — CCPxX CCPxY CCPxM3 CCPxM2 CCPxM1 CCPxM0
bit 7 bit 0
bit 7-6 Unimplemented: Read as ‘0’
bit 5-4 CCPxX:CCPxY: PWM Least Significant bits
Capture mode:
Unused.
Compare mode:
Unused.
PWM mode:
These bits are the two LSbs of the PWM duty cycle. The eight MSbs are found in CCPRxL.
bit 3-0 CCPxM3:CCPxM0: CCPx Mode Select bits
0000 = Capture/Compare/PWM disabled (resets CCPx module)
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th rising edge
1000 = Compare mode, set output on match (CCPxIF bit is set)
1001 = Compare mode, clear output on match (CCPxIF bit is set)
1010 = Compare mode, generate software interrupt on match (CCPxIF bit is set, CCPx pin is
unaffected)
1011 = Compare mode, trigger special event (CCPxIF bit is set, CCPx pin is unaffected); CCP1
resets TMR1; CCP2 resets TMR1 and starts an A/D conversion (if A/D module is
enabled)
11xx = PWM mode
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown

Saludos.
« Última modificación: 05 de Septiembre de 2014, 12:08:20 por Picuino »

Desconectado pablomanieri

  • Colaborador
  • PIC24F
  • *****
  • Mensajes: 639
Re: Generador automático de código [registros de configuración]
« Respuesta #2 en: 05 de Septiembre de 2014, 12:30:37 »
Me gusta. A probarlo

Desconectado jhozate

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1697
Re: Generador automático de código [registros de configuración]
« Respuesta #3 en: 05 de Septiembre de 2014, 12:49:52 »
Magnífico  :mrgreen: !
creo que haber visto en el facebook de microchip una herramienta parecida pero para los pic32 :2]
« Última modificación: 05 de Septiembre de 2014, 12:52:58 por jhozate »
Ser Colombiano es un Premio, Saludos desde CALI-COLOMBIA


Desconectado Miquel_S

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1251
Re: Generador automático de código [registros de configuración]
« Respuesta #5 en: 05 de Septiembre de 2014, 14:52:41 »
 ((:-)) ((:-)) Excelente
Todos somos muy ignorantes. Lo que ocurre es que no todos ignoramos las mismas cosas.

Desconectado Picuino

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 5878
    • Picuino
Re: Generador automático de código [registros de configuración]
« Respuesta #6 en: 06 de Septiembre de 2014, 11:42:52 »
Si les ha gustado esta aplicación, no se vayan todavía, aún hay más   ;-)

En la segunda versión he mecanizado aún más el proceso.
A partir del datasheet de Microchip en formato *.pdf, el programa extrae automáticamente todos los registros de configuración.
Esta nueva versión la he adaptado para que funcione con nuevos PIC con los que antes no funcionaba.

Además del programa Python, ahora se utiliza una herramienta de código abierto muy interesante llamada xpdf y que es capaz de convertir el archivo PDF en un archivo de texto TXT.
La página de descargas es: http://www.foolabs.com/xpdf/download.html
La herramienta a utilizar se llama "pdftotext.exe" en el caso de Windows

Yo he utilizado la versión de Windows de xpdf, pero hay versiones para Linux y Mac.
El programa en Python también se puede ejecutar en Linux y en Mac, con la ventaja de que en estos sistemas operativos el lenguaje Python viene ya preinstalado.


He probado la herramienta con una muestra escogida de PICs:

dspic33ep128mc504.pdf
dspic33fj32gp102.pdf
pic12f510.pdf
pic16f1829.pdf
pic16f628a.pdf
pic16f876.pdf
pic16f88.pdf
pic16f886.pdf
pic18f2525.pdf
pic18f2550.pdf
pic18f26k80.pdf
pic24f16km202.pdf
pic24f32ka304.pdf
pic32mx110f016.pdf


La conversión total apenas dura unos segundos.
Después de un vistazo al código generado, no he visto fallos importantes. Si alguien encuentra algún fallo, puede ayudar reportando en el hilo.

Algunos datasheet antiguos como el del PIC16F84 no funcionan bien porque hay diferencias en el estilo de los datasheet con respecto a los nuevos. Cambiando el archivo de texto para que sea semejante a los nuevos, puede funcionar. Como estos micros están obsoletos, no me he molestado en darles soporte.


Adjunto el programa en Python y la lista de registros generados para los microcontroladores de la lista anterior.

Para descargar el binario "pdftotext.exe" para Windows: ftp.foolabs.com/pub/xpdf/xpdfbin-win-3.04.zip
Todas las versiones para diferentes sistemas operativos: http://www.foolabs.com/xpdf/download.html

(No puedo adjuntarlo porque el tamaño es mayor de 256kb)


Un saludo.
« Última modificación: 06 de Septiembre de 2014, 11:52:49 por Picuino »


Desconectado jeremylf

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1341
Re: Generador automático de código [registros de configuración]
« Respuesta #8 en: 06 de Septiembre de 2014, 23:09:16 »
Buen programa!

Desconectado jhozate

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1697
Re: Generador automático de código [registros de configuración]
« Respuesta #9 en: 07 de Septiembre de 2014, 13:55:14 »
hola picuino, hay que hacer algun procedimiento para instalar el xpdf , ejecuto el pdftotext y no sucede nada, ya instale el phyton nunca lo he usado.
Ser Colombiano es un Premio, Saludos desde CALI-COLOMBIA

Desconectado Picuino

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 5878
    • Picuino
Re: Generador automático de código [registros de configuración]
« Respuesta #10 en: 07 de Septiembre de 2014, 16:00:08 »

No hay que hacer ningúna instalación, al menos en Windows.

El archivo doc_to_code.py, se extrae sin más de su archivo ZIP en la carpeta que quieras:

   http://www.todopic.com.ar/foros/index.php?action=dlattach;topic=43374.0;attach=22536


El archivo pdftotext.exe viene comprimido en un ZIP. Hay que extraer el archivo en el mismo directorio que el programa anterior "doc_to_code.py":

   ftp.foolabs.com/pub/xpdf/xpdfbin-win-3.04.zip


A continuación colocas en esa misma carpeta el datasheet. Por ejemplo PIC18F2550.pdf:

   http://ww1.microchip.com/downloads/en/DeviceDoc/39632e.pdf



Por último ejecutas el archivo Python dando doble click sobre "doc_to_code.py"

Otra forma de ejecutarlo es pinchando "doc_to_code.py" con el botón derecho del ratón y pulsando "Edit with IDLE" del menú desplegable.
Se abrirá el entorno gráfico de Python con el archivo ejecutable. Pulsando ahora "F5" o el menú "Run... Run Módule", el archivo también se ejecuta.


No te olvides de dejar el resultado en el hilo, por si a alguien le interesa. Gracias.
Si vés algún problema en la conversion, también vendría bien que lo reportes.


Un saludo.
« Última modificación: 07 de Septiembre de 2014, 16:04:37 por Picuino »

Desconectado jhozate

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1697
Re: Generador automático de código [registros de configuración]
« Respuesta #11 en: 07 de Septiembre de 2014, 16:48:38 »
correcto, si ha generado el archivo .c  , me corriges si el que esta confundido soy yo. 
Los registros que en el datasheet se muestran como por ej bit 14-12, el archivo traduce +(0<<12) , de esa forma solo se podria setear o resetear el bit 12.

No he probado en el compilador que uso, entonces no se si habrá problema con el +, podría ser mas conveniente usar el operador or |  ?
Ser Colombiano es un Premio, Saludos desde CALI-COLOMBIA

Desconectado Picuino

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 5878
    • Picuino
Re: Generador automático de código [registros de configuración]
« Respuesta #12 en: 07 de Septiembre de 2014, 16:57:14 »
Yo utilizo el + y me dió problemas con el último bit (el 7 o el 15) que lo interpretaba como bit de signo.
Lo solucioné haciendo un cast. De ahí que aparezca (unsigned int).

El or "|" debería funcionar sin problemas, pero no lo he probado.

Se pueden setear varios bits a la vez sin problemas si se coloca un número decimal:

   (5<<12)   es igual a   (0b101<<12)   que es igual a   101000000000000


A mí me parece más sencillo poner un número decimal "5". Por eso el programa traduce todos los comentarios de binario a decimal.


Saludos.
« Última modificación: 07 de Septiembre de 2014, 17:00:19 por Picuino »