標(biāo)題: 求前輩幫我檢查檢查這個I2C的程序、、幫我看看錯在那 [打印本頁]

作者: 狼的救贖    時間: 2014-10-25 21:03
標(biāo)題: 求前輩幫我檢查檢查這個I2C的程序、、幫我看看錯在那
#include<reg52.h>
#include<intrins.h>
#define _nop()  _nop_()
#define uchar unsigned char

sbit sda=P2^2;
sbit scl=P2^3;

bit ack;

void delayus(uchar t);
void delayms(uchar t);

void delayus(uchar t)
{
while(--t);
}

void delayms(uchar t)
{
while(t--)
  {
  delayus(245);
  delayus(245);
  }
}

void start()
{
sda=1;
_nop();
scl=1;
_nop();
_nop();
_nop();
_nop();
_nop();
sda=0;
_nop();
_nop();
_nop();
_nop();
_nop();
scl=0;
_nop();
_nop();
}

void stop()
{
sda=0;
_nop();
_nop();
scl=1;
_nop();
_nop();
_nop();
_nop();
_nop();
sda=1;
_nop();
_nop();
_nop();
_nop();
_nop();
}

void ACK_T(void)
{
sda=0;
_nop();
_nop();
_nop();
scl=1;
_nop();
_nop();
_nop();
_nop();
_nop();
scl=0;
_nop();
_nop();
}

void NOACK(void)
{
sda=1;
_nop();
_nop();
_nop();
scl=1;
_nop();
_nop();
_nop();
_nop();
_nop();
scl=0;
_nop();
_nop();
}

void write(uchar c)
{
uchar i,temp;
temp=c;
scl=0;
for(i=0;i<8;i++)
{
  temp=temp<<1;
  sda=CY;
  _nop();
  scl=1;
  _nop();
  _nop();
  _nop();
  _nop();
  _nop();
  scl=0;
}
_nop();
_nop();
sda=1;
_nop();
_nop();
scl=1;
_nop();
_nop();
_nop();
if(sda==0)ack=0;
else ack=1;
scl=0;
_nop();
_nop();

}

unsigned char read()
{
unsigned char i;
uchar j;
uchar k;
scl=0;
for(i=0;i<8;i++)
{
j=sda;
k=(k<<1)|j;
scl=1;
_nop();
_nop();
_nop();
_nop();
_nop();
scl=0;
_nop();
_nop();
}
scl=0;
_nop();
_nop();
return (k);
}

bit write_string(uchar duxie,uchar dizhi,uchar *s,uchar geshu )
{
uchar b;
start();
write(duxie);
if(ack==0)return(0);
write(dizhi);
if(ack==0)return(0);
for(b=0;b<geshu;b++)
{
  write(*s);
  if(ack==0)return(0);
  s++;
}
stop();
return(1);
}

bit read_string(uchar duxie,uchar dizhi,uchar *s,uchar geshu )
{
uchar b;
start();
write(duxie);
if(ack==0)return(0);
write(dizhi);
if(ack==0)return(0);
for(b=0;b<geshu;b++)
  {
  *s=read();
  ACK_T();
  s++;
  }
  *s=read();
  NOACK();
  stop();
  return(1);
}

void main()
{
uchar a;
a=0xaa;

  write_string(0xae,80,&a,1);
  delayus(1000);
  read_string(0xaf,80,&a,1);
  while(1)
{
  P1=a;

}
}



作者: 狼的救贖    時間: 2014-10-25 21:25
點不亮LED,問題出在哪!




歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1