本帖最后由 sea1105 于 2014-2-21 12:46 编辑
STC单片机SPI查询的方式,CS5463驱动程序如下。试验中发现读取CS5463寄存器的默认值正确,但是CS5463初始化程序里的寄存器值却好像无法写入。用示波器检测SPI口波形无论读取都正常,很费解,请高手指点指点。
sbit CS5463_CS = P1^4;
sbit CS5463_RESET = P3^5;
#define Write_Reg 0x40
unsigned char SPI_swap(unsigned char dat)
{
CS5463_CS = 0; //pull low slave SS
SPDAT = dat ; //trigger SPI send
while(!(SPSTAT & SPIF)); //wait send complete
SPSTAT = SPIF | WCOL; //clear SPI status
CS5463_CS = 1; //push high slave SS
return SPDAT;
}
void CS5463_Write(unsigned char *dat,unsigned char num)
{
unsigned char i;
for(i = 0;i < num;i++)
{
SPI_swap(*dat++);
}
}
void CS5463_Read(unsigned char *dat,unsigned char reg)
{
unsigned char i;
SPI_swap(reg << 1);
for(i = 0;i < 3;i++)
{
*dat++= SPI_swap(0xFE);
}
}
void Clear_DRDY(void)
{
unsigned char buf[4];
buf[0] = (Config << 1) | Write_Reg;
buf[1] = 0xFF;
buf[2] = 0xFF;
buf[3] = 0xFF;
CS5463_Write(buf, 4);
}
void CS5463_Init(void)
{
unsigned char buf[4];
CS5463_RESET = 0; //复位CS5460
Delay_nms(5); //延迟5ms
CS5463_RESET = 1;
Delay_nms(5); //延迟5ms
//发送同步字节
buf[0] = 0xFF;
buf[1] = 0xFF;
buf[2] = 0xFF;
buf[3] = 0xFE;
CS5463_Write(buf,4);
//写配置寄存器
buf[0] = (Config << 1) | Write_Reg;
buf[1] = 0x00; //电流增益设为10,相位偏移为默认值
buf[2] = 0x00;
buf[3] = 0x01; //DCLK = MCLK / 1
CS5463_Write(buf,4);
//写控制寄存器,缺省值
buf[0] = (Ctrl << 1) | Write_Reg;
buf[1] = 0x00;
buf[2] = 0x00;
buf[3] = 0x00;
CS5463_Write(buf,4);
//写周期计数寄存器N=4000
buf[0] = (CycleCount << 1) | Write_Reg;
buf[1] = 0x00;
buf[2] = 0x0F;
buf[3] = 0xA0;
CS5463_Write(buf,4);
//写中断屏蔽寄存器
buf[0] = (Mask << 1) | Write_Reg;
buf[1] = 0x80; //DRDY中断允许
buf[2] = 0x00;
buf[3] = 0x00;
CS5463_Write(buf,4);
//写能量-脉冲速率寄存器
buf[0] = (PulseRate << 1) | Write_Reg;
buf[1] = PulseConst >> 16;
buf[2] = PulseConst >> 8;
buf[3] = PulseConst;
CS5463_Write(buf,4);
//写模式寄存器
buf[0] = (Mode << 1) | Write_Reg;
buf[1] = 0x00;
buf[2] = 0x00; //E2:Energy Sign
buf[3] = 0x61; //电压电流高通滤波器开启,IIR默认开启,E3:Reactive Power,AFC(频率测量) 开启
CS5463_Write(buf,4);
//写电压增益校准寄存器
// buf[0] = (Vgn << 1) | Write_Reg;
// buf[1] = 0x;
// buf[2] = 0x;
// buf[3] = 0x;
// CS5463_Write(buf,4);
//写电压直流偏置校准寄存器
// buf[0] = (VDCoff << 1) | Write_Reg;
// buf[1] = 0x;
// buf[2] = 0x;
// buf[3] = 0x;
// CS5463_Write(buf,4);
//写电流增益校准寄存器
// buf[0] = (Ign << 1) | Write_Reg;
// buf[1] = 0x;
// buf[2] = 0x;
// buf[3] = 0x;
// CS5463_Write(buf,4);
//写电流直流偏置校准寄存器
// buf[0] = (IDCoff << 1) | Write_Reg;
// buf[1] = 0x;
// buf[2] = 0x;
// buf[3] = 0x;
// CS5463_Write(buf,4);
//写电压交流偏置校准寄存器
// buf[0] = (VACoff << 1) | Write_Reg;
// buf[1] = 0x;
// buf[2] = 0x;
// buf[3] = 0x;
// CS5463_Write( buf, 4 );
//写电流交流偏置校准寄存器
// buf[0] = (IACoff << 1) | Write_Reg;
// buf[1] = 0x;
// buf[2] = 0x;
// buf[3] = 0x;
// CS5463_Write(buf, 4 );
//清状态寄存器
buf[0] = (Status << 1) | Write_Reg;
buf[1] = 0xFF;
buf[2] = 0xFF;
buf[3] = 0xFF;
CS5463_Write(buf,4);
//启动转换
buf[0] = 0xE8;
CS5463_Write(buf,1);
}
|