本帖最后由 mrjeep 于 2013-8-13 08:32 编辑
PIC24FJ256GB106驱动ADXL346加速度计,IIC通信,首先进行通信测试,加速度计的设备地址为0x00,内容为oxe6(只读),若读取的不是0xe6,则通信错误。现在的问题是IIC能写数据到ADXL346,但是读取的时候始终接受不到数据,I2C1RCV值为空,很是诡异!附上相关的源代码。在DEBUG模式下调试,运行到while (I2C1STATbits.RBF == FALSE) {}处就出不来了,此时I2CICON很诡异的变成0XD000, I2C1STAT为0x0400。datasheet里是说当I2C1RSR(不可访问)接收到一个完整字节时,就将数据传送至I2C1RCV,同时置RBF为1,显然现在没有收到一个字节的数据。求高人指点!
#define SET 1
#define TRUE 1
#define FALSE 0
#define ADXL346_DEVID 0x00
I2C1BRG = 9; /* IIC speed is 400KHz, Fcy = 4MHz. */
I2C1CON = 0x8000; /* enable IIC, SDA1 and SCL1 managed by MCU */
I2C1CONbits.SEN = SET; /* send start signal */
while (I2C1CONbits.SEN == TRUE) /* wait SEN to be '0' */
{
}
I2C1TRN = 0XA6; /* send slave device's address; R/W = 0. */
while(I2C1STATbits.TRSTAT == TRUE) /* wait TRSTAT to be '0' */
{
}
if (I2C1STATbits.ACKSTAT == TRUE) /* error occured */
{
I2C1CONbits.PEN = SET; /* stop signal */
while (I2C1CONbits.PEN == TRUE) /* wait PEN to be '0' */
{
}
}
else
{
I2C1TRN = ADXL346_DEVID; /* slave device */
while(I2C1STATbits.TRSTAT == TRUE) /* wait TRSTAT to be '0' */
{
}
if (I2C1STATbits.ACKSTAT == TRUE) /* error occured */
{
I2C1CONbits.PEN = SET; /* stop signal */
while (I2C1CONbits.PEN == TRUE) /* wait PEN to be '0' */
{
}
}
else
{
I2C1CONbits.RSEN = SET; /* IIC restart */
while(I2C1CONbits.RSEN == TRUE) /* wait RSEN to be '0' */
{
}
I2C1TRN = 0XA7; /* R/W = 1, read*/
while(I2C1STATbits.TRSTAT == TRUE) /* wait TRSTAT to be '0' */
{
}
if (I2C1STATbits.ACKSTAT == TRUE) /* error occured */
{
I2C1CONbits.PEN = SET; /* stop signal */
while (I2C1CONbits.PEN == TRUE) /* wait PEN to be '0' */
{
}
}
else
{
I2C1CONbits.RCEN = SET; /* enable receiving */
while (I2C1STATbits.RBF == FALSE) /* wait RBF to be '1' */
{
}
receive_buf = I2C1RCV; /* read I2C1RCV */
I2C1CONbits.ACKDT = SET; /* NACK */
I2C1CONbits.ACKEN = SET; /* ack bit */
while (I2C1CONbits.ACKEN == TRUE)
{
}
I2C1CONbits.PEN = SET; /* stop signal */
while (I2C1CONbits.PEN == TRUE)
{
}
}
}
}
|