24C02拜肈

 lxyz1127  201804る05ら 00:52:08
ヘ玡ㄏノPIC16F877A 糶–溃ΩSW,虑パ24C02糶弄计(パ7-SEG陪ボ),ヘ玡溃礚ヴ笆,
虫糶24C02计パ7-SEG弄计常琌oK,琌糶璶弄,パ7-SEG陪ボ玱礚猭笆,羉狡碭Ωтぃ拜肈翴,琌Τ玡晋腊Γ旧

#include <pic.h> //调用PIC16F87XA单片机的头文件
//#include "877_I2C.H"
//#include "24C02.H"

void delay(int num);
void I2C_Init(void);
void I2C_Start(void);
void I2C_RptStart(void);
void I2C_Stop(void);
int I2C_Read(unsigned char ack);
unsigned char I2C_Write(unsigned char I2CWriteData);
void write_ext_eeprom(unsigned char address,unsigned char data);
unsigned char read_ext_eeprom(unsigned char address);


__CONFIG(HS & LVPDIS & WDTDIS);



const unsigned char LED[]=
{
0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90 //0~9
};

//---------------------------------------
void main() //主函数,单片机开机后就是从这个函数开始运行
{
unsigned char Reset_Count=0;
unsigned char EEP_Address=0x04;

TRISD=0X00; //7-SEG Output
PORTD=0Xff; //7-SEG low
TRISB1=1; //RB1 input
TRISE=0x00; //control 7-SEG
PORTE=0b11111101; //RE1 low

I2C_Init();
//Reset_Count=read_ext_eeprom(EEP_Address);
//Reset_Count++;
PORTD=LED[Reset_Count];
// write_ext_eeprom(EEP_Address,Reset_Count);
while(1)
{


if(RB1==0)
{
delay(20);
if(RB1==0)
{
Reset_Count++;
if(Reset_Count>=10)
{
Reset_Count=0;
}
write_ext_eeprom(EEP_Address,Reset_Count);

Reset_Count=read_ext_eeprom(EEP_Address);
PORTD=LED[Reset_Count];


}
}

}
}

//----------------I2C----------------------------------
void I2C_Init()
{
TRISC3=1; //SCL set input
TRISC4=1; //SCL set input

SSPCON=0x38; //砞﹚I2C家Α
SSPCON2=0x00;
SSPADD=0x09; //繵4M ,肚块瞯:100K

CKE=0;
SMP=1;
SSPIF=0;
BCLIF=0;
}

void I2C_Start()
{
SEN=1;
while(SEN);
}

void I2C_RptStart()
{
RSEN=1;
while(RSEN);
}

void I2C_Stop()
{
PEN=1;
while(PEN);
}

int I2C_Read(unsigned char ack)
{
unsigned char I2CReadData;

RCEN=1;
while(RCEN);
I2CReadData=SSPBUF;
if(ack)
{
ACKDT=0;
}
else
{
ACKDT=1;
}

ACKEN=1;
while(ACKEN);
return(I2CReadData);
}

unsigned char I2C_Write(unsigned char I2CWriteData)
{
SSPBUF=I2CWriteData;
while(RW);
return(!ACKSTAT);
}


//----------------24c02--------------------------------
void write_ext_eeprom(unsigned char address, unsigned char data)
{
I2C_Start();
I2C_Write(0b10100000); //A2~A0:000, R/W=0
I2C_Write(address);
I2C_Write(data);
I2C_Stop();
delay(150); //计⊿糶礚猭タ盽禲
}

unsigned char read_ext_eeprom(unsigned char address)
{
unsigned char data;

I2C_Start();
I2C_Write(0b10100000); //A2~A0:000, R/W=0
I2C_Write(address);
I2C_RptStart();
I2C_Write(0b10100001); //A2~A0:000, R/W=1
data=I2C_Read(0);
I2C_Stop();
return(data);
}

//----------------delay--------------------------------
void delay(int num)
{
int aa,bb;
aa=num;
while(aa)
{
bb=num;
while(bb)
{bb--;}
aa--;
}
}

ㄓ http://www.microchip.com.tw/newbb/viewtopic.php?forum=1&topic_id=22254&post_id=77951