Autor Tema: (Solucionado) Ayuda con SPI y CS5463  (Leído 22441 veces)

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

Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #45 en: 05 de Enero de 2012, 20:36:10 »
Hola muchachos,

Después de mucho tiempo, vuelvo al post, ya que logré escribir y leer perfectamente los

registros del CS5463, pero no estoy pudiendo leer voltaje, ni corriente, ni potencia,

que es lo que más me interesa.

Supongo yo que el problema puede estar en la interfaz analógica, en el filtrado, pero me

gustaría escuchar su opinión. Como sensor de tensión, estoy utilizando un trafo reductor

a 13Vrms, y desde allí (del secundario) me conecto a un divisor de tensión, en cascada

con un filtro pasabajos RC y finalmente un capacitor diferencial.
Para la corriente estoy utilizando un transformador de corriente, conectado en serie a

la carga. Así que la intensidad es transducida en voltaje. Dicho voltaje es disminuído a

través de un divisor, luego un filtro pasabajos, y luego un capacitor diferencial (igual

que con la interfaz de voltaje).

En cuanto al código, debería de estar bien, ya que la comunicación SPI entre el micro y

el CS5463 funciona a la perfección. Antes de comenzar a leer registros, se ejecuta una

rutina de inicialización y configuración del Cirrus:

1- Reseteo del Cirrus con el comando 0x80 (SW reset)
2- Envío de 3 bytes FF y otro FE para la sincronización con el micro
3- Se escribe en el configuration register A2 A0 3D, que activa high pass filters y

selecciona K=1
4- Configuración del N, para un cristal de 4.096MHz, N=4000
5- Se borran los bits de status register
6- Habilito data ready interruptivo
7- El paso más importante: habilitación de conversiones continuas, enviando el comando

0xE8

Luego de estos pasos, el programa se queda en un loop leyendo el voltaje RMS y

enviándolo por SPI.

Les adjunto imágenes del circuito. A alguien se le puede ocurrir algo?

Saludos!!

Desconectado MGLSOFT

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 7912
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #46 en: 05 de Enero de 2012, 21:38:17 »
Y las imagenes??
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #47 en: 05 de Enero de 2012, 23:55:11 »
No pude adjuntarlas, así que las subí

Interfaz:
 

Circuito completo:
 



Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #48 en: 10 de Enero de 2012, 18:33:44 »
Ninguna sugerencia? Que les parece la interfaz?

Saludos!

Desconectado Suky

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 6758
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #49 en: 10 de Enero de 2012, 20:08:53 »
Y PMON? Reset? Con respecto a la interfaz de entrada, implementé lo mismo, con otros valores de r y c, nada más.


No contesto mensajes privados, las consultas en el foro

Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #50 en: 11 de Enero de 2012, 18:11:43 »
Y PMON? Reset? Con respecto a la interfaz de entrada, implementé lo mismo, con otros valores de r y c, nada más.

Qué frecuencia seleccionaste para los filtros de entrada de voltaje y corriente? Como ves, estoy filtrando hasta los 33.9KHz. Y como capacitores diferenciales, que valor sugerís usar?

PFMON olvidé incluirlo en el schematic, pero está soldado en el circuito (a través de dos resistencias de 10k cada una). No utilizo hardware reset, sólo lo hago por software. Por eso no utilizo dicha pata.

Saludos

Desconectado Suky

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 6758
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #51 en: 11 de Enero de 2012, 19:18:42 »
Y PMON? Reset? Con respecto a la interfaz de entrada, implementé lo mismo, con otros valores de r y c, nada más.

Qué frecuencia seleccionaste para los filtros de entrada de voltaje y corriente? Como ves, estoy filtrando hasta los 33.9KHz. Y como capacitores diferenciales, que valor sugerís usar?

No me acuerdo y no tengo los archivos fuentes, pero era como 3kHz o 1.5kHz. Podes testear con un osciloscopio que nivel de señal de entrada ingresa el CS. Porque de alguna manera vas a tener que calibrarlo.


Saludos!
No contesto mensajes privados, las consultas en el foro

Desconectado medidort

  • PIC10
  • *
  • Mensajes: 17
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #52 en: 28 de Enero de 2012, 14:58:12 »


Hola
He podido después de mucho tiempo escribir y pedirle al CS5463. Sigo teniendo problemas cuando leo los datos que vuelven del Cirrus al PIC.
Estoy tratando de leer el cycle count register que se que vale 4000 decimal, cuando leo deberia obtener en el MSB 0x00 , el del medio 0x0F y en el LSB 0xA0. Actualmente estoy obteniendo 0x00 0x00 y 0x00.
Sin embargo en el osciloscopio veo perfecto que el cirrus me manda el data que espero.
Como comentaba en post anteriores, me sonaba que iba a ver algún problema en el manejo del buffer al mismo tiempo. Adjunto el código de SPI  y de la rutina que implementé para leer el Cycle Count Register.

CODIGO SPI:
///////////////////////////////////////////////////////////////////
//Retorno:               void
//Parametro:      char ; El dato a enviar
//Descripcion:      Envia un dato por el puerto SPI
///////////////////////////////////////////////////////////////////
void SPI_write(char data){

   char dummy=0x00;
                        
   SSPIF =0;  
   dummy=SSPBUF;                  
        SSPBUF = data;   
   while(SSPIF == 0){}    
            
}

