IIC——eeprom读写

发布于 2024-03-29  178 次阅读


PB6、PB7引脚设为GPIOoutput

uint8_t eeprom_Read(uint8_t addr)//addr:地址
{
	uint8_t Value;
	I2CStart();//开启IIC
	I2CSendByte(0xa0);//1010 0000 最后一位0为写,1为读     
	I2CWaitAck();//等待应答
	I2CSendByte(addr);//写入读取地址
	I2CSendAck();
	I2CStop();
	
	I2CStart();
	I2CSendByte(0xa1);//读
	I2CWaitAck();
	Value = I2CReceiveByte();
	I2CSendNotAck();
	I2CStop();
	
	return Value;
}

void eeprom_Write(uint8_t addr, uint8_t Value)
{
	I2CStart();
	I2CSendByte(0xa0);
	I2CWaitAck();
	I2CSendByte(addr);
	I2CSendAck();
	
	I2CSendByte(Value);
	I2CWaitAck();
	I2CStop();
}

例:

	/*eeporm为16位*/
        uint8_t high,low;
	
	high = frq >> 8;//取高八位
	low = frq & 0xff;//取低八位

	if(key[1].flag == 1)
	{
		eeprom_Write(1,high);
		HAL_Delay(10);//写入需要时间,不等待可能导致写入失败
		eeprom_Write(2,low);
		key[1].flag = 0;
		sprintf(text, "      Write Flish   ");
		LCD_DisplayStringLine(Line5, (uint8_t *)text);
		HAL_Delay(500);
		sprintf(text, "                    ");
		LCD_DisplayStringLine(Line5, (uint8_t *)text);
	}
/***************************************************************/
	if(key[2].flag == 1)
	{
		uint16_t eeprom;
		eeprom = (eeprom_Read(1) << 8) + eeprom_Read(2);//高八位+低八位
		sprintf(text, "             %d   ",eeprom );
		LCD_DisplayStringLine(Line4, (uint8_t *)text);
		key[2].flag = 0;
	}

最后更新于 2024-03-29