I2C — I2C EEPROM 中断
固件库: GD32F30x_Firmware_Library V3.0.3
芯片: GD32
源文件: GD32F30x_Firmware_Library_V3.0.3/Examples/I2C/I2C_EEPROM_interrput/main.c
功能简介
本示例演示通过 I2C 接口读写 EEPROM(如 AT24C02)。EEPROM 是最常用的 I2C 从设备,掉电不丢失数据,适合存储配置参数。
硬件准备
- AT24C02 或类似 EEPROM 模块
- 连接:SCL→PB10, SDA→PB11(具体引脚参考代码)
- 注意上拉电阻(模块通常自带)
完整代码
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
57
58
59
60
61
62
63
64
65
66
67
68
|
#include <stdio.h>
#include "gd32f30x.h"
#include "gd32f307c_eval.h"
#include "systick.h"
#include "i2c.h"
#include "at24cxx.h"
int main(void)
{
/* configure systick */
systick_config();
/* configure LEDs */
led_config();
/* configure USART */
gd_eval_com_init(EVAL_COM0);
printf("I2C-24C02 configured....\n\r");
/* configure the NVIC */
i2c_nvic_config();
/* configure GPIO */
gpio_config();
/* configure I2C */
i2c_config();
/* initialize EEPROM */
i2c_eeprom_init();
printf("\r\nThe I2C is hardware interface ");
printf("\r\nThe speed is %d", I2C_SPEED);
if(I2C_OK == i2c_24c02_test()) {
while(1) {
/* turn off all LEDs */
gd_eval_led_off(LED2);
gd_eval_led_off(LED3);
gd_eval_led_off(LED4);
gd_eval_led_off(LED5);
/* turn on a LED */
led_turn_on(count % 4);
count++;
if(count >= 4) {
count = 0;
}
delay_1ms(500);
}
}
/* turn on all LEDs */
gd_eval_led_on(LED2);
gd_eval_led_on(LED3);
gd_eval_led_on(LED4);
gd_eval_led_on(LED5);
while(1) {
}
}
void i2c_nvic_config(void)
{
nvic_priority_group_set(NVIC_PRIGROUP_PRE1_SUB3);
nvic_irq_enable(I2C0_EV_IRQn, 0, 2);
nvic_irq_enable(I2C0_ER_IRQn, 0, 1);
}
|
代码讲解
printf 输出:通过串口打印调试信息。需要先调用 uart_print_init 完成重定向。
I2C 配置:设置通信速率(标准 100K / 快速 400K / 快速+ 1M)、从机地址、时钟拉伸。
中断优先级配置:NVIC 设置中断的抢占优先级和子优先级。数字越小优先级越高。
实验现象
- 按下按键后,向 EEPROM 写入数据并读回
- 写入和读出的数据一致则 LED 亮起
注意事项
- I2C 总线需要上拉电阻(一般 4.7K)
- 从机地址要与设备手册一致(注意 7 位/8 位地址的区别)
- 写 EEPROM 后需要等待 5ms 以上再读