首页 > 其他分享 >使用CUBE_MX使用I2C通信,实现对EEPROM的读写

使用CUBE_MX使用I2C通信,实现对EEPROM的读写

时间:2024-09-17 23:21:31浏览次数:11  
标签:WriteAddr CUBE HAL uint8 pBuffer I2C MX EEPROM

一、使用CUBE_MX配置

1.配置I2C

2.配置USART1

3.重中之重(在KEIL5打开串口使用的库)

二、KEIL5配置

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

#include <stdio.h>

void SystemClock_Config(void);
void I2C_EE_BufferWrite(uint8_t* pBuffer, uint8_t WriteAddr, uint16_t NumByteToWrite);
uint32_t I2C_EE_PageWrite(uint8_t* pBuffer, uint8_t WriteAddr, uint8_t NumByteToWrite);

#define  DATA_Size			256
#define  EEP_Firstpage      0x00
#define  EEPROM_ADDRESS     0xA0
//一个I2C从设备有两个地址,一个是写操作地址,另一个是读操作地址。例如,开发板上的EEPROM芯片24C02的写操作地址是0xA0,读操作地址是0xA1,也就是在写操作地址上加1。

//在I2C的HAL库驱动中,传递从设备地址参数时,只需要设置写操作地址,函数内部会根据读写操作类型,自动使用写操作地址或读操作地址。但是在软件模拟I2C接口通信时,必须明确使用相应的地址。


#define I2Cx_TIMEOUT_MAX                300
/* Maximum number of trials for HAL_I2C_IsDeviceReady() function */
#define EEPROM_MAX_TRIALS               300


uint8_t I2C_pData[DATA_Size];
uint8_t I2c_Buf_Write[DATA_Size];
uint8_t I2c_Buf_Read[DATA_Size];



int main(void)
{


  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
	

	for (int i=0; i<DATA_Size; i++ ) //填充要发送的数据
	{   
		I2C_pData[i] =i;
	}

	//作为主设备向某个地址的从设备发送一定长度的数据
	HAL_StatusTypeDef status = HAL_OK;
	
	
	
	printf("通过I2C,由I2C_pData向EEPROM发送数据\r\n");
/*
	status=HAL_I2C_Mem_Write(&hi2c1, EEPROM_ADDRESS , EEP_Firstpage , I2C_MEMADD_SIZE_8BIT, (uint8_t*)(I2C_pData), DATA_Size, 100);	
	if(status == HAL_OK )
	{
		printf("通过I2C,由I2C_pData向EEPROM发送数据\r\n");
		status = HAL_OK;
	}
*/	
	
	
	//由于EEPROM每页只有八个字节,写入不定长的数据需要调用这个函数
	I2C_EE_BufferWrite( (uint8_t*)I2C_pData,EEP_Firstpage,DATA_Size);


	//读取写入EEPROM的数据
	//向某个从设备的指定存储地址开始读取一定长度的数据
	//将EEPROM读出数据顺序保持到I2c_Buf_Read中
    status= HAL_I2C_Mem_Read(&hi2c1,EEPROM_ADDRESS,EEP_Firstpage,I2C_MEMADD_SIZE_8BIT,I2c_Buf_Read,DATA_Size,1000);
	if(status == HAL_OK )
	{
		printf("通过I2C,读取EEPROM中的数据,并且保存到I2c_Buf_Read\r\n");
		status = HAL_OK;
	}
	
	
	
	for (int i=0; i<DATA_Size; i++ ) 
	{   
		printf("数据是 0x%02X  \r\n",I2c_Buf_Read[i]);
	} 
	
	
	
  while (1)
  {

  }

}









/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}












/* USER CODE BEGIN 4 */



/* AT24C01/02每页有8个字节 */
//#define EEPROM_PAGESIZE    8
#define EEPROM_PAGESIZE 	   8


/**
  * @brief   将缓冲区中的数据写到I2C EEPROM中
  * @param   
  *		@arg pBuffer:缓冲区指针
  *		@arg WriteAddr:写地址
  *     @arg NumByteToWrite:写的字节数
  * @retval  无
  */
