[蓝桥杯单片机11]IIC的应用—EEPROM

实现功能:断电e2prom里的内容加1,并显示在数码管上。

1.main.c 文件

#include "reg52.h"
#include "intrins.h"
#include "iic.h"
unsigned char num=0,num_ge=0,num_shi=0;

unsigned char code SMG_duanma[18]=
{0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
     0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,
     0xbf,0x7f};
void Delay50ms()		//@11.0592MHz
{
	unsigned char i, j, k;

	_nop_();
	_nop_();
	i = 3;
	j = 26;
	k = 223;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}

void Delay100us()		//@11.0592MHz
{
	unsigned char i, j;

	_nop_();
	_nop_();
	i = 2;
	j = 15;
	do
	{
		while (--j);
	} while (--i);
}

void SelectHC573(unsigned char channel)
{
	switch(channel)
	{
		case 4:
			P2 = (P2 & 0x1f) | 0x80;
		break;
		case 5:
			P2 = (P2 & 0x1f) | 0xa0;
		break;
		case 6:
			P2 = (P2 & 0x1f) | 0xc0;
		break;
		case 7:
			P2 = (P2 & 0x1f) | 0xe0;
		break;
	}
}

void DisplaySMG_Bit(unsigned char value, unsigned char pos)
{
	P0 = 0xff;
	SelectHC573(6);
	P0 = 0x01 << pos;
	SelectHC573(7);
	P0 = value;
}
//EEPROM读函数
unsigned char eeprom_read(unsigned char address)
{
  unsigned char jieshou;
  I2CStart();
  I2CSendByte(0xa0);//eeprom写入模式
  I2CWaitAck();
  I2CSendByte(address);
  I2CWaitAck();
  
  I2CStart();
  I2CSendByte(0xa1);//eeprom读取模式
  I2CWaitAck();
  jieshou=I2CReceiveByte();
  I2CStop();
  return jieshou;
}

//EEPROM写函数
unsigned char eeprom_write(unsigned char address,unsigned char value)
{
  I2CStart();
  I2CSendByte(0xa0);//eeprom写入模式
  I2CWaitAck();
  I2CSendByte(address);
  I2CWaitAck();
  
  I2CSendByte(value);
  I2CWaitAck();
  I2CStop();
}
//主函数
void main()
{
  num=eeprom_read(0);
  Delay50ms();
  num++;
  eeprom_write(0,num);
  Delay50ms();
  while(1)
  {
    num_ge = num%10;
    num_shi = num/10;
    DisplaySMG_Bit(SMG_duanma[num_shi],0);
    Delay100us();
    DisplaySMG_Bit(SMG_duanma[num_ge],1);
    Delay100us();
  }
}

2.iic.c 补充

#include "reg52.h"
#include "intrins.h"
#define DELAY_TIME	5

sbit sda = P2^1;
sbit scl = P2^0;
//

3、iic.h自己写 

#ifndef __IIC_H__
#define __IIC_H__

static void I2C_Delay(unsigned char n);
void I2CStart(void);
void I2CStop(void);
void I2CSendByte(unsigned char byt);
unsigned char I2CReceiveByte(void);
unsigned char I2CWaitAck(void);
void I2CSendAck(unsigned char ackbit);


#endif

你可能感兴趣的:(蓝桥杯单片机,单片机,蓝桥杯,嵌入式硬件)