/* ************************************************** *本实验是利用I2C先把信息写入EEPROM,然后再读出写到 *内存中,通过WATCH查看是否正确 *本程序用AVR STUDIO+WINAVR编译 ************************************************** */ #include #include #include /* ************************************************** *TWCR *+-----+-----+-----+-----+-----+-----+-----+-----+ *| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | *+-----+-----+-----+-----+-----+-----+-----+-----+ *|TWINT|TWEA |TWSTA|TWSTO|TWWC |TWEN | - |TWIE | *+-----+-----+-----+-----+-----+-----+-----+-----+ ************************************************** */ typedef unsigned char U8; #define BIT(x) BIT[x] const U8 BIT[8]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; U8 buff[50]={"SUCCESS! Mr. Yang!"}; /* ************************************************** *暂停的时间太短,有的字符会错误写入或读出 ************************************************** */ void shortdelay() { short i=2048; while(i--) { } } /* ************************************************** * ************************************************** */ void twi_init() { /* DDRC&=0XCF;//使能内部的上拉电阻 PORTC|=0X30;//使能内部的上拉电阻 */ TWBR = 5; TWSR&=0xfe; TWCR=0x84; } U8 twi_start() { TWCR=(BIT(TWINT)|BIT(TWEN)|BIT(TWSTA)); while((TWCR&0x80)==0); return(TWSR&0xf8); } void twi_stop() { TWCR=(BIT(TWINT)|BIT(TWEN)|BIT(TWSTO)); } /*写一字节*/ U8 twi_putbyte(U8 ch) { TWDR=ch; TWCR=BIT(TWINT)|BIT(TWEN); while((TWCR&0x80)==0); shortdelay(); return(TWSR&0xf8); } /*读一字节 opt:0时发NACK,1时发ACK*/ U8 twi_getbyte(U8 *ch,U8 opt) { switch(opt) { case 0: TWCR=BIT(TWINT)|BIT(TWEN); break; default: TWCR=BIT(TWEA)|BIT(TWINT)|BIT(TWEN); break; } while((TWCR&BIT(TWINT))==0); *ch=TWDR; return (TWSR&0XF8); } /*addr:0~2K*/ void twi_puts(U8 addr,U8 *str) { while(*str) { twi_start(); twi_putbyte(0xa0); twi_putbyte(addr); twi_putbyte(*str); twi_stop(); addr++; str++; } } void twi_gets(U8 addr,U8 len,U8 *str) { twi_start(); twi_putbyte(0xa0); twi_putbyte(addr); twi_stop(); twi_start(); twi_putbyte(0xa1); while(--len) { twi_getbyte(str++,1); } twi_getbyte(str,0); twi_stop(); } int main() { MCUCR=0x00; cli(); //disable all interrupts DDRD=0xff; PORTD=0xff; twi_init(); twi_puts(0,&buff[0]); twi_gets(0,18,&buff[25]); return 0; }