void I2C_EE_BufferWrite(uint8_t* pBuffer, uint8_t WriteAddr, uint16_t NumByteToWrite)
{
  uint8_t NumOfPage = 0, NumOfSingle = 0, Addr = 0, count = 0;

  Addr = WriteAddr % EEPROM_PAGESIZE;
  count = EEPROM_PAGESIZE - Addr;
  NumOfPage =  NumByteToWrite / EEPROM_PAGESIZE;
  NumOfSingle = NumByteToWrite % EEPROM_PAGESIZE;
 
  /* If WriteAddr is I2C_PageSize aligned  */
  if(Addr == 0) 
  {
    /* If NumByteToWrite < I2C_PageSize */
    if(NumOfPage == 0) 
    {
      I2C_EE_PageWrite(pBuffer, WriteAddr, NumOfSingle);
    }
    /* If NumByteToWrite > I2C_PageSize */
    else  
    {
      while(NumOfPage--)
      {
        I2C_EE_PageWrite(pBuffer, WriteAddr, EEPROM_PAGESIZE); 
        WriteAddr +=  EEPROM_PAGESIZE;
        pBuffer += EEPROM_PAGESIZE;
      }

      if(NumOfSingle!=0)
      {
        I2C_EE_PageWrite(pBuffer, WriteAddr, NumOfSingle);
      }
    }
  }
  /* If WriteAddr is not I2C_PageSize aligned  */
  else 
  {
    /* If NumByteToWrite < I2C_PageSize */
    if(NumOfPage== 0) 
    {
      I2C_EE_PageWrite(pBuffer, WriteAddr, NumOfSingle);
    }
    /* If NumByteToWrite > I2C_PageSize */
    else
    {
      NumByteToWrite -= count;
      NumOfPage =  NumByteToWrite / EEPROM_PAGESIZE;
      NumOfSingle = NumByteToWrite % EEPROM_PAGESIZE;	
      
      if(count != 0)
      {  
        I2C_EE_PageWrite(pBuffer, WriteAddr, count);
        WriteAddr += count;
        pBuffer += count;
      } 
      
      while(NumOfPage--)
      {
        I2C_EE_PageWrite(pBuffer, WriteAddr, EEPROM_PAGESIZE);
        WriteAddr +=  EEPROM_PAGESIZE;
        pBuffer += EEPROM_PAGESIZE;  
      }
      if(NumOfSingle != 0)
      {
        I2C_EE_PageWrite(pBuffer, WriteAddr, NumOfSingle); 
      }
    }
  }  
}






/**
  * @brief   在EEPROM的一个写循环中可以写多个字节,但一次写入的字节数
  *          不能超过EEPROM页的大小,AT24C02每页有8个字节
  * @param   
  *		@arg pBuffer:缓冲区指针
  *		@arg WriteAddr:写地址
  *     @arg NumByteToWrite:写的字节数
  * @retval  无
  */
uint32_t I2C_EE_PageWrite(uint8_t* pBuffer, uint8_t WriteAddr, uint8_t NumByteToWrite)
{
	HAL_StatusTypeDef status = HAL_OK;
	/* Write EEPROM_PAGESIZE */
	status=HAL_I2C_Mem_Write(&hi2c1, EEPROM_ADDRESS,WriteAddr, I2C_MEMADD_SIZE_8BIT, (uint8_t*)(pBuffer),NumByteToWrite, 100);

	while (HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY)
	{
		
	}

	/* Check if the EEPROM is ready for a new operation */
	while (HAL_I2C_IsDeviceReady(&hi2c1, EEPROM_ADDRESS, EEPROM_MAX_TRIALS, I2Cx_TIMEOUT_MAX) == HAL_TIMEOUT);

	/* Wait for the end of the transfer */
	while (HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY)
	{
		
	}
	return status;
}











//重定向c库函数printf到串口DEBUG_USART,重定向后可使用printf函数
int fputc(int ch, FILE *f)
{
	/* 发送一个字节数据到串口DEBUG_USART */
	HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 1000);	
	
	return (ch);
}

///重定向c库函数scanf到串口DEBUG_USART,重写向后可使用scanf、getchar等函数
int fgetc(FILE *f)
{
		
	int ch;
	HAL_UART_Receive(&huart1, (uint8_t *)&ch, 1, 1000);	
	return (ch);
}

/* USER CODE END 4 */








/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

标签:WriteAddr,CUBE,HAL,uint8,pBuffer,I2C,MX,EEPROM
From: https://blog.csdn.net/weixin_67341796/article/details/142320816