///////////////////////////////////////////////////////////////////
//Retorno:           char ;  el dato recibido
//Parametro:      void
//Descripcion:      Recibe un dato por el puerto SPI
///////////////////////////////////////////////////////////////////
char SPI_read(void){
   char data;

    while(!BF){};
      data = SSPBUF;
   return data;
}
  
CODIGO DE PEDIDO DE LECTURA
//Retorno:           void
//Parametro:      void
//Descripcion:      Funcion para pedir el voltaje el cual devuelvo los datos leidos
//               en los tres registros datoH, datoM, datoL.
//////////////////////////////////////////////////////////////////////////////////////
void CIRRUS_readCycleCountReg(void){

   RC2 = LOW; //CS =0
   SPI_write(0x0A);
   SPI_read();
   SPI_write(0xFF);
   datoH = SPI_read();
   SPI_write(0xFF);
   datoM = SPI_read();   
   SPI_write(0xFF);
   datoL = SPI_read();   
   RC2 = HIGH; //CS =1

}



Uploaded with ImageShack.us
« Última modificación: 28 de Enero de 2012, 15:22:08 por medidort »

Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #53 en: 17 de Febrero de 2012, 10:27:22 »
Buenas!

Finalmente FUNCIONA todo el sistema. Tenía problemas constructivos simplemente. Estuve realizando medidas, y todas ellas son coherentes.
Lo que sigue a continuación es la calibración. Leí la hoja de datos y no tiene ningún misterio, es seguir el orden establecido por Cirrus. El problema que tengo es que la placa está soldada, y no puedo conectarle a las entradas diferenciales señales de referencia externas (fuentes bien calibradas, para calibración de ganancia), ni cortocircuitar las entradas y ponerlas a tierra para hacer la calibración de offset, si bien no es tan importante (con HPF=1 no hay que hacer DC offset).

Lo que se me ocurre, al menos para hacer calibración de ganancia, es tomar como señales de referencia las entradas de lìnea (los 220v "achicados" por el divisor) y una corriente conocida, por ejemplo la de una bombita de 60w (obviamente achicada también, por el circuito adaptador de corriente).

Como hicieron ustedes? Utilizaron algún zócalo para desmontar el Cirrus y calibrarlo? Si hubiera sido encapsulado DIP...

Saludos

Desconectado Suky

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 6758
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #54 en: 17 de Febrero de 2012, 15:06:54 »
En nuestro caso se pensó el hardware con la posibilidad de configurarlo para la calibración  :mrgreen:
No contesto mensajes privados, las consultas en el foro

Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #55 en: 17 de Febrero de 2012, 15:56:34 »
En nuestro caso se pensó el hardware con la posibilidad de configurarlo para la calibración  :mrgreen:

 8) eso es previsión....tendré que hacer una placa nueva con switches para calibrar.....saludos

Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #56 en: 02 de Marzo de 2012, 10:30:47 »
Hola Estimados!

Estoy midiendo voltaje. El registro Vrms me da: 0xAF88B4. Para esto el valor de las entradas VIN+ y VIN- es 77.7mVrms cada una.

Como hago la regla de tres para obtener la medición en Español? Cuál es el fondo de escala de Vrms register? La hoja de datos es un poco confusa..

Gracias!

Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #57 en: 29 de Marzo de 2012, 10:04:49 »
Hola,

Tengo a todo el sistema funcionando correctamente, ya puedo leer voltaje, corriente, potencia, FP, etc.
Todas las cargas con FP cerca de 1 (resistivas), son medidas a la perfección: Ief, Vef, P, S, FP, etc.  :)

Lo extraño es que con cargas no lineales, cuyo FP es màs bajo, obtengo FP y P con un 10% de error. Será que PC[6:0] (phase compensation) del registro Configuration Register afecta a esto?
En este momento lo tengo configurado como PC[6:0]=000000.

Por otro lado, el bit AFC del Operational Mode Register lo tengo seteado (AFC=automatic line-frequency=1). Con esto detecto la frecuencia de línea automaticamente.

Que recomiendan?

Saludos

Desconectado MGLSOFT

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 7912
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #58 en: 29 de Marzo de 2012, 10:34:41 »
Podrías publicar tu hardware y firmware, para acelerar el proceso de los que aun no comenzamos con este tema??
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado bolso103

  • PIC10
  • *
  • Mensajes: 20
Re: (Solucionado) Ayuda con SPI y CS5463
« Respuesta #59 en: 29 de Marzo de 2012, 11:12:08 »
Podrías publicar tu hardware y firmware, para acelerar el proceso de los que aun no comenzamos con este tema??

Claro, aquí va.

Código:

Código: [Seleccionar]
;**********************************************************************
;             ARCHIVO PARA GRABAR EN EL PIC P16F690   *
;   *
; SON LAS RUTINAS PARA MANEJAR EL PROTOCOLO SPI   *
;**********************************************************************
;                                                                     *
;   Nombre de archivo:     spi.asm                                   *
;   Fecha inicio:      15 de noviembre del 2011                  *
;   Última modificación: 29 de marzo de 2012     *
;                                                                     *
;   Autores: FUCHS MONKAS VARELA                       *
;   Proyecto: SIME                                      *
;                                                                     *
;                                                                     *
;**********************************************************************
;                                                                     *
;    Archivos requeridos: P16F690.INC                                 *
;                                                                     *
;**********************************************************************
;                                                                     *
;    BIBLIOGRAFÍA: AN220: Watt-Hour Meter using PIC16C923 and CS5460  *
;                                                                     *
;**********************************************************************

