Nuru_Banmian
Nuru_Banmian
Published on 2025-04-22 / 61 Visits
0
0

I2C_案例2_hal库方式使用I2C

CubeMX设置

1. RCC,SYS,CLOCK CONFIGURATION设置

2. Usart和I2C设置

本案例设置好默认即可

I2C_案例2_Usart设置.png

I2C_案例2_I2C设置.png

代码

编写m24c02模块代码

m24c02.h

 #ifndef __M24C02_H
 #define __M24C02_H
 ​
 #include "i2c.h"
 ​
 // 宏定义
 #define W_ADDR 0xA0
 #define R_ADDR 0xA1
 ​
 // 初始化
 void M24C02_Init(void);
 ​
 // 向EEPROM写入一个字节
 void M24C02_WriteByte(uint8_t inneraddr, uint8_t byte);
 ​
 // 从EEPROM读取一个字节
 uint8_t M24C02_ReadByte(uint8_t inneraddr);
 ​
 // 连续写入多个字节(页写)
 void M24C02_WriteBytes(uint8_t inneraddr, uint8_t *bytes, uint8_t size);
 ​
 // 连续读取多个字节
 void M24C02_ReadBytes(uint8_t inneraddr, uint8_t *buffer, uint8_t size);
 ​
 #endif
 ​

m24c02.c

 #include "m24c02.h"
 ​
 // 初始化
 void M24C02_Init(void)
 {
     MX_I2C2_Init();
 }
 ​
 // 向EEPROM写入一个字节
 void M24C02_WriteByte(uint8_t inneraddr, uint8_t byte)
 {
     HAL_I2C_Mem_Write(&hi2c2, W_ADDR, inneraddr, I2C_MEMADD_SIZE_8BIT, &byte, 1, 1000);
 ​
     // 延迟等待写入周期结束
     HAL_Delay(5);
 }
 ​
 // 从EEPROM读取一个字节
 uint8_t M24C02_ReadByte(uint8_t inneraddr)
 {
     uint8_t byte = 0;
     HAL_I2C_Mem_Read(&hi2c2, R_ADDR, inneraddr, I2C_MEMADD_SIZE_8BIT, &byte, 1, 1000);
     return byte;
 }
 ​
 // 连续写入多个字节(页写)
 void M24C02_WriteBytes(uint8_t inneraddr, uint8_t *bytes, uint8_t size)
 {
     HAL_I2C_Mem_Write(&hi2c2, W_ADDR, inneraddr, I2C_MEMADD_SIZE_8BIT, bytes, size, 1000);
 ​
     // 延迟等待写入周期结束
     HAL_Delay(5);
 }
 ​
 // 连续读取多个字节
 void M24C02_ReadBytes(uint8_t inneraddr, uint8_t *buffer, uint8_t size)
 {
     HAL_I2C_Mem_Read(&hi2c2, R_ADDR, inneraddr, I2C_MEMADD_SIZE_8BIT, buffer, size, 1000);
 }
 ​

main.c

 /* USER CODE BEGIN Includes */
 #include "m24c02.h"
 #include <string.h>
 /* USER CODE END Includes */
 ​
 /* USER CODE BEGIN 2 */
   printf("你好r\n");
 ​
   // 2. 向EEPROM依次写入单个字符
   M24C02_WriteByte(0x00, 'a');
   M24C02_WriteByte(0x01, 'b');
   M24C02_WriteByte(0x02, 'c');
 ​
   // 3. 读取字符
   uint8_t byte1 = M24C02_ReadByte(0x00);
   uint8_t byte2 = M24C02_ReadByte(0x01);
   uint8_t byte3 = M24C02_ReadByte(0x02);
 ​
   // 4. 串口输出打印
   printf("byte1 = %c\t byte2 = %c\t byte3 = %c\n", byte1, byte2, byte3);
 ​
   // 5. 写入多个字符
   M24C02_WriteBytes(0x00, "123456", 6);
 ​
   // 6. 读取多个字符
   uint8_t buffer[100] = {0};
   M24C02_ReadBytes(0x00, buffer, 6);
 ​
   // 7. 串口打印
   printf("buffer = %s\n", buffer);
 ​
   // 8. 测试超出16个字节的写入
   // 清零缓冲区
   memset(buffer, 0, sizeof(buffer));
 ​
   M24C02_WriteBytes(0x00, "1234567890abcdefghijk", 21);
   M24C02_ReadBytes(0x00, buffer, 21);
   printf("buffer = %s\n", buffer);
 ​
   /* USER CODE END 2 */

usart.c

 /* Includes ------------------------------------------------------------------*/
 #include "usart.h"
 ​
 ​
 /* USER CODE BEGIN 1 */
 int fputc(int ch, FILE *f)
 {
   HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 1000);
   return ch;
 }
 /* USER CODE END 1 */



Comment