相关文章

  • Springboot古建筑信息现代数字化管理平台z6mmx程序+源码+数据库+调试部署+开发环境
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容随着信息技术的飞速发展,古建筑作为中华文化的瑰宝,其保护、传承与展示方式亟需与时俱进。传统古建筑管理模式存在信息不对称、资源浪费、效率低下等......
  • VP 【MX-S2】 解题报告
    VP【MX-S2】解题报告VPresult:比赛地址目录VP【MX-S2】解题报告【MX-S2-T1】变DescriptionConstraintsSolutionCode【MX-S2-T2】排DescriptionConstraintsSolutionSubtask2Subtask3FinalCode【MX-S2-T3】跳DescriptionConstraintsSolutionSubtask1Subtask2FinalCode......
  • STM32CubeIDE看门狗
    看门狗简介看门狗:本质是一个递减的计数器当程序有BUG或硬件问题导致的程序卡死或跑飞时,看门狗可及时复位程序作用:防止程序卡死或程序跑飞,保证系统的可靠性和稳定性STM32有独立看门狗(IWDG)和窗口看门狗(WWDG)两种类型独立看门狗:独立工作,对时间精度要求较低窗口看门狗:时间精......
  • 必趣CB1核心板、H616主控linux验证IO模拟I2C驱动DS1307时钟芯片
    使用了#include<gpiod.h>内部库作为IO驱动`#ifndef __DS1307_Hdefine__DS1307_HdefineNUM_LEDS21//控制4个GPIO引脚defineCHIPNAME"gpiochip0"//GPIO芯片的名称defineWRITE_CMD 0x00defineREAD_CMD 0x01defineDEV_ADDR0xD0//......
  • [linux 驱动]i2c总线设备驱动详解与实战
    目录1描述2结构体2.1bus_type2.2i2c_bus_type2.2.1i2c_device_match2.2.2i2c_device_probe2.2.3i2c_device_remove2.2.4i2c_device_shutdown2.2i2c_adapter2.3i2c_algorithm2.4i2c_driver2.5i2c_client3i2c核心3.1注册i2c适配器3.2注册i2c设备......
  • P11037 【MX-X3-T4】「RiOI-4」上课
    P11037【MX-X3-T4】「RiOI-4」上课本文主要解释不断\(+1\)的过程如何快速实现的具体流程。题意给定正整数\(n,q\)和\(n\)个区间\([l_i,r_i]\)。有\(q\)组询问,每次询问给定一个整数\(x\)。在每个区间内选择一个整数\(a_i\)(\(l_i\leqa_i\leqr_i\)),使得所选整数的总......
  • P11036 【MX-X3-T3】「RiOI-4」GCD 与 LCM 问题
    P11036【MX-X3-T3】「RiOI-4」GCD与LCM问题题意描述给出\(a\),求一组构造\(b,c,d\)使得\(a+b+c+d=gcd(a,b)+lcm(c,d)\)同时需要保证\(b,c,d\le1634826193\)思路变量实在太多了,考虑先大胆消掉一个,令\(b=1\),此时问题简化为使得\(a+c+d=lcm(c,d)\)赛时真的没想出......
  • 【北京迅为】iTOP-i.MX6开发板使用手册第四部分固件编译第十四章非设备树Android4.4系
     可根据用户需求更换,百变定制,高端产品无忧! 迅为IMX6Q兼容四核商业级、双核商业级、四核工业级、更可提供i.MX6Q家族PLUS版本核心板。核心板采用十层PCB沉金盲埋设计,更能保证电磁兼容与系统稳定。 公众号:迅为电子 -----------------------------------------   ......
  • JMeter jmx脚本文件解析
    JMeter——jmx脚本文件解析_jmx文件线程组解析-CSDN博客<?xmlversion="1.0"encoding="UTF-8"?><jmeterTestPlanversion="1.2"properties="5.0"jmeter="5.5"><hashTree><TestPlanguiclass="TestP......
  • 基于STM32C8T6的CubeMX:HAL库点亮LED
    三个可能的问题和解决方法:大家完成之后回来看,每一种改错误都是一种成长,不要畏惧,要快乐,积极面对,要耐心对待STMCuBeMX新建项目的两种匪夷所思的问题https://mp.csdn.net/mp_blog/creation/editor/142151511STMCubeMX文件下载后会出现其他项目无法下载的问题https://mp.csdn.ne......