list p=16f690 ; list directive to define processor


#include <P16F690.inc> ; processor specific variable definitions

; RELOJ INTERNO
; __CONFIG    _CP_OFF & _CPD_OFF & _BOR_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT & _MCLRE_ON & _FCMEN_OFF & _IESO_OFF

; RELOJ DEL CIRRUS
__CONFIG    _CP_OFF & _CPD_OFF & _BOR_OFF & _PWRTE_ON & _WDT_OFF & _EC_OSC & _MCLRE_ON & _FCMEN_OFF & _IESO_OFF


;***** VARIABLE DEFINITIONS
w_temp EQU 0x7D ; variable used for context saving
status_temp EQU 0x7E ; variable used for context saving
pclath_temp EQU 0x7F ; variable used for context saving




SPBRG_VAL EQU 0x19 ; BRG = 25 dec


;**********************************CALCULO DEL BAUD RATE*************************************************

;                    FOSC
; Desired Baud Rate =  -------------------
;            16(SPBRGH:SPBRG + 1)

;Despejando,

;       FOSC
;   x =       ----------    - 1
;          Desired Baud Rate
;         ------------------
;       16

; 1) Para FOSC = 4Mhz (INTOSCK),

; x = 25.04. Se utiliza 25d como valor más cercano (19h)

; Con ello, queda un baudrate de baud = 9615,38. Un error del 0.16%.




;************************************************************************************************
dirEEPROM EQU 0x20 ;*******verificar donde es que empieza la EEPROM*****
;************************************************************************************************

; CS5460 variables (string equates)
SYNC0 equ 0xFE ; Sync bytes sent as dummy data during reads
SYNC1 equ 0xFF ; No more than 3 SYNC1 bytes at a time.

VOLTAJE_MSB equ 0x60
VOLTAJE_med equ 0x61
VOLTAJE_LSB equ 0x62
 
cblock 0x20 ; Para guardar variables en la RAM, empezando en 0x20
;SSP variables (SPI mode). Buffer de recepcion desde el CS5463
RXDATA0 ; RXDATA buffer MSB
RXDATA1 ; RXDATA buffer
RXDATA2 ; RXDATA buffer LSB

; TXDATA buffer (SPI mode). Buffer de transmision hacia el CS5463
TXDATA  ; Byte de comando para mandar al CS4563
TXDATA0 ; TXDATA buffer MSB
TXDATA1 ; TXDATA buffer
TXDATA2 ; TXDATA buffer LSB
DIRECCION

endc


#define CS PORTC, 2 ; CS



;**********************************************************************
ORG 0x000 ; processor reset vector
  goto main ; go to beginning of program


ORG 0x004 ; interrupt vector location
movwf w_temp ; save off current W register contents
movf STATUS,w ; move status register into W register
movwf status_temp ; save off contents of STATUS register
movf PCLATH,w ; move pclath register into W register
movwf pclath_temp ; save off contents of PCLATH register


; isr code can go here or be located as a call subroutine elsewhere


movf pclath_temp,w ; retrieve copy of PCLATH register
movwf PCLATH ; restore pre-isr PCLATH register contents
movf status_temp,w ; retrieve copy of STATUS register
movwf STATUS ; restore pre-isr STATUS register contents
swapf w_temp,f
swapf w_temp,w ; restore pre-isr W register contents
retfie ; return from interrupt


;**********************************************************************
main
call InicioPuertos ; configuro puertos y SPI
call ConfigCirrus ; configuro cirrus
call SetupSerial

call ResetIDCoff
call ResetVDCoff

;********************CALIBRACIONES A REALIZAR EN EL INICIO*************
;call calibrarVgn
;call calibrarIgn
call CargarCalibracionVoltageGain
call CargarCalibracionCorrienteGain
;**********************************************************************
loop
;call delay1s ; HACER!!
call enviarTrama
;call mostrarNormal
goto loop

;**********************************************************************
enviarTrama:
movlw 0X23 ; numeral
call Envia

call direcc; envio byte de direccion (los 5 mas significativos valen 0)

call LeerPotenciaActiva
movf RXDATA0, W
call Envia
movf RXDATA1, W
call Envia
movf RXDATA2, W
call Envia

call LeerCorriente
movf RXDATA0, W
call Envia
movf RXDATA1, W
call Envia
movf RXDATA2, W
call Envia

call LeerFP
movf RXDATA0, W
call Envia
movf RXDATA1, W
call Envia
movf RXDATA2, W
call Envia

call LeerVoltaje
movf RXDATA0, W
call Envia
movf RXDATA1, W
call Envia
movf RXDATA2, W
call Envia

movlw 0X2A ; asterisco
call Envia
return
;**********************************************************************

mostrarNormal:
call mostrarDireccion
movf DIRECCION, W
call Envia

call mostrarCorriente
call LeerCorriente

movf RXDATA0, W
call Envia

movf RXDATA1, W
call Envia

movf RXDATA2, W
call Envia

call mostrarPotenciaActiva
call LeerPotenciaActiva

movf RXDATA0, W
call Envia

movf RXDATA1, W
call Envia

movf RXDATA2, W
call Envia

call mostrarFP
call LeerFP

movf RXDATA0, W
call Envia

movf RXDATA1, W
call Envia

movf RXDATA2, W
call Envia

movlw 0X0D
call Envia
movlw 0X0D
call Envia
movlw 0X0D
call Envia
movlw 0X0D
call Envia

