#include <msp430x54x.h>
#define SDA_1 P3OUT |= BIT7 //SDA = 1
#define SDA_0 P3OUT &=~ BIT7 //SDA = 0
#define SCL_1 P5OUT |= BIT4 //SCL = 1
#define SCL_0 P5OUT &=~ BIT4 //SCL = 0
#define DIR_IN P3DIR &=~ BIT7 //I/O口为输入
#define DIR_OUT P3DIR |= BIT7 //I/0口为输出
#define SDA_IN (P3IN & 0x80) //Read SDA
void Delay();
void start_I2C();
void stop_I2C();
void Ack();
void NAck();
void CheckAck();
void SendByte(unsigned char c);
unsigned char ReadByte();
unsigned char read_PCF8563(unsigned char slave_addr,unsigned char write_addr);
void write_PCF8563(unsigned char slave_addr,unsigned char write_addr,unsigned char writedata);
void main()
{ WDTCTL = WDTPW+WDTHOLD; //关闭看门狗定时器
P3DIR |= BIT7;
P5DIR |= BIT4;
write_PCF8563(0xA2,0x02,0x59);
read_PCF8563(0xA2,0x02);
}
void Delay()
{_NOP();}
void start_I2C(void) //I2C的开始条件
{ SDA_1; //发送起始条件的数据信号
Delay();
SCL_1;
Delay();
SDA_0; //发送起始信号
Delay();
SCL_0; //钳住I2C总线,准备发送或接收数据
Delay();
}
void stop_I2C(void) //I2C的停止条件
{SDA_0; //发送结束条件的数据信号
Delay();
SCL_1;
Delay();
SDA_1; //发送I2C总线结束信号
Delay();
}
void SendByte(unsigned char c)
{int BitCnt;
for(BitCnt=0;BitCnt<8;BitCnt++)
{ if((c<<BitCnt)&0x80)
SDA_1;
else SDA_0;
Delay();
SCL_1; //置时钟线为高,通知从机开始接收数据位
Delay();
SCL_0;
}
Delay();
CheckAck();
}
unsigned char ReadByte()
{ unsigned char read_data=0;
unsigned char BitCnt;
DIR_IN; //置数据线为输入方式
for(BitCnt=0;BitCnt<8;BitCnt++)
{ Delay();
SCL_0; //置时钟线为低,准备接收数据位
Delay();
SCL_1; //置时钟线为高使数据线上数据有效
Delay();
if(SDA_IN==0x80)
read_data=read_data+1; //读数据位,接收的数据位放入read_data中
read_data=read_data<<1;
Delay();
}
SCL_0;
Delay();
DIR_OUT;
return(read_data);
}
void CheckAck()
{unsigned char count=20;
DIR_IN;
SDA_1; //8位发送完后释放数据线,准备接收应答位
Delay();
SCL_1;
Delay();
while(SDA_IN)
{count--;
if(!count)
stop_I2C();
}
SCL_0;
Delay();
DIR_OUT;
}
void Ack()
{ SDA_0; //在此发出应答信号
Delay();
SCL_1;
Delay();
SCL_0; //清时钟线,钳住I2C总线以便继续接收
Delay();
}
void NAck()
{SDA_1;
Delay();
SCL_1;
Delay();
SCL_0; //清时钟线,钳住I2C总线以便继续接收
Delay();
}
void write_PCF8563(unsigned char slave_addr,unsigned char write_addr,unsigned char writedata)
{ start_I2C(); //启动总线
SendByte(slave_addr); //发送器件地址
SendByte(write_addr); //发送器件子地址
SendByte(writedata); //发送数据
stop_I2C(); //结束总线
}
unsigned char read_PCF8563(unsigned char slave_addr,unsigned char write_addr)
{ unsigned char Y;
start_I2C(); //启动总线
SendByte(slave_addr); //发送器件地址
SendByte(write_addr); //发送器件子地址
start_I2C(); //重新启动总线
SendByte(slave_addr+1);
Y=ReadByte();
NAck(); //发送非应位
stop_I2C(); //结束总线
return(Y);
}
用5438给PCF8563读写数据,试了一下,每次都是检测不到从机应答(即运行到CheckAck后便停止),想让大家给看看程序是不是有问题,如果程序没问题的话,那是不是PCF8563坏了?
[
本帖最后由 zzbaizhi 于 2012-2-21 16:40 编辑 ]
此帖出自
小平头技术问答
如果没有示波器,建议在网上买一个最简单的逻辑分析仪,就几十块钱,能够帮你很多忙。
一周热门 更多>