本帖最后由 鼹鼠 于 2013-11-14 23:58 编辑
#include<reg52.h>
#include<INTRINS.H>
typedef unsigned char uint8;
typedef unsigned int uint16;
typedef unsigned long uint32;
sbit SCL = P3^7;
sbit SDA = P3^6;
void Delay(void)
{
_nop_();
_nop_();
_nop_();
_nop_();
}
void InitI2C(void)
{
SDA = 1;
SCL = 1;
}
void I2CStart(void)
{
SDA = 1;
Delay();
SCL = 1;
Delay();
SDA = 0;
Delay();
SCL = 0;
}
void I2CStop(void)
{
SCL = 0;
Delay();
SDA = 0;
Delay();
SCL = 1;
Delay();
SDA = 1;
Delay();
}
void I2CSend(uint8 byte)
{
uint8 mask;
uint8 i,j;
mask = 0x80;
for(i = 0;i < 8;i--)
{
SCL = 0;
Delay();
if((mask & byte) == 0)
{
SDA = 0;
}
else
{
SDA = 1;
}
mask >>= 1;
Delay();
}
SCL = 0;
SDA = 1;
Delay();
SCL = 1;
j = SDA;
Delay();
SCL = 1;
}
uint8 I2CRead(void)
{
uint8 byte;
uint8 i;
byte = 0;
for(i = 0;i < 8;i--)
{
SCL = 0;
SDA = 1;
Delay();
SCL = 1;
Delay();
byte <<= 1;
if(SDA == 1)
{
byte |= 0x01;
}
Delay();
}
SCL = 0;
SDA = 1;
Delay();
SCL = 1;
Delay();
SCL = 0;
return byte;
}
uint8 I2CReadAck(void)
{
uint8 i;
uint8 byte;
byte = 0;
for(i = 0;i < 8;i--)
{
SCL = 0;
SDA = 1;
Delay();
SCL = 1;
Delay();
byte <<= 1;
if(SDA == 1)
{
byte |= 0x01;
}
Delay();
}
SCL = 0;
Delay();
SDA = 0;
Delay();
SCL = 1;
Delay();
SCL = 0;
return byte;
}
uint8 read_eeprom(uint8 addr)
{
uint8 databyte;
I2CStart();
I2CSend(0xa0);
I2CSend(addr);
I2CStart();
I2CSend(0xa1);
databyte = I2CRead();
I2CStop();
return databyte;
}
void write_eeprom(uint8 addr,uint8 databyte)
{
I2CStart();
I2CSend(0xa0);
I2CSend(addr);
I2CSend(databyte);
I2CStop();
}
void UART_init(void)
{
SCON = 0X50;
TMOD &= 0X0F;
TMOD |= 0X20;
TH1 = 0XFD;
TL1 = 0XFD;
TR1 = 1;
}
void UART_send_byte(uint8 dat)
{
SBUF = dat;
while(!TI);
TI = 0;
}
void main(void)
{
uint8 addr = 0x00,databyte = 0xe4;
uint8 c = 0;
uint16 i;
UART_init();
InitI2C();
while(1)
{
write_eeprom(addr,databyte);
for(i = 0;i < 1000;i++)
{
Delay();
}
c = read_eeprom(addr);
UART_send_byte(c);
addr++;
databyte++;
if(addr == 0xff)
{
addr = 0;
}
if(databyte == 0xff)
{
databyte = 0;
}
for(i = 0;i < 1000;i--)
{
Delay();
}
}
}
这个是主程序。。。新手求大神!!! |