8051 - I2C BitBang

时间:2017-06-01 13:19:29

标签: i2c 8051

我正在使用I2C bitbang,我正面临着一个问题。我想我需要SCL和SDA线之间的延迟。我不知道延迟需要多少。 有人可以检查我的I2C代码,看看是否一切都检查出来?我想确保它不是软件错误。

#include <at89c51ic2.h>
#include <stdio.h>

#define SDA P0_0
#define SCL P0_1

void I2CInit(){
    SDA = 1;
    SCL = 1;
}
void I2CStart(){
    SCL = 1;
    I2CDelay();
    SDA = 0;
    I2CDelay();
    SCL = 0;
    I2CDelay();
}
void I2CRestart(){
    SDA = 1;
    SCL = 1;
    SDA = 0;
    SCL = 0;
}
void I2CStop(){
    SDA = 0;
    I2CDelay();
    SCL = 1;
    I2CDelay();
    SDA = 1;
    I2CDelay();
}
void I2CAck(){
    I2CDelay();
    SDA = 0;
    I2CDelay();
    SCL = 1;
    I2CDelay();
    SCL = 0;
    I2CDelay();
    SDA = 1;
    I2CDelay();
}
void I2CNak(){
    SDA = 1;
    SCL = 1;
    SCL = 0;
    SDA = 1;
} 
void I2CSend(unsigned char Data){
    unsigned char i;
    for (i = 0; i < 8; i++) {
        if ((Data & 0x80) == 0)
            SDA = 0;
        else
            SDA = 1;
        SCL = 1;
        I2CDelay();
        SCL = 0;
        I2CDelay();
        Data <<= 1;
    }
    SDA = 1; 
    I2CDelay();
    SCL = 1;
    I2CDelay();
    if (SDA)
        SCL = 0;
    I2CDelay();
    SDA = 1;
    SCL = 1;
    }

char I2CRead(unsigned char lastone){ // last one == 1 for last byte; 0 for any other byte
    char i, Data=0;
    for (i = 0; i < 8; i++){
        SCL = 1;
        I2CDelay();
        if(SDA) Data |=1;
        if(i<7) Data<<=1;
        SCL = 0;
        I2CDelay();
}
    SDA = lastone;
    SCL = 1;
    I2CDelay();
    SCL = 0;
    SDA = 1;
    SCL = 1;
    I2CDelay();
    return Data;
}

void I2CSendAddr(unsigned char addr, unsigned char rd){
    I2CStart();
    I2CSend(addr+rd);
}
void I2CDelay(){
    unsigned int i;
    for (i = 0; i < 4000; i++);
    return;
}

0 个答案:

没有答案