2017-02-25 56 views
-2

真的很簡單的問題,但我不完全確定如何在if語句中包含for循環。背景:我有一臺加溼器,我正試圖根據房間的溼度進行自動化。我使用了ardiuno,dht11溼度傳感器和伺服器。加溼器旋鈕有三個設置(高低),所以伺服器有三個位置。我的代碼正在運行,所以伺服根據溼度水平適當旋轉。問題在於它很容易波動。爲了糾正我想要合併一個for循環,以便在說60次溼度大於55秒的迭代之後,伺服就會移動。我試圖添加一個for循環,但它似乎並沒有工作。for循環與if語句ardiuno提供動力溼度控制

但這只是我基於我所知的小編程的解決方案。如果有更好的解決方案或甚至是我想知道的同樣可行的替代方案。我目前正在學習機械工程,但我發現要真正做出需要電子和代碼背景的東西。我試圖通過一系列的項目獨立學習,所以我非常渴望學習。希望這有助於解釋我爲什麼要問這樣一個簡單的問題。

#include <dht.h> 
#include <Servo.h> 
Servo myservo;//create servo object to control a servo 

dht DHT; 

#define DHT11_PIN 7 // pin for humidity sensor (also measure temp) 

void setup() { 
    myservo.attach(9);//attachs the servo on pin 9 to servo object 
    myservo.write(0);//statting off position at 0 degrees 
    delay(1000);//wait for a second 
    Serial.begin(9600); 

} 

void loop() { 
    int chk = DHT.read11(DHT11_PIN); // the follow is just so that I can  see the readings come out properly 
    Serial.print("Temperature = "); 
    Serial.println(DHT.temperature); 
    Serial.print("Humidity = "); 
    Serial.println(DHT.humidity); 
    delay(500); 

    if (DHT.humidity > 55) // here is where my code really begins 
    { 
     for (int i=0; i>60; i++); // my goal is to execute the follow code after the statement above has been true for 60 one second iterations 
    { 
     myservo.write(0);//goes to off position 
     delay(1000);//wait for a second 
    } 
} else if (DHT.humidity > 40) { 
     for (int i=0; i>60; i++); // same thing here 
     myservo.write(90);//goes to low position 
     delay(1000);//wait for a second 
} 


else 
{ 
    for (int i=0; i>60; i++); 
    myservo.write(180);//goes to high position 
    delay(1000); 
} 
} // end of void loop() 
+1

請確保您的代碼縮進。 –

+3

你的for循環有兩個問題:第一個是條件,第二個是分號。 –

+0

for(int i = 0; i> 60; i ++);//這將永遠不會循環,嘗試我<60,並且也放棄分號 –

回答

1

只是解決你的問題,下面一行是不正確的:

for (int i=0; i>60; i++); 

兩件事情: 1)在for循環中描述了其上執行的條件第二條語句。寫它的方式,它只會在i> 60時執行(根據註釋不是你想要的)。 2)for語句之後的分號使下一個塊無關聯。

糾正線以下:

for (int i=0; i<60; i++) 

更多信息請參閱以下內容: https://www.tutorialspoint.com/cprogramming/c_for_loop.htm

它可能會有助於檢查你的編譯器警告,和/或設置較高的警告級別,以儘早地捕捉這些類型的東西(當然,這有點依賴於編譯器)。

+0

謝謝你。我做了更正,但仍然無法正常工作。我在常規的ardiuno IDE中工作,所以我會如何設置更高的警告級別? – iberussian