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;
}
}
-
1You can have multiple returns. Some people disagree on style grounds, but it works as intended.user31481– user314812017年12月16日 09:37:29 +00:00Commented Dec 16, 2017 at 9:37
1 Answer 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
lang-c