Amigos: dejo acá la 'librería' que me hice para usar el MCP6S21. Funciona bien hasta el momento, también puse ahí la configuración del módulo SPI del dsPIC30f401 como máster, está la opción de ponerlo como slave, pero no lo he probado.
Si hay algo que pueda mejorarse, estoy muy interesado en saberlo.
Saludos a todos
//configura y usa modulo SPI
//funciones:
//- spi_init_slave(void): configura el módulo como esclavo, sin SS.
//- spi_init_master(void): configura el módulo como maestro.
//gain_pga1() setea ganancia del MCP6S21
#include "p30f4011.h"
#define CS1 LATFbits.LATF0
extern int *dptr;
void spi_init_master(void)
{
CS1=1; //para no escribir sobre el PGA
SPI1STATbits.SPIEN=0; //deshabilita el módulo SPI
IFS0bits.SPI1IF=0; //limpia la bandera de interupción
IEC0bits.SPI1IE=0; //deshabilita la interrupción del módulo
IPC2bits.SPI1IP=0x2; //prioridad de interrupcion Nº2 (ADC tiene 4)
SPI1CONbits.MSTEN=1; //como maestro
SPI1CONbits.CKE=1;
SPI1CONbits.SPRE=0b000; //prescaler secundario 1
SPI1CONbits.PPRE=0b00; //prescaler primario 1
SPI1STATbits.SPIROV=0; //No receive overflow
SPI1STATbits.SPIEN=1; //habilita el módulo SPI
}
void spi_init_slave(void)/*sin SS habilitado*/
{
SPI1BUF=0; //limpia el buffer del módulo
IFS0bits.SPI1IF=0; //limpia la bandera de interupción
IEC0bits.SPI1IE=1; //habilita la interrupción del módulo
IPC2bits.SPI1IP=0x3; //prioridad de interrupcion Nº3 (ADC tiene 4)
SPI1CONbits.MSTEN=0; //como slave
SPI1CONbits.SMP=0; //debe sere deshabilitado en modo Slave
SPI1STATbits.SPIROV=0; //No receive overflow
SPI1STATbits.SPIEN=0; //habilita el módulo SPI
}
int spi_out(int send)
{
SPI1BUF=send;
while(!SPI1STATbits.SPIRBF){}
return SPI1BUF;
}
void gain_pga1(int gain)
{
switch(gain)
{
case 0:
spi_out(0b00100000);
spi_out(0x0); //dummy data
break;
case 1:
spi_out(0b01000000);
spi_out(0b00000000);
break;
case 2:
spi_out(0b01000000);
spi_out(0b00000001);
break;
case 4:
spi_out(0b00000010);
spi_out(0b00000010);
break;
case 5:
spi_out(0b01000000);
spi_out(0b00000011);
break;
case 8:
spi_out(0b01000000);
spi_out(0b00000100);
RE8=1;delay_ms(5);RE8=0;
break;
case 10:
spi_out(0b01000000);
spi_out(0b00000101);
RE8=1;RE8=0;
break;
case 16:
spi_out(0b01000000);
spi_out(0b00000110);
break;
case 32:
spi_out(0b01000000);
spi_out(0b00000111);
break;
}
CS1=1;
}
http://vtasco.googlepages.com/spi.c (para bajarla)