atmega16有硬件IIC(TWI)接口,不需模仿,直接操作寄存器即可
#include
#include
#define uchar unsigned char
#define uint unsigned int
#define Start() TWCR|=(1<#define Stop() TWCR|=(1<//停止信号
#define Wait() while(!(TWCR&(1<//等候数据发送完
#define Test() (TWSR&0XF8)//查看twsr的状况码
#define Write(X) {TWDR=X;TWCR=(1<//写字节
#define Read() TWCR|=(1<//读字节
extern const uchar table[]={
~0x3f,~0x06,~0x5b,~0x4f,
~0x66,~0x6d,~0x7d,~0x07,
~0x7f,~0x6f,~0x77,~0x7c,
~0x39,~0x5e,~0x79,~0x71};
void delay(uint t)
{
uint i,j;
for(i=0;i<10;i++)
for(j=0;j}
void init()
{
TWSR=0;
TWBR=0X23;
TWCR=0X44;
}
//能够经过读出Test()来看TWSR处于什么状况,也能够不必运用Test()
uchar write()
{
Start();
Wait();
//if(Test()!=0x08)
//return 0;
Write(0xa0);
Wait();
if(Test()!=0x18)
return 0;
Write(3);
Wait();
//if(Test()!=0x28)
//return 0;
Write(56);
Wait();
// if(Test()!=0x28)
// return 0;
Stop();
delay(1000);
}
uchar read()
{
uchar dat;
TWSR=0;
Start();
Wait();
//if(Test()!=0x08)
// return 0;
Write(0xa0);
Wait();
//if(Test()!=0X18)
//return 0;
Write(3);
Wait();
// if(Test()!=0x28)
// return 0;
Start();
Wait();
// if(Test()!=0x10)//这儿有必要写10,由于是第2次开端
// return 0;
Write(0xa1);
Wait();
if(Test()!=0x40)
return 0;
Read();
Wait();
// if(Test()!=0x58)//读完无应答
// return 0;
dat=TWDR;
Stop();
}
void main()
{
uchar z,shi,ge;
init();
write();
z=read();
DDRA=0XFF;
shi=z/10;
ge=z;
while(1) {
PORTB=0xfe;
PORTA=table[shi];
delay(10);
PORTB=0xfd;
PORTA=table[ge];
delay(10);
}
}
声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/news/guandian/257946.html