int hal_i2c_writeByte(uint8_t slaveAddr, uint16_t regAddr, uint8_t byte) {
I2C_AcknowledgeConfig(I2C2, ENABLE);
I2C_GenerateSTART(I2C2, ENABLE);
int timeout = I2C_TIMEOUT;
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT)) {
if((timeout--) == 0) {
// Error
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) {
// Error
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) {
// Error
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) {
// Error
return -4;
}
delay_us(1);
}
I2C_SendData(I2C2, byte);
timeout = I2C_TIMEOUT;
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) {
if((timeout--) == 0) {
// Error
return -5;
}
delay_us(1);
}
I2C_GenerateSTOP(I2C2, ENABLE);
timeout = I2C_TIMEOUT;
while(I2C_GetFlagStatus(I2C2, I2C_FLAG_BUSY)) {
if((timeout--) == 0) {
// Error
return -6;
}
delay_us(1);
}
delay_us(100);
return 0;
}