直接参考了网上的程序
主机发送数据,从机接受数据。
主机发送了地址,从机没返回ACK。现象主机卡”while(!(I2C_SR1&0x02))“。从机进不了中断,初始化设置了ACK,可是查看寄存器地址没写入,大侠们看看,什么问题。
主机程序
void I2C_init(void)
{
I2C_FREQR = 0x0a;
I2C_CCRH = 0x00;
I2C_CCRL = 0x32;
I2C_TRISER = 0x04;
I2C_CR2 |=0x04;
I2C_CR1 |=0x01;
}
void zhu_w(uchar x )
{
uchar temp;
while(I2C_SR3 & 0x02); //总线空闲
I2C_CR2 |= 0x01; //产生起始位
while(!(I2C_SR1 & 0x01)); //起始位发送完成
I2C_DR = 0x42; //从机地址
while(!(I2C_SR1&0x02));//地址发送完成
temp = I2C_SR1;
temp = I2C_SR3;
I2C_DR = 0x00;
while(!(I2C_SR1 & 0x84));
I2C_DR = x;
while(!(I2C_SR1 & 0x84));
I2C_CR2 |= 0x02;
}
从机程序
@far @interrupt void I2C_Handler(void)
{
uchar state1,state2,state3;
//地址匹配 地址位1
if((I2C_SR1&0x02)==0x02)
{
state1 = I2C_SR1;
state3 = I2C_SR3;
I2C_CR2 |= 0x04;
}
//接收到数据
if( (I2C_SR1& 0x40) ==0x40)
{
I2C_CR2 |= 0x04;
con = I2C_DR;
//SetOutput(temp1);
}
if((I2C_SR2 & 0x04) == 0x04)
I2C_SR2 &= ~0x04; //应答失败,清除该位
if((I2C_SR1 & 0x10) == 0x10)
{
state1 = I2C_SR1;
I2C_CR2 |= 0x02;
}
}
void I2C_init(void)
{
I2C_FREQR = 0x0a;
I2C_CCRH = 0x00;
I2C_CCRL = 0x32;
I2C_TRISER = 0x04;
I2C_OARH=0x40;
I2C_OARL=0x42;
I2C_ITR |= 0x06;//中断使能
I2C_CR2 =0x04; //应答设置
I2C_CR1 |=0x01; //使能I2C模块
}
|