Proteus仿真时可以,实际操作时能写不能读。请帮忙看看。
编译器用sdcc 3.4
/**<
* \fn i2c_write_byte(c)
* \brief Writes a byte to device.
* \param c data
*/
void i2c_write_byte(uint8 c)
{
uint8 i;
for (i = 0; i < 8; i++) {
set_sda(c & 0x80);
set_scl_high();
delay_4us();
c <<= 1;
set_scl_low();
delay_4us();
}
}
/**<
* \fn i2c_read_byte()
* \brief Reads a byte from device.
* \return Returned data.
*/
uint8 i2c_read_byte(void)
{
uint8 i, c = 0;
for (i = 0; i < 8; i++) {
set_scl_high();
delay_4us();
c <<= 1;
c |= get_sda();
set_scl_low();
delay_4us();
}
return c;
}
uint8 pcf8574_write_port(uint8 slave, uint8 bits)
{
uint8 ret = 1;
/* START condition.
*/
set_sda_high();
set_scl_high();
delay_4us();
set_sda_low();
delay_4us();
set_scl_low();
delay_xms(5);
///< SLAVE address.
i2c_write_byte(0x40 | (slave & 0x07) << 1);
/**< ACK condition.
*/
set_sda_high();
delay_4us();
set_scl_high();
delay_4us();
ACC = get_sda();
set_scl_low();
delay_4us();
if (ACC)
goto __i2c_write_finish;
delay_xms(5);
i2c_write_byte(bits);
/**< ACK condition.
*/
set_sda_high();
delay_4us();
set_scl_high();
delay_4us();
ACC = get_sda();
set_scl_low();
delay_4us();
if (ACC)
goto __i2c_write_finish;
ret = 0;
__i2c_write_finish:
delay_xms(5);
/**< STOP condition.
*/
set_sda_low();
delay_4us();
set_scl_high();
delay_4us();
set_sda_high();
delay_xms(30);
return ret;
}
uint8 pcf8574_read_port(uint8 slave, uint8 *out)
{
uint8 ret = 1;
/**< START condition.
*/
set_sda_high();
set_scl_high();
delay_4us();
set_sda_low();
delay_4us();
set_scl_low();
delay_xms(5);
///< SLAVE address.
i2c_write_byte(0x41 | (slave & 0x07) << 1);
/**< ACK condition.
*/
set_sda_high();
delay_4us();
set_scl_high();
delay_4us();
ACC = get_sda();
set_scl_low();
delay_4us();
if (ACC)
goto __i2c_read_finish;
delay_xms(5);
*out = i2c_read_byte();
/**< NAK condition.
*/
set_sda_high();
set_scl_high();
delay_4us();
set_scl_low();
set_sda_low();
delay_4us();
ret = 0;
__i2c_read_finish:
delay_xms(5);
/**< STOP condition.
*/
set_sda_low();
delay_4us();
set_scl_high();
delay_4us();
set_sda_high();
delay_xms(30);
return ret;
}
|