简体   繁体   English

虽然循环在 c 中没有中断

[英]While loop is not breaking in c

I am newbie to arduino and c.我是arduino和c的新手。 I am working on a project in which I have a DHT11 and nodemcu esp8266.我正在做一个项目,其中有一个 DHT11 和 nodemcu esp8266。 In this project I want to control an AC .在这个项目中,我想控制一个 AC 。 Condition I want is Ac must turn on when temperature goes above 32.00 degree and stay on until temp goes below 30.00.我想要的条件是当温度高于 32.00 度时必须打开交流电并保持打开直到温度低于 30.00。 After going below 30.00 degree AC should turn off and turn on only when temperature goes above 32.00 degree.低于 30.00 度 AC 后应关闭并仅在温度高于 32.00 度时打开。

I am successfully turning ac on when it goes above 32.00 but it never turn off even if temp goes below 30.00.当它高于 32.00 时,我成功打开交流电,但即使温度低于 30.00,它也永远不会关闭。 On resetting nodemcu it turns off.在重置 nodemcu 时它会关闭。

I think my while loop is not breaking .我认为我的 while 循环没有中断。 Pasting my code below please help.在下面粘贴我的代码,请帮忙。

void loop() {    
   float t = dht.readTemperature();    

  if (t > 32.00) {    
    while (t > 30.00) {    
      float t = dht.readTemperature();    
      digitalWrite(r1,HIGH);    
      Serial.print(t);    
      Serial.println("Ac_on");    
      delay(1000);    
    }    
  }     
  else {    
    float t = dht.readTemperature();    
    digitalWrite(r1,LOW);    
    Serial.print(t);    
    Serial.println("Ac_off");    
    delay(1000);    
  }    

}    

You have two very different and distinct variables with the name t .您有两个非常不同且截然不同的变量,名称为t First the one defined outside the loop, and then the one defined inside the loop.首先是在循环外定义的,然后是在循环内定义的。 The loop condition can only "see" the one defined outside the loop.循环条件只能“看到”循环外定义的条件。

Variables defined inside an inner scope shadows the variables of the same name in an outer scope, and they are (as mentioned) different and distinct.内部范围内定义的变量阴影相同名称的变量在外部范围,并且它们(如所提到的)不同且独特的。

The solution is to assign to the variable t inside the loop, not define a brand new variable:解决办法是在循环内部变量t赋值,而不是定义一个全新的变量:

t = dht.readTemperature();    

On a different note, you probably don't need to refetch the temperature in the else case.另一方面,您可能不需要在else情况下重新获取温度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM