STM32F103C8T6 CubeMX I2C EEPROM AT24C256

 

1. 修改usart.c,将printf转为串口打印

/* USER CODE BEGIN 0 */
#include "stdio.h"
int fputc(int ch, FILE *f)
{
    /* Place your implementation of fputc here */
    /* e.g. write a character to the USART2 and Loop until the end of transmission */
    HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
    return ch;
}
/* USER CODE END 0 */

2.修改i2c.c

void HAL_I2C_MspInit(I2C_HandleTypeDef* i2cHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(i2cHandle->Instance==I2C1)
  {
  /* USER CODE BEGIN I2C1_MspInit 0 */

  /* USER CODE END I2C1_MspInit 0 */
  
    __HAL_RCC_GPIOB_CLK_ENABLE();
        __HAL_RCC_I2C1_CLK_ENABLE();
    /**I2C1 GPIO Configuration    
    PB6     ------> I2C1_SCL
    PB7     ------> I2C1_SDA 
    */
    GPIO_InitStruct.Pin = GPIO_PIN_6|GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    /* I2C1 clock enable */
            
  /* USER CODE BEGIN I2C1_MspInit 1 */

  /* USER CODE END I2C1_MspInit 1 */
  }
}
 

3.修改main.c

增加头文件:

#include "main.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"
#include <stdio.h>
#include <string.h>

   /* USER CODE BEGIN 1 */
#define ADDR_24LCxx_Write 0xA0
#define ADDR_24LCxx_Read 0xA1
#define BufferSize 256
uint8_t WriteBuffer[256] = { 0 };
uint8_t ReadBuffer[256] = { 0 };

uint16_t i = 0;
  /* USER CODE END 1 */

/* USER CODE BEGIN 2 */
    printf("\r\n***************I2C Example00*******************************\r\n");

    HAL_StatusTypeDef status = HAL_OK;
    
     for(i=0; i<256; i++)
      {
          WriteBuffer[i]=i;    /* WriteBuffer Initialization */
          printf("%02d ", WriteBuffer[i]);
      }

        unsigned int iPageSize = 8;
  
        for(i=0; i<256/iPageSize; i++)
        {
            if (HAL_I2C_Mem_Write(&hi2c1, ADDR_24LCxx_Write, i*iPageSize, I2C_MEMADD_SIZE_16BIT,&(WriteBuffer[i*iPageSize]),iPageSize, 1000) == HAL_OK)
            {
                //printf("\r\n Byte %02d to Byte %02d Write OK",i,i+8);
                HAL_Delay(5);//写完以后需要延时5ms,这个不能少
            }else{
                //printf("\r\n Byte %02d to Byte %02d Write Failed",i,i+8);
            }                
        }
        
 
/* read date from EEPROM */
    status = HAL_I2C_Mem_Read(&hi2c1, ADDR_24LCxx_Read, 0, I2C_MEMADD_SIZE_16BIT,ReadBuffer,BufferSize, 0x1000);
    printf("%d\r\n",status);
    for(i=0; i<256; i++)
    printf("%02d ",ReadBuffer[i]);

if(memcmp(ReadBuffer,WriteBuffer,256) == 0 ) /* check data */
          printf("\r\n AT24C02 Read Test OK\r\n");
      else
          printf("\r\n AT24C02 Read Test Failed\r\n");
/* USER CODE END 2 */
 

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值