0

I have Arduino Mega and Weather Shield. I want to calculate wind speed.

float get_wind_speed()
{

float deltaTime = millis() - lastWindCheck; //750ms 

deltaTime /= 1000.0; 

  float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4

  windClicks = 0; //Sıfırla ve yeni oluşan rüzgarı izle
  lastWindCheck = millis();

  windSpeed *= 1.492; //4 * 1.492 = 5.968MPH

 Serial.println();
 Serial.print("Windspeed :");
 Serial.println(windSpeed);

 return(windSpeed);
}

But when I run my code I see two windspeed value. First one is windspeed=0.0 or any value. Second one is windspeed=nan.

How can I make it better?

1

When debugging a problem like this one, print out values of the variables that the calculation depends on.

In this case, you may find that both windClicks and deltaTime are 0 or 0.0. The IEEE 754 floating-point-operations specification dictates a result of NaN (not-a-number) for various zero over zero calculations. It dictates a result of +Inf or -Inf for calculations like 7/0.0 or -13/0.0. [See, for example, the stackoverflow question, Why does division by zero with floating point (or double precision) numbers not throw an exception.]

If arithmetic generates a NaN or +Inf result, subsequent arithmetic using that result will also produce NaN or +Inf results.

To deal with the problem, you could use deltaTime > 0 as a required pre-condition for calculation of windSpeed. That is, have an if-statement protecting the calculation block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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