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;
 }
}
asked Dec 16, 2017 at 9:27
1
  • 1
    You can have multiple returns. Some people disagree on style grounds, but it works as intended. Commented 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!

answered Dec 16, 2017 at 9:37
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.