کد:
#include<mega16.h>
#define xtal 1000000
#include <stdio.h>
/* the I2C bus is connected to PORTB */
/* the SDA signal is bit 3 */
/* the SCL signal is bit 4 */
#asm
.equ __lcd_port=0x12
#endasm
#include <lcd.h>
#asm
.equ __i2c_port=0x18
.equ __sda_bit=3
.equ __scl_bit=4
#endasm
/* now you can include the I2C Functions */
#include <i2c.h>
/* function declaration for delay_ms */
#include <delay.h>
#define EEPROM_BUS_ADDRESS 0xa0
/* read a byte from the EEPROM */
unsigned int eeprom_read(unsigned int address) {
unsigned int data;
i2c_start();
i2c_write(EEPROM_BUS_ADDRESS);
i2c_write((address&0xff00)>>8);
i2c_write(address&0x00ff);
i2c_start();
i2c_write(EEPROM_BUS_ADDRESS | 1);
data=i2c_read(0);
i2c_stop();
return data;
}
/* write a byte to the EEPROM */
void eeprom_write(unsigned int address, unsigned int data) {
i2c_start();
i2c_write(EEPROM_BUS_ADDRESS);
i2c_write((address&0xff00)>>8);
i2c_write(address&0x00ff);
i2c_write((data&0xff00)>>8);
i2c_write(data&0x00ff);
i2c_stop();
/* 10ms delay to complete the write operation */
delay_ms(10);
}
void main(void)
{
unsigned int i;
char buffer[20];
unsigned int a;
unsigned int address;
unsigned int data_ir;
address=0x01;
data_ir=0x01;
lcd_init(16);
lcd_clear();
lcd_gotoxy(0,0);
lcd_putsf(" EEPROM");
delay_ms(1000);
for(a=0;a<65000;a++,address++,data_ir++){
/* initialize the I2C bus */
i2c_init();
/* write the byte 55h at address 10h */
eeprom_write(address,data_ir);
/* read the byte from address AAh */
i=eeprom_read(address);
lcd_clear();
sprintf(buffer,"add=%d",i);
lcd_puts(buffer);