static uint8_t I2CGetByte(uint8_t lastbyte, uint8_t * Data) { uint8_t abyte = 0; uint8_t i; for (i = 0; i < 8; i++) //get each bit, MSB first { if (SetSCLHigh()) return IIC_SCL_TIMEOUT; abyte <<= 1; //shift result over to make room for next bit if (GET_SDA()) abyte++; //same as 'abyte |= 1', only faster CLEAR_SCL(); } if (lastbyte) SET_SDA(); //do not ACK last uint8_t read else CLEAR_SDA(); if (SetSCLHigh()) return IIC_SCL_TIMEOUT; CLEAR_SCL(); SET_SDA(); *Data = abyte; return IIC_OK; }
static uint8_t i2c_soft_receive_bit(void) { // SDA = 1 // SCL = 1 // wait SCL low // bit = SDA // SCL = 0 uint8_t bit; SDA(1); waitSomeTimeInUs(1); SCL1(); waitSomeTimeInUs(1); while( GET_SCL() == 0); bit = GET_SDA(); SCL0(); SDA_OUTPUT(); waitSomeTimeInUs(1); return bit; }
/*--------------------------------------------------- int i2c_gpio_phase_start(); Generate i2c_gpio_phase_start Condition: Stream Format: SCL _____/--------\___ SDA =---------\_____ width (4.7u)4.7u|4.7u| Arguments: NONE Return value: int SUCCESS 0 int ERR_STATUS 1 ----------------------------------------------------*/ static RET_CODE i2c_gpio_phase_start(i2c_gpio_priv_t *p_priv) { /* Make sure is out */ SET_SDA_OUT(p_priv); SET_SCL_OUT(p_priv); SET_SDA_HI(p_priv); /* Set SDA high */ if(0 == GET_SCL(p_priv)) { I2C_GPIO_DELAY_US(p_priv->clock_period); } SET_SCL_HI(p_priv); /* Set SCL high */ I2C_GPIO_DELAY_US(p_priv->clock_period); if(0 == GET_SCL(p_priv)) { return ERR_STATUS; } if(0 == GET_SDA(p_priv)) { return ERR_STATUS; } SET_SDA_LO(p_priv); I2C_GPIO_DELAY_US(p_priv->clock_period); SET_SCL_LO(p_priv); return SUCCESS; }
//------------------------------------------------------------------------------ // Function: SendByte // Description: //------------------------------------------------------------------------------ static uint8_t I2CSendByte(uint8_t abyte) { uint8_t error = 0; uint8_t i; for (i = 0; i < 8; i++) { if (abyte & 0x80) SET_SDA(); //send each bit, MSB first else CLEAR_SDA(); if (SetSCLHigh()) //do clock cycle return IIC_SCL_TIMEOUT; CLEAR_SCL(); abyte <<= 1; //shift over to get next bit } SET_SDA(); //listen for ACK #if 1 if (SetSCLHigh()) return IIC_SCL_TIMEOUT; if (GET_SDA()) //error if no ACK { printk("IIC_NOACK\n"); error = IIC_NOACK; } #endif CLEAR_SCL(); return (error); //return 0 for no ACK, 1 for ACK received }
/*--------------------------------------------------- int i2c_gpio_phase_get_bit(id); Set a BIT (Hi or Low) Stream Format: SCL _____/---\ SDA ??AAAAAAAA width 4.7u| 4u| Arguments: NONE Return value: int i : Set(1) or Clear(0) this bit on iic bus ----------------------------------------------------*/ static int i2c_gpio_phase_get_bit(i2c_gpio_priv_t *p_priv) { int ret = 0; SET_SDA_IN(p_priv); SET_SDA_HI(p_priv); /* Hi Ind */ I2C_GPIO_DELAY_US(p_priv->clock_period); SET_SCL_HI(p_priv); I2C_GPIO_DELAY_US(p_priv->clock_period); ret = GET_SDA(p_priv); SET_SCL_LO(p_priv); return ret; }