检测Arduino电位器的变化

时间:2014-12-04 21:04:53

标签: arduino

我试图在检测到电位器模拟读取值的变化时编写我的arduino代码来执行函数。

我的问题是我如何检测电位器值的变化,我正在按照正常情况读取电位器,但是我不知道如何比较它以查看它是否已经改变。

用于读取电位计值的循环代码:

void loop()
{  
  val = analogRead(potpin);
        val = map(val, 0, 1023, 0, 179);
        Serial.println(val);
        delay(15);
        if (val >= 90)
        {     
          sendSMS5();
          delay(10000);
          switchOff();          
        }

}

我在想,如果价值落入某个特定范围,可能需要比较一些IF值,这是唯一的方法。

1 个答案:

答案 0 :(得分:2)

将值保存在循环外声明的变量中。

#define TOLERANCE 10

int oldVal = 0;

void loop()
{  
    val = analogRead(potpin);
    val = map(val, 0, 1023, 0, 179);
    Serial.println(val);
    delay(15);

    int diff = abs(val - oldVal);

    if(diff > TOLERANCE)
    {
        oldVal = val; // only save if the val has changed enough to avoid slowly drifting
        // and so on
    }     

    if (val >= 90)
    {     
        sendSMS5();
        delay(10000);
        switchOff();          
    }

}