在读的时候不能发送重复发送起始信号,SI位不能清零:
代码如下,起始信号:
UNS_8 I2C0_Start()//void
{
LPC_I2C0->CONCLR = 0x38;//1<<3|1<<4|1<<5
LPC_I2C0->CONSET |= 0x20;
while (!(LPC_I2C0->CONSET & 0x08));
LPC_I2C0->CONCLR = 0x20;//1<< 5
return (LPC_I2C0->STAT & 0xF8);
}
读取数据函数:
UNS_8 I2C0_ReadByte(UNS_8 t_slave_addr,
UNS_8 t_opera
tion_addr,
UNS_8 *p_read_data,
UNS_8 t_data_num)
{
UNS_8 t_status;
UNS_8 t_count;
t_status = I2C0_Start();
while(t_status != 0x08);
t_status = I2C0_SendByte(t_slave_addr);
while(t_status != 0x18);
t_status = I2C0_SendByte(t_operation_addr);
while(t_status != 0x28);
t_status = I2C0_Start();
while(t_status != 0x10);
t_status = I2C0_SendByte(t_slave_addr | 0x01);
while(t_status != 0x40);
for(t_count = 0; t_count < t_data_num; t_count++)
{
if(t_count)
{
t_status = I2C0_GetByte(p_read_data,1);
while(t_status != 0x50);
}
else
{
t_status = I2C0_GetByte(p_read_data,0);
while(t_status != 0x58);
}
p_read_data++;
}
I2C0_Stop();
/*返回错误号*/
return 1;
}
从机地址是0XA0,操作地址是0X00。
UNS_8 I2C0_SendByte(UNS_8 t_data)
{
LPC_I2C0->DAT = t_data;
/*加载数据后需清除SI位*/
LPC_I2C0->CONSET = 0x04;
LPC_I2C0->CONCLR = 0x08;//1<<3
/*收到应答*/
while(!(LPC_I2C0->CONSET & 0x08));
return (LPC_I2C0->STAT & 0xF8);
}
一周热门 更多>