AVR单片机硬件I2C接口驱动程序
程序功能:先由atmega16向EEPROM中某地址写数字71,然后再从EEPROM里读出来显示到数码管上;
#include
#include avrdef.h>
unsigned charconstduacode[]={0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71}; //0-f 数字模*/
void delay(unsigned int);
void display(unsigned int);
void send1byte(unsigned char address,unsigned char data);
unsigned char read1byte(unsigned char address);
#define START TWCR=BIT(7)|BIT(5)|BIT(2)
#define STOP TWCR=BIT(7)|BIT(4)|BIT(2)
#define WRITE(x) {TWDR=x; TWCR=BIT(7)|BIT(2);}
void main()
{unsigned char i=0;
DDRC=0xff;
while(1)
{
send1byte(4,71);
i=read1byte(4);
display(i);
}
}
void send1byte(unsigned char address,unsigned char data)
{
START;
while(!(TWCR&0x80));
WRITE(0xa0);
while(!(TWCR&0x80));
WRITE(address);
while(!(TWCR&0x80));
WRITE(data);
while(!(TWCR&0x80));
STOP;
delay(2);
}
unsigned char read1byte(unsigned char address)
{
unsigned char temp;
START;
while(!(TWCR&0x80));
WRITE(0xa0);
while(!(TWCR&0x80));
WRITE(address);
while(!(TWCR&0x80));
START;
while(!(TWCR&0x80));
WRITE(0xa1);
while(!(TWCR&0x80));
TWCR=BIT(7)|BIT(2);
while(!(TWCR&0x80));
temp=TWDR;
STOP;
return temp;
}
void display(unsigned int dat)
{
unsigned char a[4],i;
for(i=0;i<4;i++)
{
a[3-i]=dat%10;
dat/=10;
}
DDRB=0xff; DDRD=0xff;
for(i=0;i<4;i++)
{
PORTB=duacode[a[i]];
PORTD&=~BIT(i);
delay(10);
PORTD|=BIT(i);
}
}
void delay(unsigned int x)
{
unsigned int a; unsigned char b;
for(a=x;a>0;a--)
for(b=100;b>0;b--);
}
AVR单片机I2C接口驱动程 相关文章:
- Windows CE 进程、线程和内存管理(11-09)
- RedHatLinux新手入门教程(5)(11-12)
- uClinux介绍(11-09)
- openwebmailV1.60安装教学(11-12)
- Linux嵌入式系统开发平台选型探讨(11-09)
- Windows CE 进程、线程和内存管理(二)(11-09)