STM8S103的板子上,有一个默认自带的AT24C02芯片,I2C读写,程序可以正常工作。
但是当飞线接另一个芯片时,却不能正常通讯,总是死在等待slaveAddress的应答上,I2C通信失败。
请教一下,有人遇到类似问题,如何解决的??
下面是代码:
void Delayms(unsigned int ms)
{
unsigned int x , y;
for(x = ms; x > 0; x--) /* ͨ¹ýÒ»¶¨ÖÜÆÚÑ»·½øÐÐÑÓʱ*/
for(y = 3000 ; y > 0 ; y--);
}
void IIC_Init()
{
PB_DDR_bit.DDR4 = 1;
PB_DDR_bit.DDR5 = 1;
PB_ODR_bit.ODR4 = 1;
PB_ODR_bit.ODR5 = 1;
PB_CR2_bit.C24 = 1;
PB_CR2_bit.C25 = 1;
I2C_CR2_bit.SWRST = 1; //I2C1->CR1 |= 1 << 15;
asm("nop");
asm("nop");
asm("nop");
asm("nop");
I2C_CR2_bit.SWRST = 0;
//I2C1->CR2 &= ~I2C_CR2_FREQ; //
I2C_FREQR_bit.FREQ = 16; //Freq = 36M
I2C_CCRH_bit.F_S = 1;
I2C_CCRH_bit.DUTY = 0;
I2C_CCRL = 40; //200KHZ I2CFreq = PCLK1 / CCR / DUTY[λ] = 16MHZ / 40 / 2 = 200KHZ
I2C_TRISER_bit.TRISE = 16 + 1;
// I2C1->CR1 &= ~I2C_CR1_SMBUS;
I2C_CR1_bit.ENGC = 1;
I2C_CR1_bit.PE = 1;
}
void IIC_Write(unsigned char subaddr , unsigned char Byte_addr , unsigned char *buffer , unsigned short num)
{
unsigned char i2csr1;
//while(I2C1->SR2 & I2C_SR2_BUSY);
I2C_CR2_bit.START = 1;
while(I2C_SR1_bit.SB == 0);
i2csr1 = I2C_SR1; //SR1.AF
I2C_DR = (subaddr);
while(I2C_SR1_bit.ADDR == 0);
i2csr1 = I2C_SR1;
i2csr1 = I2C_SR3;
I2C_DR = Byte_addr;
while(I2C_SR1_bit.BTF == 0);
i2csr1 = I2C_SR1;
while(num > 0)
{
I2C_DR = *buffer;
while(I2C_SR1_bit.BTF == 0);
i2csr1 = I2C_SR1;
buffer++;
num--;
}
I2C_CR2_bit.STOP = 1;
}
void IIC_Read(unsigned char subaddr , unsigned char Byte_addr , unsigned char *buffer , unsigned short num)
{
unsigned char i2csr1;
I2C_CR2_bit.ACK = 1;
I2C_CR2_bit.START = 1;
while(I2C_SR1_bit.SB == 0);
i2csr1 = I2C_SR1;
I2C_DR = subaddr;
while(I2C_SR1_bit.ADDR == 0);
i2csr1 = I2C_SR1;
i2csr1 = I2C_SR3;
I2C_DR = Byte_addr;
while(I2C_SR1_bit.BTF == 0);
i2csr1 = I2C_SR1;
I2C_CR2_bit.START = 1;//I2C1->CR1 |= I2C_CR1_START;
while(I2C_SR1_bit.SB == 0);
i2csr1 = I2C_SR1;//SR1.AF??
I2C_DR = (char)(subaddr | 0x01);
while(I2C_SR1_bit.ADDR == 0);
i2csr1 = I2C_SR1;
i2csr1 = I2C_SR3;
while(num)
{
if(num == 1)
{
I2C_CR2_bit.ACK = 0;
I2C_CR2_bit.STOP = 1;
}
while(I2C_SR1_bit.RXNE == 0);
i2csr1 = I2C_SR1;
*buffer = I2C_DR;
buffer++;
num--;
}
} |