call LeerPotApa

movf RXDATA0, W
call Envia

movf RXDATA1, W
call Envia

movf RXDATA2, W
call Envia

movlw 0X0D
call Envia
movlw 0X0D
call Envia
movlw 0X0D
call Envia
movlw 0X0D
call Envia

movlw 0xAA
call Envia
call LeerVoltaje

movf RXDATA0, W
call Envia

movf RXDATA1, W
call Envia

movf RXDATA2, W
call Envia

movlw 0xBB
call Envia
return

;**********************************************************************
direcc:
bcf STATUS,RP0 ; Banco 0
bcf STATUS,RP1

btfss PORTA,2
goto negative
goto positive
negative
  bsf DIRECCION, 0
goto salida
positive
bcf DIRECCION, 0
goto salida
salida

btfss PORTC,0
goto negative1
goto positive1
negative1
  bcf DIRECCION, 1
goto salida1
positive1
bsf DIRECCION, 1
goto salida1
salida1

btfss PORTC,1
goto negative2
goto positive2
negative2
  bcf DIRECCION, 2
goto salida2
positive2
bsf DIRECCION, 2
goto salida2
salida2

bcf DIRECCION,3
bcf DIRECCION,4
bcf DIRECCION,5
bcf DIRECCION,6
bcf DIRECCION,7
movf DIRECCION, W
call Envia

;DIP SW
;1 - RA2
;2 - RC0
;3 - RC1
return
;**********************************************************************
CargarCalibracionCorrienteOffset
movlw b'01100000'
movwf TXDATA
movlw 0x56
movwf TXDATA0
movlw 0x66
movwf TXDATA1
movlw 0x66
movwf TXDATA2
call SSPWrite
  return
;**********************************************************************
CargarCalibracionVoltajeOffset
movlw b'01100010'
movwf TXDATA
movlw 0xFF
movwf TXDATA0
movlw 0xDE
movwf TXDATA1
movlw 0x10
movwf TXDATA2
call SSPWrite
  return
;**********************************************************************
CargarCalibracionCorrienteGain
movlw b'01000100'
movwf TXDATA
movlw 0x4D
movwf TXDATA0
movlw 0xE0
movwf TXDATA1
movlw 0x1F
movwf TXDATA2
call SSPWrite
  return
;**********************************************************************
CargarCalibracionVoltageGain
movlw b'01001000'
movwf TXDATA
movlw 0x3B
movwf TXDATA0
movlw 0x4E
movwf TXDATA1
movlw 0x06
movwf TXDATA2
call SSPWrite
  return

;**********************************************************************
calibrarIACOFF
movlw b'11001101'
movwf TXDATA
call SSPCmd
return
;**********************************************************************
calibrarVACOFF
movlw b'11010101'
movwf TXDATA
call SSPCmd
return

;**********************************************************************
calibrarVgn
movlw b'11010110'
movwf TXDATA
call SSPCmd
return
;**********************************************************************
calibrarIgn
movlw b'11001110'
movwf TXDATA
call SSPCmd
return

;**********************************************************************
Sincronizo
movlw SYNC1 ; SYNC1 byte (0xFF)
movwf TXDATA
movlw SYNC1 ; SYNC1 byte (0xFF)
movwf TXDATA0
movlw SYNC1 ; SYNC1 byte (0xFF)
movwf TXDATA1
movlw SYNC0 ; SYNC0 byte (0xFE)
movwf TXDATA2
call SSPWrite ; send sync bytes to CS5460
  return
;**********************************************************************

InicioPuertos

; Establezco entradas y salidas en los puertos. '0' indica que es salida, '1' que es entrada
; Sin conectar = 1, no implementado = 0


;DIP SW
;1 - RA2
;2 - RC0
;3 - RC5


bsf STATUS,RP0 ; Banco 1
bcf STATUS,RP1

  movlw b'00010011'
; RA0 = 1 - programador
; RA1 = 1 - programador
; RA2 = 0 - DIP SW
; RA3 = 0 - programador
; RA4 = 0 - OSC2
; RA5 = 0 - OSC1
; RA6 = 0 - unimplemented
; RA7 = 0 - unimplemented
movwf TRISA



bsf STATUS,RP0 ; Banco 1
bcf STATUS,RP1

movlw b'00110000' ; RB0 = 0 - unimplemented
; RB1 = 0 - unimplemented
; RB2 = 0 - unimplemented
; RB3 = 0 - unimplemented
; RB4 = 1 - SDI
; RB5 = 1 - RX (Xbee)
; RB6 = 0 - SCK
; RB7 = 0 - TX (Xbee)
movwf TRISB


bsf STATUS,RP0 ; Banco 1
bcf STATUS,RP1


  movlw b'01111000'
  movwf TRISC
; RC0 = 1 - DP SW
; RC1 = 1 - DP SW
; RC2 = 0 - /SS
; RC3 = 1 - entrada de SCK para testeo
; RC4 = 1 - SDI
; RC5 = 0
; RC6 = 1 - SS must have TRISC<6> bit set (pagina 183 del 16F690)
; RC7 = 0 - SDO

movlw  b'11000000' ;setup SSP Module - input sampled at end of output, xmit on rising SCLK
movwf SSPSTAT
; bit 0 - BF = 0. Buffer Full Status bit
;BF = 1: Receive complete, SSPBUF is full
;BF = 0: Receive not complete, SSPBUF is empty

