开启中断,接收到数据时会调用回调函数
要发送接收都有了,还有非阻塞的,然后通过回调函数来实现功能,真是非常方便的,
库函数回调如下:
void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *I2cHandle)
{
/* Toggle LED2: Transfer in reception process is correct */
//add user code 1 john
BSP_LED_Toggle(LED2);
}
void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *I2cHandle)
{
/* Toggle LED2: Transfer in transmission process is correct */
BSP_LED_Toggle(LED2);
//add user code 2 john
}
可以实现I2C接收消息的异步,效率也是更高。
ST提供I2C接口有:
(#) Blocking mode functions are :
(++) HAL_I2C_Master_Transmit()
(++) HAL_I2C_Master_Receive()
(++) HAL_I2C_Slave_Transmit()
(++) HAL_I2C_Slave_Receive()
(++) HAL_I2C_Mem_Write()
(++) HAL_I2C_Mem_Read()
(++) HAL_I2C_IsDeviceReady()
(#) No-Blocking mode functions with Interrupt are :
(++) HAL_I2C_Master_Transmit_IT()
(++) HAL_I2C_Master_Receive_IT()
(++) HAL_I2C_Slave_Transmit_IT()
(++) HAL_I2C_Slave_Receive_IT()
(++) HAL_I2C_Mem_Write_IT()
(++) HAL_I2C_Mem_Read_IT()
(#) No-Blocking mode functions with DMA are :
(++) HAL_I2C_Master_Transmit_DMA()
(++) HAL_I2C_Master_Receive_DMA()
(++) HAL_I2C_Slave_Transmit_DMA()
(++) HAL_I2C_Slave_Receive_DMA()
(++) HAL_I2C_Mem_Write_DMA()
(++) HAL_I2C_Mem_Read_DMA()
(#) A set of Transfer Complete Callbacks are provided in non Blocking mode:
(++) HAL_I2C_MemTxCpltCallback()
(++) HAL_I2C_MemRxCpltCallback()
(++) HAL_I2C_MasterTxCpltCallback()
(++) HAL_I2C_MasterRxCpltCallback()
(++) HAL_I2C_SlaveTxCpltCallback()
(++) HAL_I2C_SlaveRxCpltCallback()
(++) HAL_I2C_ErrorCallback()
官方代码案例:
//主机模式发送
/* Timeout is set to 10S */
while(HAL_I2C_Master_Transmit(&hi2c1, (uint16_t)I2C_ADDRESS, (uint8_t*)aTxBuffer, TXBUFFERSIZE, 10000)!= HAL_OK)
{
/* Error_Handler() function is called when Timeout error occurs.
When Acknowledge failure occurs (Slave don't acknowledge its address)
Master restarts communication */
if (HAL_I2C_GetError(&hi2c1) != HAL_I2C_ERROR_AF)
{
Error_Handler();
}
}
//主机模式接收
/* Timeout is set to 10S */
while(HAL_I2C_Master_Receive(&hi2c1, (uint16_t)I2C_ADDRESS, (uint8_t *)aRxBuffer, RXBUFFERSIZE, 10000) != HAL_OK)
{
/* Error_Handler() function is called when Timeout error occurs.
When Acknowledge failure occurs (Slave don't acknowledge it's address)
Master restarts communication */
if (HAL_I2C_GetError(&hi2c1) != HAL_I2C_ERROR_AF)
{
Error_Handler();
}
}
//从机模式接收
/* Timeout is set to 10S */
if(HAL_I2C_Slave_Receive(&hi2c1, (uint8_t *)aRxBuffer, RXBUFFERSIZE, 10000) != HAL_OK)
{
/* Transfer error in reception process */
Error_Handler();
}
//从机模式发送
/* Timeout is set to 10S */
if(HAL_I2C_Slave_Transmit(&hi2c1, (uint8_t*)aTxBuffer, TXBUFFERSIZE, 10000)!= HAL_OK)
{
/* Transfer error in transmission process */
Error_Handler();
}
//错误回调函数
/**
* @brief I2C error callbacks.
* @param I2cHandle: I2C handle
* @note This example shows a simple way to report transfer error, and you can
* add your own implementation.
* @retval None
*/
void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *I2cHandle)
{
//
}
------by john
浙公网安备 33010602011771号