I2C总线驱动代码

通过上篇对I2C总线的介绍,那面,接下来就需要软件部分针对I2C总线的编程实现。


具体细细道来,(前提是,已经找好两个IO口分别为SDA SCL)

1.1st function: I2c start

void IIC_Start(void)
{
    SDA_OUTPUT();
    SET_SDA();
    usleep(4);
    SET_SCL();
    usleep(6);
    CLR_SDA();          
    usleep(4); 
}
2. 2nd :I2c stop

void IIC_Stop (void)
{
    usleep(4);
    CLR_SCL();
    usleep(4);
    SDA_OUTPUT();
    usleep(4);
    CLR_SDA();
    usleep(4);
    SET_SCL();
    usleep(4);
    SET_SDA();
    usleep(4);
}


3. 3rd:ACK

void I2C_ACK(uint8_t ack)
{
    CLR_SCL();
    SDA_OUTPUT();
	usleep(2); 
	if (ack)
	{
		SET_SDA();
	}
	else
	{
		CLR_SDA();
	}
	usleep(2); 
    SET_SCL();
	usleep(4); 
    CLR_SCL();
	usleep(4); 
}

4. 4th :send one byte

void IIC_Byte_send (unsigned char data)
{
    int j;
    for ( j = 0; j < 8; j++ )
    {
		usleep(4); 
		CLR_SCL();
		usleep(2);
        if ( data & 0x80 )  SET_SDA();
        else  CLR_SDA();
        data <<= 1;
        usleep(2);
        SET_SCL();        
    }
	usleep(4);
}

5. 5th: receive one byte

void IIC_Byte_receive (unsigned char *data)
{
    int j;
    unsigned char tmp=0x00;

	CLR_SCL();
    for( j = 0 ; j < 0x08 ; j++)
    {		
    	tmp <<=1;
        usleep(4);
        SET_SCL();
        usleep(2);
        if (TST_SDA())  tmp += 1;
        usleep(2);
        CLR_SCL();
    }
	usleep(4);      
    *data = tmp;
}
6. 6th:send byte and wait ACK

int I2C_Send_data_Wait_ack(unsigned char data)
{
    IIC_Byte_send(data); //IIC send one byte
    CLR_SCL();              // high clock cycle
    SDA_INPUT();
    usleep(4);
    SET_SCL();
    usleep(4);
    if (0x00 == TST_SDA() )                 //ACK
    { 
        usleep(4);
        CLR_SCL();
        usleep(4);
        SDA_OUTPUT();  
        SET_SDA();         
        usleep(4); 
    }
    else
    {          
        IIC_Stop();//NoACK
        SET_SCL();
        return(0);
    }
    return(1);
}


构建完这6个函数,I2C驱动还有什么理由通信不了呢?


当然了,大神们可能各有各的办法。小弟这里也只是抛砖引玉罢了。。。。。



你可能感兴趣的:(硬件电路)