; bit 1 - no implementado (0)
; bit 2 - no implementado (0)
; bit 3 - no implementado (0)
; bit 4 - no implementado (0)
; bit 5 - no implementado (0)

; bit 6 - CKE = 1. SPI Clock Edge Select bit.
;Si CKP = 0:
;1 = Data transmitted on rising edge of SCK (Microwire alternate)
;0 = Data transmitted on falling edge of SCK
;Si CKP = 1:
;1 = Data transmitted on falling edge of SCK (Microwire default)
;0 = Data transmitted on rising edge of SCK

; bit 7 - SMP = 1. Input data sampled at end of data output time

bcf STATUS,RP0 ;vuelvo al banco 0
bcf STATUS,RP1

movlw b'00100010'
  movwf SSPCON ; SPI master, Fosc/64, SSP enabled, clk idle low


;bit 3-0 SSPM<3:0>: Synchronous Serial Port Mode Select bits
;0000 = SPI Master mode, clock = FOSC/4
;0001 = SPI Master mode, clock = FOSC/16
;0010 = SPI Master mode, clock = FOSC/64
;0011 = SPI Master mode, clock = TMR2 output/2

; bit 4 - CKP: Clock Polarity Select bit. CKP = 0.
;CKP = 1: Idle state for clock is a high level (Microwire default)
;CKP = 0: Idle state for clock is a low level (Microwire alternate)

; bit 5 SSPEN = 1. Habilitacion del SPI

; bit 6 - SSPOV = 0. Receive Overflow Indicator bit. No overflow
;SSPOV = 1: A new byte is received while the SSPBUF register is still
    ;holding the previous data. In case of overflow, the data in SSPSR is lost.
;Overflow can only occur in Slave mode. The user must read the SSPBUF, even if only
;transmitting data, to avoid setting overflow. In Master mode, the overflow bit
;is not set since each new reception (and transmission) is initiated by writing
;to the SSPBUF register.

; bit 7 - WCOL = 0. Write Collision Detect bit. No collision
;WCOL = 1. The SSPBUF register is written while it is
;still transmitting the previous word (must be cleared in software)


;*******************************LAS ENTRADAS SON DIGITALES****************************************************
bcf STATUS, RP0
bsf STATUS, RP1
movlw 0x00
movwf ANSEL
movlw 0x00
movwf ANSELH
;*************************************************************************************************************
; para que funcione el DP SW

bcf STATUS, RP0; BANK 0
bcf STATUS, RP1

BCF CCP1CON, CCP1M0

bcf STATUS, RP0; BANK 2
bsf STATUS, RP1

BCF CM2CON0, C2ON
BCF VRCON, VP6EN;
BCF CCP1CON, CCP1M1
BCF CCP1CON, CCP1M2
BCF CCP1CON, CCP1M3

bsf STATUS, RP0; BANK 3
bsf STATUS, RP1
BCF PSTRCON, STRD
BCF PSTRCON, STRC
BCF PSTRCON, STRB
BCF PSTRCON, STRA

;*************************************************************************************************************
bcf STATUS, RP1
bcf STATUS, RP0

bsf CS ; Set CS5460 /CS

return



;**********************************************************************


ConfigCirrus
call ResetCS5463 ; reset CS4563
call InitCS5463
return


;**********************************************************************
LeerPotenciaActiva
movlw b'00010100'   
movwf TXDATA
call SSPRead
return
;**********************************************************************
LeerCorriente    
movlw b'00010110'   ; corriente RMS
movwf TXDATA
call SSPRead
return
;**********************************************************************
LeerCorrienteInst    
movlw b'00001110'   ; corriente instantanea
movwf TXDATA
call SSPRead
return
;**********************************************************************
LeerVoltaje    
movlw b'00011000'   ; voltaje RMS
movwf TXDATA
call SSPRead
return
;**********************************************************************
LeerVoltajeInst
movlw b'00010000'   ; voltaje instantaneo
movwf TXDATA
call SSPRead
return
;**********************************************************************
LeerPulseRateReg
movlw b'00001100' ;uso como salidas RA2, RC1, y quiero recibir la palabra 0x800000
movwf TXDATA
call SSPRead ; llamo a leer SPI con el byte 00001100, Pulse Rate Register
return
;*********************************************************************
LeerCycleCountReg
movlw b'00001010'
movwf TXDATA
call SSPRead
return
;*********************************************************************
LeerEpsilonReg
movlw b'00011010'
movwf TXDATA
call SSPRead
return
;*********************************************************************
LeerIDCoff
movlw b'00000010'
movwf TXDATA
call SSPRead
return
;*********************************************************************
LeerVgn
movlw b'00001000'
movwf TXDATA
call SSPRead
return
;*********************************************************************
LeerIgn
movlw b'00000100'
movwf TXDATA
call SSPRead
return
;*********************************************************************
LeerPotApa
movlw b'00110110'
movwf TXDATA
call SSPRead
return
;*********************************************************************
LeerFP
movlw b'00110010'
movwf TXDATA
call SSPRead
return
;*********************************************************************
LeerIACoff
movlw b'00100000'
movwf TXDATA
call SSPRead
return
;*********************************************************************
LeerVACoff
movlw b'00100010'
movwf TXDATA
call SSPRead
return
;*********************************************************************

