配置I2C 和串口
串口的配置就不做详细介绍

 



1
#include "stm32f1xx_hal.h" 2 #include "Eeprom.h" 3 #include "string.h" 4 extern I2C_HandleTypeDef hi2c1; 5 /*------д×Ö·û´®µ½EEPROMÖÐ*/ 6 void I2C_eepWritePage(uint8_t address,char * str){ 7 int len = 0;//ÓÃÀ´¼ÆËãд½øµÄ×Ö·û´®³¤¶È 8 int status ; //ÓÃÀ´´æ·Åд½øÈ¥µÄ״̬ 9 int page = 0; //ÓÃÀ´±£´æÒ³Êý 10 int k = 0;//ÓÃÀ´ÓÃ×öforÑ­»· ҳд 11 len = strlen(str)+1;//¼Ó1 °Ñ½áÊø·ûÒ²°üÀ¨½øÈ¥ 12 if(len <= 7){ //Èç¹û×Ö½Ú³¤¶ÈСÓÚ8¸ö×Ö½Ú ÄÇô¾Í¿ÉÒÔÖ±½Ó´æ·ÅÎÞÐè·ÖÒ³ 13 status = HAL_I2C_Mem_Write(&hi2c1,0xA0,address,I2C_MEMADD_SIZE_8BIT,str,len,200);//0xa0дÃüÁî 14 if(status == HAL_OK){ 15 printf("дÈë³É¹¦£¡ \nдÈëµÄÊý¾Ý³¤¶ÈΪ:%d\nдÈëµÄÊý¾ÝÄÚÈÝΪ:%s",len,str); 16 } 17 }else{//Èç¹ûдÈëµÄ×Ö½Ú´óÓÚ8¸ö×Ö½ÚÔò·ÖÒ³±£´æ 18 page = len%8 > 0 ? (len/8+1): (len/8);//ÓÃÀ´¼ÆËãÓжàÉÙÒ³Êý¾Ý ÈýÔªÔËËã 19 for(k = 0; k<page; k++){ 20 while(HAL_I2C_IsDeviceReady(&hi2c1,0xA0,3,500));//²â溯Êý ÅжÏeepromÊÇ·ñ´¦ÔÚæµ״̬ 21 status = HAL_I2C_Mem_Write(&hi2c1,0xA0,address+k*8, 22 I2C_MEMADD_SIZE_8BIT,str+8*k,(len-8*k>=8)?8:(len-8*k),200); 23 HAL_Delay(10); 24 if(status == HAL_OK){ 25 printf("±£´æµÚ:%dÒ³µÄµØÖ·:%d\n",k+1,address+8*k);//address+8*k 26 } 27 /*---->Ò»¸öÒ»¸ö×Ö½Úд*/ 28 while(HAL_I2C_IsDeviceReady(&hi2c1,0xA0,3,500)){ 29 HAL_I2C_Mem_Write(&hi2c1,0xA0,address+k,I2C_MEMADD_SIZE_8BIT,str+k,1,200); 30 HAL_Delay(10); 31 } 32 } 33 } 34 } 35 uint8_t* I2c_eep_Read(uint8_t address, uint8_t * data){ 36 uint8_t d = 0; //ÓÃ×÷forÑ­»·±äÁ¿´æ·Å±äÁ¿ 37 uint8_t Read_status = 0;//ÓÃÀ´´æ·Å¶ÁÈ¡µÄ״ֵ̬ 38 do{ 39 while(HAL_I2C_IsDeviceReady(&hi2c1,0xA1,3,5));//²â溯Êý 40 Read_status = HAL_I2C_Mem_Read(&hi2c1,0xA1,address,I2C_MEMADD_SIZE_8BIT,&data[d],1,200); 41 if(Read_status == HAL_OK){ 42 d ++; 43 address ++; 44 }else{ 45 printf("¶ÁÈ¡µ½µÚ%d¸ö×Ö½Ú³öÏÖ´íÎó:%d\n",d-1,Read_status); 46 } 47 HAL_Delay(10); 48 }while(data[d-1] != '\0' && d<100); 49 return data; 50 }

主函数代码
void main(){
     printf("\n1-------------------eeprom  start\n"); 
     I2C_eepWritePage(0x00,"你好,我是新写入的数据!我写了很多内容今天的天气很多变\0"); uint8_t data[100] = {0}; HAL_Delay(100); printf("读取到的数据:%s",I2c_eep_Read(0x00,data));//eeprom 读取数据
}

 

实现结果