模拟读数出错的计算

时间:2015-10-27 02:54:12

标签: c++ arduino

我正在编写一个Arduino Uno,并且我在一个while循环中陷入困境,因为我在某些传感器值上运行计算时遇到问题。当我读取我的四个传感器值并比较前两个与后两个的比率时,无论值是多少,我都会得到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获取了值,但是&#39;比率&#39;总是出来0.00。因此,我相信我会被困在循环中。这里发生了什么?

另外,为了检查,我添加了数学&#39;像快速计算一样浮动,但我在串行监视器中得到的值为1.00。为什么?它应该是1.222。

1 个答案:

答案 0 :(得分: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