if(!) statements with radio.write()

Hi,

I'm making a project with nrf24l01+ chips.
I've seen example code for these using the statement:

if( !radio.write(&data, sizeof(data)){
   Serial.println("No signal from rx");
}

But in that code it doesn't tell the arduino to radio.write() before this if() statement.

What does the if() statement here actually do? Does it perform the radio.write() and then perform the Serial.println only if it returns false? Alternatively, do you need to have already performed radio.write() and then this if() statement takes the value of this(like below)?

radio.write(&data, sizeof(data));
if( !radio.write(&data, sizeof(data)){
   Serial.println("No signal from rx");
}

I was thinking it wouldn't be this because I believe the radio.write() function will not let you move on unless it receives acknowledgement, so you'd never actually reach the if() statement it did return false?

Sorry I know I've convoluted that question.
Thanks in advance

Does it perform the radio.write() and then perform the Serial.println only if it returns false?

Yes. It’s that simple. Trying to get inside your confused mind… the ‘if’ code block begins with the ‘{’ not the ‘if’, so if you thought it would have to “go back to the if” or something like that, absolutely no.

The write() function should return the number of bytes written, so the if condition is true if no bytes are written.

int was_succesful = radio.write(&data, sizeof(data)); //Attempt to write. In case we fail, write() will return 0.
if(!was_succesful){ //Check how it went and print the message if we failed to write.
   Serial.println("No signal from rx");
}

This code will behave the same way as the first one you posted.

aarg:
Yes. It's that simple. Trying to get inside your confused mind... the 'if' code block begins with the '{' not the 'if', so if you thought it would have to "go back to the if" or something like that, absolutely no.

Thanks that's cleared that up.

kubajz22:

int was_succesful = radio.write(&data, sizeof(data)); //Attempt to write. In case we fail, write() will return 0.

if(!was_succesful){ //Check how it went and print the message if we failed to write.
  Serial.println("No signal from rx");
}




This code will behave the same way as the first one you posted.

Thanks a lot that's exactly what I was looking for. Glad you could understand what I was asking :slight_smile:
Much appreciated

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.