int EEPROM_i2c_readByte(uint8_t slaveAddr, uint16_t regAddr, uint8_t * retByte) {
I2C_AcknowledgeConfig(I2C2, ENABLE);
I2C_GenerateSTART(I2C2, ENABLE);
int timeout = I2C_TIMEOUT;
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT)) {
if((timeout--) == 0) {
return -1;
}
delay_us(1);
}
I2C_Send7bitAddress(I2C2, slaveAddr, I2C_Direction_Transmitter);
timeout = I2C_TIMEOUT;
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) {
if((timeout--) == 0) {
return -2;
}
delay_us(1);
}
// Register Address 15-8
I2C_SendData(I2C2, (uint8_t)((regAddr >> 8) & 0x00FF));
timeout = I2C_TIMEOUT;
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) {
if((timeout--) == 0) {
return -3;
}
delay_us(1);
}
// Register Address 7-0
I2C_SendData(I2C2, (uint8_t)(regAddr & 0x00FF));
timeout = I2C_TIMEOUT;
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) {
if((timeout--) == 0) {
return -4;
}
delay_us(1);
}
I2C_GenerateSTART(I2C2, ENABLE);
timeout = I2C_TIMEOUT;
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT)) {
if((timeout--) == 0) {
return -5;
}
delay_us(1);
}
I2C_Send7bitAddress(I2C2, slaveAddr, I2C_Direction_Receiver);
timeout = I2C_TIMEOUT;
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)) {
if((timeout--) == 0) {
return -6;
}
delay_us(1);
}
timeout = I2C_TIMEOUT;
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_RECEIVED)) {
if((timeout--) == 0) {
return -7;
}
delay_us(1);
}
*retByte = I2C_ReceiveData(I2C2);
I2C_AcknowledgeConfig(I2C2, DISABLE);
I2C_GenerateSTOP(I2C2, ENABLE);
timeout = I2C_TIMEOUT;
while(I2C_GetFlagStatus(I2C2, I2C_FLAG_BUSY)) {
if((timeout--) == 0) {
return -8;
}
delay_us(1);
}
delay_us(100);
return 0;
}
void delay_us(int us)
{
volatile u32 i;
for(i = us; i > 0; i--) // 72clock = 1us
{
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop");
}
}
// Use example
uint8_t addr = 0xA0; // Device address
uint8_t value = 0;
int targetaddr = 0x00;
EEPROM_i2c_readByte(addr, targetaddr, &value);