stm32at24c02cube配置的驱动代码
时间: 2023-12-01 11:03:03 浏览: 93
stm32驱动源码
以下是使用STM32 AT24C02 EEPROM芯片的驱动代码,基于STM32 Cube库进行配置,包括初始化、写入和读取数据等基本操作:
```c
#include "stm32f4xx_hal.h"
#include "stm32f4xx_hal_i2c.h"
/* AT24C02 EEPROM地址 */
#define AT24C02_ADDRESS 0xA0
/* I2C句柄 */
I2C_HandleTypeDef hi2c1;
/* 初始化I2C */
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();
}
}
/* 写入数据到EEPROM */
HAL_StatusTypeDef AT24C02_WriteByte(uint16_t MemAddress, uint8_t data)
{
uint8_t Address_HighByte = (uint8_t)((MemAddress & 0xFF00) >> 8);
uint8_t Address_LowByte = (uint8_t)(MemAddress & 0x00FF);
uint8_t TxBuffer[2];
TxBuffer[0] = Address_HighByte;
TxBuffer[1] = Address_LowByte;
if (HAL_I2C_Master_Transmit(&hi2c1, AT24C02_ADDRESS, TxBuffer, 2, 1000) != HAL_OK)
{
return HAL_ERROR;
}
if (HAL_I2C_Master_Transmit(&hi2c1, AT24C02_ADDRESS, &data, 1, 1000) != HAL_OK)
{
return HAL_ERROR;
}
return HAL_OK;
}
/* 从EEPROM读取数据 */
HAL_StatusTypeDef AT24C02_ReadByte(uint16_t MemAddress, uint8_t *data)
{
uint8_t Address_HighByte = (uint8_t)((MemAddress & 0xFF00) >> 8);
uint8_t Address_LowByte = (uint8_t)(MemAddress & 0x00FF);
uint8_t TxBuffer[2];
TxBuffer[0] = Address_HighByte;
TxBuffer[1] = Address_LowByte;
if (HAL_I2C_Master_Transmit(&hi2c1, AT24C02_ADDRESS, TxBuffer, 2, 1000) != HAL_OK)
{
return HAL_ERROR;
}
if (HAL_I2C_Master_Receive(&hi2c1, AT24C02_ADDRESS, data, 1, 1000) != HAL_OK)
{
return HAL_ERROR;
}
return HAL_OK;
}
/* 初始化EEPROM */
void AT24C02_Init(void)
{
MX_I2C1_Init();
}
```
使用时可以先调用`AT24C02_Init()`初始化EEPROM,然后使用`AT24C02_WriteByte()`写入数据,使用`AT24C02_ReadByte()`读取数据。例如:
```c
uint8_t data = 0x12;
AT24C02_WriteByte(0x00, data);
uint8_t read_data;
AT24C02_ReadByte(0x00, &read_data);
```
阅读全文