2015-10-27 65 views
0

我正在編程一個Arduino Uno,並且我陷入了一段時間循環,因爲我在運行某些傳感器值時遇到了問題。當我讀取我的四個傳感器值並比較前兩個比值和後兩個比值時,無論值是多少,我總是得到0.00。這裏是我的代碼:模擬讀數計算出錯

while (((frontleft + frontright)/(backleft + backright) <= 0.8) || ((frontleft + frontright)/(backleft + backright) > 1.2)) { 
    if (backleft + backright > frontleft + frontright) { 
     myStepper2.step(10); 
    } 
    if (backleft + backright < frontleft + frontright) { 
     myStepper2.step(-10); 
    } 
    int backleft = analogRead(A0); 
    int backright = analogRead(A1); 
    int frontleft = analogRead(A2); 
    int frontright = analogRead(A3); 

    Serial.print("Backleft Reading: "); 
    Serial.println(backleft); 
    Serial.print("\n"); 
    Serial.print("BackRight Reading: "); 
    Serial.println(backright); 
    Serial.print("\n"); 
    Serial.print("Frontleft Reading: "); 
    Serial.println(frontleft); 
    Serial.print("\n"); 
    Serial.print("Frontright Reading: "); 
    Serial.println(frontright); 
    Serial.print("\n"); 
    float ratio = (frontleft + frontright)/(backleft + backright); 
    float math = (5 + 6)/(4 + 5); 
    Serial.print("Math: "); 
    Serial.println(math); 
    Serial.print("Ratio: "); 
    Serial.println(ratio); 
    Serial.print("\n"); 
    delay(500); 

    }  

我得到價值爲我的傳感器backleftbackrightfrontleftfrontright但「比」永遠是0.00。正因爲如此,我相信我會陷入困境。這裏發生了什麼?

此外,爲了檢查,我添加了'數學'float作爲快速計算,但是我在串行監視器中獲得了1.00的值。爲什麼?它應該是1.222。

回答

2

嘗試

float ratio = (frontleft + frontright)/float((backleft + backright)); 
while (ratio <= 0.8 || ratio > 1.2) { 
    //do your thing here 

    ratio = (frontleft + frontright)/float((backleft + backright)); 
} 

然後當你試圖打印

Serial.println(ratio, 4) //prints four decimal places 
+0

太感謝你了,它看起來像它的工作。但它仍然停留在while循環中,所以看起來我也必須改變它。當比值在0.8和1.2之間時,它應該退出循環。但這不應該很難做到。 – crushendo

+0

即使這是正確的解決方案,我建議@crushendo開始思考積分數學,而不是使用浮點數。在這種情況下,使用整數代替浮點數非常容易(例如'10 *(frontleft + frontright)/(backleft + backright));'或更好的(10 *(frontleft + frontright)+ 5)/(backleft + );然後檢查8和12而不是0.8和1.2)。畢竟,微控制器沒有浮點單元,所以爲什麼你想讓你的代碼更大更慢? – frarugi87