InitCS5463
movlw 0x40 ; escribo en el configuration register.
movwf TXDATA
movlw 0x00 ; PUEDE HABER PROBLEMA: **** PC[6:0] = 0000000 ****. Igain = 0 (x10)
movwf TXDATA0
movlw 0x00
movwf TXDATA1
movlw 0x01
movwf TXDATA2
call SSPWrite

  ;N=4000 cristal de 4,096MHz
movlw 0x4A ; escribo en el cycle count register
movwf TXDATA
movlw 0x00
movwf TXDATA0
movlw 0x0F ; 0FA0h = 4000d
movwf TXDATA1
movlw 0xA0
movwf TXDATA2
call SSPWrite

  ;Borrar todos los bits de STATUS
movlw 0x5E ; status register
movwf TXDATA
movlw 0x00
movwf TXDATA0
movlw 0x00
movwf TXDATA1
movlw 0x00
movwf TXDATA2
call SSPWrite

  ;Habilito HPFs
movlw 0x64 ; operational mode register
movwf TXDATA
movlw 0x00
movwf TXDATA0
movlw 0x00
movwf TXDATA1
movlw 0x61 ; Habilito HPFs. deteccion de freq de linea automatica
movwf TXDATA2
call SSPWrite
 
; QUITO OFFSET DE POTENCIA
; movlw 0x5C ; POFF
; movwf TXDATA
; movlw 0xFF
; movwf TXDATA0
; movlw 0xC9
; movwf TXDATA1
; movlw 0xE8
; movwf TXDATA2
; call SSPWrite     

;Conversion continua
movlw 0xE8 ; C3=1
movwf TXDATA
call SSPCmd
return

;***************************************************************************
; initialization routines
;***************************************************************************
; Commands the CS5463 to perform a reset cycle via the SPI code.
; After the CS5463 is resets, the serial port is resynchronized by sending SYNC bytes.
;***************************************************************************
; Inputs: none
; outputs: none

ResetCS5463
movlw b'10000000' ; comando de RESET POR SW, 0x80
movwf TXDATA ;
call SSPCmd ; send command to CS5463

;***************************************************************************
; Initialize the CS5460 Serial Port
; Write SYNC1 (0xFF) to the CS4560 up to 3 times followed by
; a SYNC0 (0xFE) to initialize the Serial Port

movlw SYNC1 ; SYNC1 byte (0xFF)
movwf TXDATA
movlw SYNC1 ; SYNC1 byte (0xFF)
movwf TXDATA0
movlw SYNC1 ; SYNC1 byte (0xFF)
movwf TXDATA1
movlw SYNC0 ; SYNC0 byte (0xFE)
movwf TXDATA2
call SSPWrite ; send sync bytes to CS5460

  return

;***************************************************************************
; Read data from the CS4560 through the SSP PORT *
;***************************************************************************
; Inputs: TXDATA (read command specifying which register to read)
; Outputs: RXDATA0, RXDATA1, RXDATA2 (received data buffer)

SSPRead
bcf CS ; CS4560 chip select pin7 low
bcf PIR1,SSPIF ; clear flag

movf TXDATA,W ; CS4560 register to read
movwf SSPBUF ; put it in SSPBUF the start read

btfss PIR1,SSPIF ; wait for SSP to be ready
goto $-1
movf SSPBUF,W ; al pedo!!
bcf PIR1,SSPIF ; clear flag

; send three dummy bytes
; in this case we send "SYNC1"s

movlw SYNC1 ; dummy byte 1
movwf SSPBUF
bcf PIR1,SSPIF
btfss PIR1,SSPIF
goto $-1
movf SSPBUF,W
movwf RXDATA0
bcf PIR1,SSPIF

movlw SYNC1 ; dummy byte 2
movwf SSPBUF
bcf PIR1,SSPIF
btfss PIR1,SSPIF
goto $-1
movf SSPBUF,W
movwf RXDATA1
bcf PIR1,SSPIF

movlw SYNC1 ; dummy byte 3
movwf SSPBUF
bcf PIR1,SSPIF
btfss PIR1,SSPIF ;00010100
goto $-1
movf SSPBUF,W
movwf RXDATA2 ; LSB
bcf PIR1,SSPIF

bsf CS ; CS4560 chip select pin back high

return


;***************************************************************************
; Write data to a CS4560 register *
; The commmand will be in TXDATA and the data will be in *
; TXDATA0 (MSB), TXDATA1, and TXDATA2 (LSB) *
;***************************************************************************
; Inputs: TXDATA, TXDATA1, TXDATA2, TXDATA3
; Outputs: none

SSPWrite

bcf CS ; set CS4560 chip select pin 7 low
bcf PIR1,SSPIF ; clear the flag
movf TXDATA,W ; get command (or register)

movwf SSPBUF ; put it in SSPBUF
btfss PIR1,SSPIF ; wait for SSP to be ready
goto $-1
movf SSPBUF,W ; dummy read, discard byte
bcf PIR1,SSPIF ; command byte sent, clear flag

movf TXDATA0,W ; get first data byte
movwf SSPBUF ; send data byte 0 (MSB)
btfss PIR1,SSPIF ; wait for SSP to be ready
goto $-1
movf SSPBUF,W ; dummy read, discard byte
bcf PIR1,SSPIF ; first data byte sent, clear flag

movf TXDATA1,W
movwf SSPBUF ; send data byte 1
btfss PIR1,SSPIF ; wait for SSP to be ready
goto $-1
movf SSPBUF,W
bcf PIR1,SSPIF ; second data byte sent, clear flag

