Interesting "if" behaviour.

This is part of a sketch:

void loop()
{
  servoinPWM = pwmread(servoin);
  if(servoinPWM > 0);
  {
    Serial.println(servoinPWM);
  }
}

servoinPWM is an unsigned int.
servoin is a byte.

The subroutine pwmread() reads the duration of the incoming pwm signal (just a replacement for pulseIn() function but with 1 microsecond resolution).

My question is:
How can I get "0" printed to the serial port with this sketch? It should be impossible (the if statement should prevent a "0" being printed) but it occurs!

The algorith should be like this:

  • Read pwm signal
  • If it is not zero, print it to the serial port
  • If it is zero continue with the loop

What am I doing wrong??? Any ideas are welcome.

Is it printing 0 or '0', i.e. the ASCII equivalent to zero. If so bad luck to you!

You have a semicolon on the end of your if statement. That terminates the if block. Everything after that is going to be executed unconditionally.

Man, I have to start looking for those. There seems to be a rash of them lately.

KeithRB:
Man, I have to start looking for those. There seems to be a rash of them lately.

Simple solution
if( condition) …
MAY stop you from doing what everybody does once a while .
Just let the compiler evaluate without explicit check for ZERO, it is ONE of the few things “automation” is beneficial.

Vaclav:
Simple solution
if( condition) .....
MAY stop you from doing what everybody does once a while .
Just let the compiler evaluate without explicit check for ZERO, it is ONE of the few things "automation" is beneficial.

In this case no, because the following that advice, the OP would have written:

if(servoinPWM);

which doesn't remove the error.

Delta_G:
You have a semicolon on the end of your if statement. That terminates the if block. Everything after that is going to be executed unconditionally.

Oh my God!

Quote from Einstein: "Two Things Are Infinite: the Universe and Human Stupidity"

I am very sorry for wasting your time. But mistakes like these are sometimes not easy to see, especially if it is your own code.

Thank you very much...

Had the OP used the auto format tool he would have seen the error!

Mark

OP: These are what I call "flat forehead mistakes". It's where you see the error and then slam the heel of your hand to your forehead, saying something like: "How could I be so stupid?" Relax, most of us have fairly flat foreheads and you should expect your fair share. The good news is that it's unlikely you'll make this mistake again. The bad news is that you'll move on to more sophisticated bugs down the road. It's process we all go (went?) through.