0

I'm trying to fix my I2C code:

Is the following function correct because it has multiple returns. I don't know if that would work.

uint8_t I2C_rx(uint8_t ack_rx)
{
    uint8_t i;
    if (ack_rx)
    {
        TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA); // sending ACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
    else
    {
        TWCR = (1<<TWINT)|(1<<TWEN);           // sending NACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
}
1
  • 1
    You can have multiple returns. Some people disagree on style grounds, but it works as intended.
    – user31481
    Dec 16, 2017 at 9:37

1 Answer 1

1

No problem with multiple returns but it could be reduced to:

uint8_t I2C_rx(bool ack_rx)
{
  uint8_t cr = (1<<TWINT) | (1<<TWEN);
  if (ack_rx) cr |= (1<<TWEA);
  TWCR = cr;
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

or

uint8_t I2C_rx(bool ack_rx)
{
  TWCR = (1<<TWINT) | (1<<TWEN) | (ack_rx<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

Cheers!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.