⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 iic.c

📁 有急于51单片机IIC的操作讲解
💻 C
字号:
#include<reg52.h>                   //52系列单片机定义文件

#define uchar unsigned char
sbit iic_sda = P1^0;
sbit iic_scl = P1^1;



void delay(uchar x)
{
    while(x--);
}

/*start condition*/
void iic_start()
{
    iic_scl = 1;
    iic_sda = 1;        
    iic_sda = 0;  
    iic_scl = 0;	
}

/*stop condition*/
void iic_stop()
{
    iic_scl = 1;    
    iic_sda = 0;  
    iic_sda = 1;  
    iic_scl = 0;
}

/*acknowledge*/
void iic_response(void ) 
{
    iic_sda = 0;        //lower the level
	iic_scl = 1;   
	iic_scl = 0;	 	
}

/*write operation*/
void iic_writebyte(uchar dat)
{
    uchar i;
    for(i = 0;i < 8;i++)
    {        
        iic_scl = 0;
        iic_sda = (bit)(dat & 0x80);
        dat <<= 1;
        iic_scl = 1;
    }
    iic_scl = 0;
    
}

/*read operation*/
uchar iic_readbyte()
{
    uchar i,dat;
    dat = 0;
    iic_sda = 1;
    for(i = 0;i < 8;i++)
    {
        iic_scl = 0;
        iic_scl = 1;
        dat <<= 1;
        if(iic_sda)
        {
            dat++;
        }                      
    }
    iic_scl = 0;
    delay(50);
    return(dat);                      
}


void main()
{
    uchar d=0;
    iic_start();            //start at24c02
    iic_writebyte(0xa0);    //the command of write at24c0
    iic_response();         //acknowledge
    iic_writebyte(0x10);    //word address
    iic_response();
    iic_writebyte(0x25);    //sent data to at24c02
    iic_response();
    iic_stop();             //stop operation
    delay(100);            
    iic_start();            //start at24c02
    iic_writebyte(0xa0);    //the command of write at24c0
    iic_response();         //acknowledge
    iic_writebyte(0x10);    //word address
    iic_response(); 
    iic_stop();  
    iic_start();
    iic_writebyte(0xa1);    //device address and  the command of read from at24c02
    iic_response();
    d = iic_readbyte();     //read from at24c02
    iic_response();
    iic_stop();              //stop here   
    while(1);
}
           

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -