STM32 at24c512 I2C 驱动
时间: 2023-07-22 12:37:47 浏览: 197
以下是一个基于STM32的AT24C512 I2C驱动的示例代码,使用了HAL库:
```
#include "stm32f1xx_hal.h"
#define EEPROM_ADDRESS 0xA0 // AT24C512的I2C地址
I2C_HandleTypeDef hi2c1;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C1_Init();
uint8_t tx_data[2]; // 存储要写入的数据
uint8_t rx_data; // 存储要读取的数据
tx_data[0] = 0x00; // 要写入的EEPROM地址
tx_data[1] = 0x55; // 要写入的数据
HAL_I2C_Master_Transmit(&hi2c1, EEPROM_ADDRESS, tx_data, 2, 1000); // 写入数据
HAL_Delay(10); // 等待EEPROM写入完成
tx_data[0] = 0x00; // 要读取的EEPROM地址
HAL_I2C_Master_Transmit(&hi2c1, EEPROM_ADDRESS, tx_data, 1, 1000); // 发送要读取的地址
HAL_I2C_Master_Receive(&hi2c1, EEPROM_ADDRESS, &rx_data, 1, 1000); // 读取数据
while (1)
{
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
static void MX_I2C1_Init(void)
{
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();
}
}
static void MX_GPIO_Init(void)
{
__HAL_RCC_GPIOC_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}
void Error_Handler(void)
{
while (1)
{
}
}
```
在这个示例中,我们首先设置了系统时钟、GPIO和I2C。然后在主函数中,我们定义了要写入的数据和要读取的数据的变量,写入数据的过程是先设置要写入的EEPROM地址和要写入的数据,然后使用HAL_I2C_Master_Transmit函数向AT24C512芯片写入数据。读取数据的过程是先设置要读取的EEPROM地址,然后使用HAL_I2C_Master_Transmit函数向AT24C512芯片发送要读取的地址,最后使用HAL_I2C_Master_Receive函数从芯片中读取数据。注意,在写入数据后需要加一个延迟,以等待EEPROM写入完成。
阅读全文