完整的STM32F4 I2C HAL驱动PCA9555程序带容错功能,出错重新初始化PCA9535
时间: 2023-06-26 20:08:28 浏览: 450
STM32F4 I2C/IIC 驱动程序
以下是一个基本的STM32F4 HAL库驱动程序示例,用于控制PCA9555 I2C扩展器,并具有容错功能。如果出现错误,将重新初始化PCA9535。
```c
#include "stm32f4xx_hal.h"
#define PCA9555_ADDR 0x40 << 1
I2C_HandleTypeDef hi2c1;
void PCA9555_Init(void)
{
uint8_t data[2];
data[0] = 0x06; // Configuration register
data[1] = 0x00; // All outputs
HAL_I2C_Master_Transmit(&hi2c1, PCA9555_ADDR, data, 2, 1000);
}
void PCA9555_Write(uint8_t channel, uint8_t value)
{
uint8_t data[2];
data[0] = 0x02; // Output register
data[1] = value;
HAL_I2C_Master_Transmit(&hi2c1, PCA9555_ADDR, data, 2, 1000);
}
void PCA9555_Retry_Write(uint8_t channel, uint8_t value)
{
uint8_t retry = 3;
while(retry--)
{
if(HAL_I2C_IsDeviceReady(&hi2c1, PCA9555_ADDR, 1, 1000) == HAL_OK)
{
PCA9555_Write(channel, value);
break;
}
else
{
HAL_I2C_DeInit(&hi2c1);
HAL_I2C_Init(&hi2c1);
PCA9555_Init();
}
}
}
int main(void)
{
HAL_Init();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_I2C1_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = GPIO_PIN_6 | GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 100000;
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c1) != HAL_OK)
{
Error_Handler();
}
PCA9555_Init();
PCA9555_Retry_Write(0, 0xFF);
while (1)
{
PCA9555_Retry_Write(0, 0x00);
HAL_Delay(500);
PCA9555_Retry_Write(0, 0xFF);
HAL_Delay(500);
}
}
```
在这个例子中,PCA9555_Init()函数初始化PCA9555,并将其配置为所有输出。PCA9555_Write()函数将输出值写入PCA9555的输出寄存器。PCA9555_Retry_Write()函数带有重试逻辑,如果I2C总线上的设备没有响应,则会重新初始化PCA9555,然后重试写操作。最后,在main()函数中,我们以1秒的间隔循环写入PCA9555的输出寄存器。
阅读全文