movf TXDATA2,W
movwf SSPBUF ; send data byte 2 (LSB)
btfss PIR1,SSPIF ; wait for SSP to be ready
goto $-1
movf SSPBUF,W ; dummy read, discard byte
bcf PIR1,SSPIF ; third data byte sent, clear flag

;bsf CS
return

;***************************************************************************
; Write a 1 byte command to the CS4560 *
; The command will be in TXDATA *
;***************************************************************************
; Inputs: TXDATA
; Outputs: none

SSPCmd
bcf CS ; set CS4560 chip select pin 7 low

movf TXDATA,W ; get command
movwf SSPBUF ; send command
bcf PIR1,SSPIF ; clear interrupt flag
btfss PIR1,SSPIF ; loop waiting for command to be sent
goto $-1

movf SSPBUF,W ; command sent

bsf CS ; set CS4560 chip select pin back high

return

;***************************************************************************
cargoEEPROM:
bcf STATUS, RP0
bsf STATUS, RP1 ; voy al banco 2 para escribir en EEPROM

movf dirEEPROM, 0

movwf EEADR ; dirección donde voy a guardar el dato
movf VOLTAJE_MSB, 0 ; cargo RXDATA0 en w
; movf 0xAA, 0
movwf EEDAT ; cargo RXDATA0 en EEDAT
call escriboEEPROM

bcf STATUS, RP0
bsf STATUS, RP1

incf dirEEPROM, 1
movf dirEEPROM, 0

movwf EEADR ; dirección donde voy a guardar el dato
movf VOLTAJE_med, 0 ; cargo RXDATA1 en w
; movf 0xBB, 0
movwf EEDAT ; cargo RXDATA1 en EEDAT
call escriboEEPROM

bcf STATUS, RP0
bsf STATUS, RP1

incf dirEEPROM, 1
movf dirEEPROM, 0

movwf EEADR ; dirección donde voy a guardar el dato
movf VOLTAJE_LSB, 0 ; cargo RXDATA2 en w
; movf 0xCC, 0
movwf EEDAT ; cargo RXDATA0 en EEDAT

call escriboEEPROM
return

;***************************************************************************
escriboEEPROM:
bsf STATUS, RP0 ;bank 3
bsf STATUS, RP1 ;bank 3
BSF EECON1, WREN ; habilito escritura. EECON1 esta en el bank 3
BCF INTCON, GIE ; deshabilito interrupciones
BTFSC INTCON,GIE ; See AN576
GOTO $-2
MOVLW 0x55 ;
MOVWF EECON2 ; Escribo 55h
MOVLW 0xAA ;
MOVWF EECON2 ; Escribo AAh
bsf EECON1,WR ; Seteo bit WR para comenzar escritura
call verificoEscritura
return
;***************************************************************************
verificoEscritura:
btfsc EECON1,WR ; hasta que no haya terminado el tiempo de escritura
goto verificoEscritura ; no entro a la verificación

bcf STATUS, RP0
bsf STATUS, RP1
movf EEDAT, W ; cargo dato en W (pasado como parámetro al inicio)

bsf STATUS, RP0 ;bank 3
bsf STATUS, RP1 ;bank 3
bsf EECON1, RD ; leo dato

bcf STATUS, RP0
bsf STATUS, RP1 ;
subwf EEDAT, W     ; el valor escrito en W es igual al leído en EEDAT?
bsf STATUS, RP0 ;bank 3
bsf STATUS, RP1 ;bank 3
btfss STATUS, Z ; la diferencia es 0?
call errorEscritura ; NO, escribir error
return
;***************************************************************************
errorEscritura:
bcf STATUS, RP1
bcf STATUS, RP0
bsf PORTA, 2
;prendo y apago salida algún led indicando error de verificación de escritura y retomo al punto donde estaba
return

;********************CONFIGURACION DEL PUERTO SERIE**************************************
SetupSerial:
bsf STATUS, RP0
bcf STATUS, RP1

;-------------------------TXSTA: TRANSMIT STATUS AND CONTROL REGISTER---------------------------

;bit 7 CSRC: Clock Source Select bit
; Asynchronous mode:
; Don’t care
; Synchronous mode:
; 1 = Master mode (clock generated internally from BRG)
; 0 = Slave mode (clock from external source)

;bit 6 TX9: 9-bit Transmit Enable bit
; 1 = Selects 9-bit transmission
; 0 = Selects 8-bit transmission

;bit 5 TXEN: Transmit Enable bit(1)
; 1 = Transmit enabled
; 0 = Transmit disabled

;bit 4 SYNC: EUSART Mode Select bit
; 1 = Synchronous mode
; 0 = Asynchronous mode

;bit 3 SENDB: Send Break Character bit.
; Asynchronous mode:
; 1 = Send Sync Break on next transmission (cleared by hardware upon completion)
; 0 = Sync Break transmission completed
; Synchronous mode:
; Don’t care

;bit 2 BRGH: High Baud Rate Select bit
; Asynchronous mode:
; 1 = High speed
; 0 = Low speed
; Synchronous mode:
; Unused in this mode

;bit 1 TRMT: Transmit Shift Register Status bit
; 1 = TSR empty
; 0 = TSR full

;bit 0 TX9D: Ninth bit of Transmit Data
; Can be address/data bit or a parity bit.

;ME JODEN EL BIT 3 Y EL 1
; ERA movlw b'00100010'
movlw b'00100100' ; BRGH = 1 !!!
movwf TXSTA ;TXSTA: ver pagina 160

