帮我写出基于STM32F103 ,AT24C16程序驱动包含页写和页读,HAL库实现
时间: 2023-05-23 18:07:05 浏览: 199
#include "stm32f1xx_hal.h"
#include "stm32f1xx_hal_i2c.h"
#define EEPROM_ADDR 0xA0 // EEPROM address
#define PAGE_SIZE 16 // Page size in bytes
uint8_t eeprom_buffer[PAGE_SIZE]; // Page buffer
/* Function to write to EEPROM */
void write_to_eeprom(uint16_t address, uint8_t* data, uint16_t size)
{
// Wait for I2C bus to be ready
while (HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY);
// Write page to EEPROM
HAL_I2C_Mem_Write(&hi2c1, EEPROM_ADDR, (uint16_t)address, I2C_MEMADD_SIZE_8BIT, data, size, HAL_MAX_DELAY);
}
/* Function to read from EEPROM */
void read_from_eeprom(uint16_t address, uint8_t* data, uint16_t size)
{
// Wait for I2C bus to be ready
while (HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY);
// Read page from EEPROM
HAL_I2C_Mem_Read(&hi2c1, EEPROM_ADDR, (uint16_t)address, I2C_MEMADD_SIZE_8BIT, data, size, HAL_MAX_DELAY);
}
/* Function to write page to EEPROM */
void write_eeprom_page(uint16_t page_address)
{
// Calculate start address for page
uint16_t address = page_address * PAGE_SIZE;
// Write page to EEPROM
write_to_eeprom(address, eeprom_buffer, PAGE_SIZE);
}
/* Function to read page from EEPROM */
void read_eeprom_page(uint16_t page_address)
{
// Calculate start address for page
uint16_t address = page_address * PAGE_SIZE;
// Read page from EEPROM
read_from_eeprom(address, eeprom_buffer, PAGE_SIZE);
}
阅读全文