1、说明

(1)MCU为STM32F103C8,EEPROM型号M24C02; (2)硬件连接:EEPROM连接STM32的IIC1; (3)EEPROM的E0,E1,E2,WC脚连接地,因此其设备地址为:(0x50<<1),即0xA0; (4)程序中使用HAL库,代码有CubeMX生成;

2、程序

驱动头文件:m24_eeprom.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
\#ifndef __M24_EEPROM_H_
#define __M24_EEPROM_H_

#include "stdbool.h"
#include "string.h"

#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

HAL_StatusTypeDef EEPROM_ReadByte(uint16_t MemAddress,uint8_t *data);
HAL_StatusTypeDef EEPROM_WriteByte(uint16_t MemAddress,uint8_t data);

HAL_StatusTypeDef EEPROM_ReadMultipleBytes(uint16_t MemAddress, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef EEPROM_WriteMultipleBytes(uint16_t MemAddress, uint8_t *pData, uint16_t Size);

#endif

驱动主文件:m24_eeprom.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "m24_eeprom.h"
#include "i2c.h"

#define M24C02_ADDR (0x50<<1)

//eeprom read n bytes
HAL_StatusTypeDef EEPROM_ReadMultipleBytes(uint16_t MemAddress, uint8_t *pData, uint16_t Size)
{
if (HAL_I2C_Mem_Read(&hi2c1, M24C02_ADDR0x01, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 1000) == HAL_OK)
{
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}

//eeprom write n bytes
HAL_StatusTypeDef EEPROM_WriteMultipleBytes(uint16_t MemAddress, uint8_t *pData, uint16_t Size)
{
for(int i=0; i<Size; i++){
if(EEPROM_WriteByte(MemAddress+i, pData[i]) != HAL_OK){
return HAL_ERROR;
}
}
}

//EEPROM read
HAL_StatusTypeDef EEPROM_ReadByte(uint16_t MemAddress,uint8_t *data)
{
if (HAL_I2C_Mem_Read(&hi2c1, M24C02_ADDR0x01, MemAddress, I2C_MEMADD_SIZE_8BIT, data, 1, 1000) == HAL_OK)
{
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}

//EEPROM write byte
HAL_StatusTypeDef EEPROM_WriteByte(uint16_t MemAddress,uint8_t data)
{
if (HAL_I2C_Mem_Write(&hi2c1, M24C02_ADDR, MemAddress, I2C_MEMADD_SIZE_8BIT,&data,1, 1000) == HAL_OK)
{
//write cycle :5ms
HAL_Delay(5);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}

在main主文件进行调用:
  • 初始化
1
sht30_init();
  • 写EEPROM
1
2
3
4
5
6
uint8_t wdata[4] = {2,5,6,8};
if( EEPROM_WriteMultipleBytes(1,wdata, 4) != HAL_OK){
SEGGER_RTT_printf(0, "EEPROM write error\r\n");
}else{
SEGGER_RTT_printf(0, "EEPROM write ok\r\n");
}
  • 再读取回来
1
2
3
4
5
6
7
uint8_t rbuff[4];
SEGGER_RTT_printf(0, "EEPROM READ bytes:");
EEPROM_ReadMultipleBytes(1, rbuff, 4);
for(int x=0; x<4; x++){
SEGGER_RTT_printf(0, " %d", rbuff[x]);
}
SEGGER_RTT_printf(0, "\r\n");

将读取的数据和写入的数据进行比较,即可验证是否正确。 : 写入byte操作需要5ms,因此写入时候需要一定的延时。

结果如下所示:

m24c02-EEPROM读写