我是PIC的新手。我知道这个论坛上有很多关于I2C的帖子,我尝试了所有给出的方法,但仍然无法解决我的问题。我正在使用PIC16F1516和外部EEPROM CAT24C04TDI来存储一些数据。我使用了4K7欧姆电阻进行上拉,我的代码是:
void I2CWrite(void);
void WaitMSSP(void);
void I2CRead(void);
void i2c_init(void);
//void _delay_ms(unsigned int);
void main()
{
_delay_ms(100); // Give delay for power up
i2c_init(); // Initialize I2C
_delay_ms(20);
I2CWrite(); // Sends the data to I2C EEPROM
_delay_ms(50);
while(1)
{
I2CRead(); // Read back the data?s
TXREG='n';
while(TXIF==0);
TXREG='r';
_delay_ms(500);
}
}
void I2CWrite()
{
SSPCON2bits.SEN=1;
WaitMSSP(); // wait for the operation to be finished
SSPBUF=0xa0;//Send Slave address write command
WaitMSSP();
SSPBUF=0x00; // Send the starting address to write
WaitMSSP();
SSPBUF=0x34; // rough data to be written
WaitMSSP();
}
PEN=1; // Send stop bit
WaitMSSP();
}
void I2CRead()
{
SEN=1; //Send start bit
WaitMSSP(); //wait for the operation to be finished
SSPBUF=0xa0;//Send Slave address write command
WaitMSSP();
SSPBUF=0x00; // Send the starting address to write
WaitMSSP();
RSEN=1; // Send re-start bit
WaitMSSP();
SSPBUF=0xa1; // Slave address read command
WaitMSSP();
RCEN=1; // Enable receive
WaitMSSP();
ACKDT=1; // Acknowledge data 1: NACK, 0: ACK
ACKEN=1; // Enable ACK to send
PEN=1; // Stop condition
WaitMSSP();
putch(SSPBUF); // Send the received data to PC
_delay_ms(30);
}
PEN=1;
WaitMSSP();
}
void WaitMSSP()
{
while(!SSPIF); // while SSPIF=0 stay here else exit the loop
SSPIF=0; // operation completed clear the flag
}
void i2c_init()
{
TRISCbits.TRISC3=1; // Set up I2C lines by setting as input
TRISCbits.TRISC4=1;
SSPCON1 = 0b00101000;
// SSPADD=(FOSC / (4 * I2C_FREQ)) - 1; //clock 100khz
SSPADD = 0x18 ; //clock 100khz
SSPSTAT=80; // Slew rate control disabled
PIR1bits.SSPIF = 0; // Clear MSSP interrupt request flag
PIE1bits.SSPIE = 1; // Enable MSSP interrupt enable bit
}
当我将其连接到示波器时,发送SEN = 1后,SDA和SCL端口什么也不会发生。请帮助我解决这个问题。我很长时间以来一直坚持这样做。
SSPIF
不是寄存器:数据表显示在寄存器PIR1
中的位置为3,因此而不是行
while(!SSPIF); // while SSPIF=0 stay here else exit the loop
SSPIF = 0; // operation completed clear the flag
这意味着您应该用
进行测试和清除while ((PIR1 & 0x08) == 0);
PIR1 = 0;
清除状态的汇编指令是
BCF PIR1,SSPIF ;I2C done, clear flag
以及该论坛中的更多详细信息还请阅读数据表以获取更多信息。