;------------------------------------------------------------------------------------

bcf STATUS, RP0
bcf STATUS, RP1

movlw b'10010110' ;habilita puerto serie y recepcion
movwf RCSTA

bsf STATUS, RP0
bcf STATUS, RP1

;---------------------------------BAUDCTL: BAUD RATE CONTROL REGISTER---------------------------------------

;bit 7 ABDOVF: Auto-Baud Detect Overflow bit
;Asynchronous mode:
;1 = Auto-baud timer overflowed
;0 = Auto-baud timer did not overflow
;Synchronous mode:
;Don’t care

;bit 6 RCIDL: Receive Idle Flag bit
;Asynchronous mode:
;1 = Receiver is Idle
;0 = Start bit has been received and the receiver is receiving
;Synchronous mode:
;Don’t care

;bit 5 Unimplemented: Read as ‘0’

;bit 4 SCKP: Synchronous Clock Polarity Select bit
;Asynchronous mode:
;1 = Transmit inverted data to the RB7/TX/CK pin
;0 = Transmit non-inverted data to the RB7/TX/CK pin
;Synchronous mode:
;1 = Data is clocked on rising edge of the clock
;0 = Data is clocked on falling edge of the clock

;bit 3 BRG16: 16-bit Baud Rate Generator bit
;1 = 16-bit Baud Rate Generator is used
;0 = 8-bit Baud Rate Generator is used. USAMOS ESTE

;bit 2 Unimplemented: Read as ‘0’

;bit 1 WUE: Wake-up Enable bit
;Asynchronous mode:
;1 = Receiver is waiting for a falling edge. No character will be received byte RCIF will be set. WUE will
;automatically clear after RCIF is set.
;0 = Receiver is operating normally
;Synchronous mode:
;D;on’t care

;bit 0 ABDEN: Auto-Baud Detect Enable bit
;Asynchronous mode:
;1 = Auto-Baud Detect mode is enabled (clears when auto-baud is complete)
;0 = Auto-Baud Detect mode is disabled
;Synchronous mode:
;Don’t care

movlw b'00000000'   ;BRG16 = 0: 8-bit Baud Rate Generator is used. PROBAR EL MSB con 1
;movlw b'00001010'   ; ERA
movwf BAUDCTL

;-------------------------------------------------------------------------------------------------------
movlw SPBRG_VAL ;cargo un baud rate de 9600 para un XT de 4.096Mhz. Justificado arriba
movwf SPBRG

bcf STATUS, RP0
return
;***************************************************************************
TransmitSerial:
bsf STATUS, RP0
bcf STATUS, RP1
bsf TXSTA, TXEN

bcf STATUS, RP0
bcf STATUS, RP1
loopTX
btfss PIR1,TXIF ;check if transmitter busy
goto loopTX ;return if transmitter busy
movf 0xAA, W
;movf VOLTAJE_med, W ;get the data to be transmitted VOLTAJE_med
movwf TXREG ;and transmit
return
;***************************************************************************
Envia:
  ; movlw VOLTAJE_LSB
; movlw b'10101010'
movwf TXREG ; envia Dato.-
bsf STATUS,RP0 ; Banco 1
esperar
btfss TXSTA,TRMT   ; chequea si esta listo
    goto esperar ; Esperamos  a que se desocupe.-
    bcf STATUS,RP0 ; Banco 0
  return

;***************************************************************************
mostrarDireccion
movlw 0x0D
call Envia
movlw 0x0D
call Envia
movlw 0x44
call Envia
movlw 0x49
call Envia
movlw 0x52
call Envia
movlw 0x0D
call Envia
movlw 0x0D
call Envia
return
;***************************************************************************
mostrarCorriente
movlw 0x0D
call Envia
movlw 0x0D
call Envia
movlw 0x43
call Envia
movlw 0x4F
call Envia
movlw 0x52
call Envia
movlw 0x52
call Envia
movlw 0x49
call Envia
movlw 0x45
call Envia
movlw 0x4E
call Envia
movlw 0x54
call Envia
movlw 0x45
call Envia
movlw 0x0D
call Envia
movlw 0x0D
call Envia
return
;***************************************************************************
mostrarPotenciaActiva
movlw 0x0D
call Envia
movlw 0x0D
call Envia
movlw 0x50
call Envia
movlw 0x4F
call Envia
movlw 0x54
call Envia
movlw 0x45
call Envia
movlw 0x4E
call Envia
movlw 0x43
call Envia
movlw 0x49
call Envia
movlw 0x41
call Envia
movlw 0x0D
call Envia
movlw 0x0D
call Envia
return
;***************************************************************************
mostrarFP
movlw 0x0D
call Envia
movlw 0x0D
call Envia
movlw 0x46
call Envia
movlw 0x50
call Envia
movlw 0x0D
call Envia
movlw 0x0D
call Envia
return
;***************************************************************************
ORG 0x2100 ; data EEPROM location
DE 1,2,3,4 ; define first four EEPROM locations as 1, 2, 3, and 4

END                     ; directive 'end of program'

Hardware:







Tener en cuenta que la impedancia de entrada del canal de corriente no es muy grande (vale 20KOhm), por lo tanto las señales caen en un 0.8 aproximadamente. Es por ello que el valor de Ign vale 0x4DE01F. Esto levanta la señal de corriente en 1.2 veces aproximadamente, arrojando resultados perfectos.





 

anything