AnsweredAssumed Answered

HAL I2C Slave

Question asked by chuev.vladimir on Apr 24, 2018
Latest reply on Apr 28, 2018 by Frank CA

I'm trying to make I2C Slave using examples from Cube.

 

The wizard can write the register, but when reading the HAL_I2C_ListenCpltCallback  is called only once.

 

Can someone share their working code with me?  I don't understand how this should work.

 

uint8_t i2cSlavDirection;
uint8_t i2cSlaveTransmitBuffer;
uint8_t i2cSlaveReceiveBuffer[2];

 


// Never called
void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *i2cHandle) {
    _Error_Handler(__FILE__, __LINE__);
}

 

// Never called
void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *i2cHandle) { }

 

// Never called
void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *i2cHandle) { }

 

 

 

void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *i2cHandle) {
    HAL_GPIO_TogglePin(GPIOB, LED_GREEN_Pin);

 

    switch (i2cSlavDirection) {
        case I2C_DIRECTION_TRANSMIT: { // master write
            // ... reg write ...
        }
        break;
        case I2C_DIRECTION_RECEIVE: { // master read
            // ... get reg value and write to i2cSlaveTransmitBuffer ...

 

            if(HAL_I2C_Slave_Sequential_Transmit_IT(i2cHandle, (uint8_t*)&i2cSlaveTransmitBuffer, 1, I2C_FIRST_AND_LAST_FRAME) != HAL_OK){
                _Error_Handler(__FILE__, __LINE__);
            }
        }
        break;
    }

 

    // Restarting
    if(HAL_I2C_EnableListen_IT(i2cHandle) != HAL_OK){
        _Error_Handler(__FILE__, __LINE__);
    }
}

 

 

 

void HAL_I2C_AddrCallback(I2C_HandleTypeDef *i2cHandle, uint8_t transferDirection, uint16_t addrMatchCode) {
    i2cSlave.transferDirection = transferDirection;

 

    // 2 - master write, 1 - master read
    uint8_t receiveSize = transferDirection == I2C_DIRECTION_TRANSMIT ? 2 : 1;
    if(HAL_I2C_Slave_Sequential_Receive_IT(i2cHandle, (uint8_t*)i2cSlaveReceiveBuffer, receiveSize, I2C_FIRST_FRAME) != HAL_OK){
        _Error_Handler(__FILE__, __LINE__);
    }
}

 

 

 

void StartDefaultTask(void const * argument) {
    if(HAL_I2C_EnableListen_IT(&hi2c1) != HAL_OK) {
        _Error_Handler(__FILE__, __LINE__);
    }

    while (1);
}

Outcomes