'while' within 'if' statement

I have this piece of code;
if(t<(s-.5)){
while(t<(s+.5)){
double t=read_sensor();
double s=(p+2286)/127;
m=90;}
}
The program is stuck in the while loop even when t=29 and s=25. I feel that the closing 'if' bracket may be the problem. Had hoped to provide hysteresis for a temperature reading. Any suggestions?

Suggestion? Properly post the whole code.

Whole code is too long. It would take me forever to explain. I may just have to use a delay to turn off a device which is temperature dependent. Would have been neat to do a hysteresis solution. Need to stop oscillation around the temp turn off point.
I have seen others having the same problem in the past.

This is not the same variable 't' as in the while statement. Try removing the 'double' keyword. Also the 'if' statement is redundant.

Just above the 'if' statement is double t=read_sensor(); Also double s=(p+2286)/127. 't' and 's' are then defined for the 'if' and the 't' is the same. Sorry I should have put in these lines.
The 'if' statement sets the lower hysteresis point. The while statement sets the upper hysteresis point. one degrees centigrade hysteresis. There is no hysteresis if you take out the "if' statement. The temp will oscillate around (s+.5)
Anyway that was the theory.

No they are not the same. They have the same name but can / will have different values in them.

the variable type defines a variable

double t = 29.0;  // define a float variable named "t"
double s = 25.0; //  define a float variable named "s"

if(t<(s-.5)){
  while(t<(s+.5)){
    double t=read_sensor();  // define a **NEW** and **DIFFERENT** variable with name "t" valid inside of the brackets of the while-loop

   double s=(p+2286)/127;  // define a **NEW** and **DIFFERENT** variable with name "s" valid inside of the brackets of the while-loop
   m=90;}
}

If you don't believe me simply add serial-output to make it visible

It is always a good idea to post the complete code. Even if it would be 2000 lines of code
It is not always nescessary to understand every single line of a code.
But for example definitions of variables are important (as you can see in your case too!!)

And the more your code is well organised in partially functions with self-explaining names the easier it becomes to understand and analyse a code written by somebody else.

variable-names like "t" and "s" are NON-self-descriptive
By writing such short names you are trying to save some minutes of time and adding hours of time to analyse why your code does not work.

best regards Stefan

Probably, a hystersis algorithm should be something like this (pseudocode)

if ( temperature - 0.5 > setpoint ) switch off heater
else if ( temperature + 0.5 < setpoint ) switch on heater
else do nothing.

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