標題: 51單片機i2c協(xié)議示例程序 [打印本頁]

作者: fangyangas1    時間: 2016-10-13 11:15
標題: 51單片機i2c協(xié)議示例程序
#include<reg52.h>
#include<intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit sda=P3^5;
sbit scl=P3^4;
void start_bit();
void stop_bit();
void slave_ack();
void no_ack();
void write_byte(uchar dat);
uchar read_byte();
void write_date(uchar addr,uchar date);
uchar read_date(uchar addr);
void delay(uint x);
void main()
{
       ucharnum;
       write_date(0x01,0xaa);
       delay(2);
       num=read_date(0x01);
       P0=num;
       while(1);
                     
}
void start_bit()                //開始位
{
       scl=1;
       _nop_();
       sda=1;
       _nop_();
       sda=0;
       _nop_();
       scl=0;      
}
void stop_bit()                     //停止位
{
       sda=0;
       _nop_();
       scl=1;
       _nop_();
       sda=1;
}
void slave_ack()            //應答信號
{
       _nop_();
       _nop_();
       scl=0;
       _nop_();;
       sda=1;
       _nop_();
       _nop_();
       scl=1;
       _nop_();
       _nop_();
       while(sda);
       //P0=0xfe;
       scl=0;
}
void no_ack()          //無應答
{
       sda=1;
       _nop_();
       scl=1;
       _nop_();
       scl=0;
}
void write_byte(uchar dat)       //寫一個字節(jié)
{
       uchari;
       scl=0;
       for(i=0;i<8;i++)
       {
              if(dat&0x80)
                     sda=1;
              else
                     sda=0;
              scl=1;
              dat<<=1;
              scl=0;
       }
}
uchar read_byte()                  //讀一個字節(jié)
{
       uchari,dat=0;
       sda=1;
       for(i=0;i<8;i++)
       {     
              dat<<=1;
              scl=1;
              if(sda==1)
                     dat|=0x01;
               scl=0;
                    
       }
       returndat;
}
void write_date(uchar addr,uchar date)        //在指定地址寫一個字節(jié)
{
       start_bit();
       write_byte(0xa0);
       slave_ack();   
       write_byte(addr);
      
       slave_ack();
       write_byte(date);
       slave_ack();
       stop_bit();
       delay(100);
}
uchar read_date(uchar addr)                //指定位置讀一個字節(jié)
{
       uchardate;
       start_bit();
       write_byte(0xa0);
      
       slave_ack();
      
       write_byte(addr);
       slave_ack();
       start_bit();
       write_byte(0xa1);
       slave_ack();
       date=read_byte();
       no_ack();
       stop_bit();
       returndate;
}
void delay(uint x)
{
       uinti,j;
       for(i=x;i>0;i--)
              for(j=0x40;j>0;j--);
}






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