代码:
#include
#include
#include
typedef unsigned char uchar;
typedef unsigned int uint;
#define EEPROM_BUS_ADDRESS 0xa0
#define TW_START 0X08
#define TW_MT_SLA_ACK 0X18
#define TW_MT_SLA_NACK 0X20
#define TW_MT_DATA_ACK 0X28
#define TW_MT_DATA_NACK 0X30
#define TW_MT_ARB_LOST 0X38
#define TW_MR_ARB_LOST 0X38
#define TW_MR_SLA_ACK 0X40
#define TW_MR_SLA_NACK 0X48
#define TW_MR_DATA_ACK 0X50
#define TW_MR_DATA_NACK 0X38
#define Page_size 64
#define Page_mask Page_size-1
void I2C_init(void)
{
TWSR=0;
TWBR=0;
TWAR=0;
TWCR=0X44;
}
uchar I2C_start(void)
{
TWCR=(1<1<1<while(!(TWCR&(1<return 1;
}
void I2C_stop(void)
{
TWCR=(1<1<1<uchar I2C_write(uchar c)
{
uchar ack=1;
TWDR=c;
TWCR=(1<1<while(!(TWCR&(1<if((TWSR&0xf8)!=TW_MT_SLA_ACK)
ack=0;
return ack;
}
uchar I2C_read(uchar ack)
{
if(ack)
TWCR=(1<1<1<else
TWCR=(1<1<while(!(TWCR&(1<return(TWDR);
}
void EEprom_Page_write(uint Addr,uchar n,uchar* arr)
{
uchar i;
I2C_start();
I2C_write(EEPROM_BUS_ADDRESS);
I2C_write(Addr>>8);
I2C_write(Addr);
for(i=1;i<=n;i++)
{
I2C_write(*arr);
arr++;
}
I2C_stop();
delay_ms(10);
}
void EEprom_write(uint Addr,uchar n,uchar* arr)
{
uchar n_tmp;
n_tmp=Page_size-(uchar)(Addr&Page_mask);
if((n>n_tmp)&&(n_tmp!=0))
{
EEprom_Page_write(Addr,n_tmp,arr);
Addr+=n_tmp;
n-=n_tmp;
arr+=n_tmp;
}
while(n>=Page_size)
{
EEprom_Page_write(Addr,Page_size,arr);
Addr+=Page_size;
n-=Page_size;
arr+=Page_size;
}
if(n!=0)
EEprom_Page_write(Addr,n,arr);
}
void EEprom_read(uint Addr,uchar n,uchar* arr)
{
uchar i;
I2C_start();
I2C_write(EEPROM_BUS_ADDRESS);
I2C_write(Addr>>8);
I2C_write(Addr);
I2C_start();
I2C_write(EEPROM_BUS_ADDRESS|1);
for(i=1;i<=n-1;i++)
{
*arr=I2C_read(1);
arr++;
}
*arr=I2C_read(0);
I2C_stop();
}
void main(void)
{
uchar i,data[200];
UCSRA=0;
UCSRB=0X18;
UCSRC=0X86;
UBRRH=0;
UBRRL=0X19;
I2C_init();
for(i=0;i<200;i++){data=i;}
EEprom_write(0x0aa,200,data);
for(i=0;i<200;i++){data=0;}
EEprom_read(0x0aa,200,data);
for(i=0;i<200;i++){putchar(data);}
while (1)
{
}
}
仿真效果:
文章评论(0条评论)
登录后参与讨论