首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在循环中锁定10秒前的值(使用按钮)?

如何在循环中锁定10秒前的值(使用按钮)?
EN

Stack Overflow用户
提问于 2022-03-18 13:57:30
回答 1查看 74关注 0票数 0

我一直在创建一个涉及Mq-3传感器的项目。当传感器增加51%时,RedLED就会闪烁。关于这一点,我根据比率和我从答复者收集的数据建立了一个使用的公式。

代码语言:javascript
复制
sensorVal=analogRead(sensorPin);  //read SensorPin
sensorCalc51=(322./150.)*sensorVal; //This is the 51% value that the arduino makes that is dependent on the sensorVal
代码语言:javascript
复制
if (sensorVal >= sensorCalc51) {           //the condition involves both the sensorVal and sensorCalc51
    for (int i=0; i<=20; i=i+1) {       
        analogWrite(redPin,255);
        delay (500);
        analogWrite(redPin,000);
        delay (500);
    }

正如您在代码中所看到的,该条件永远不会为真,因为公式总是使sensorCalc51高于sensorVal。我需要通过一个按钮使sensorCalc51锁定它的最新值,这样当用户在传感器上呼吸时,它不会变得更高,而且它实际上使条件成为现实。

EN

回答 1

Stack Overflow用户

发布于 2022-03-19 01:08:43

您应该将sensorCalc51封装在if语句中,并将值存储在全局或静态本地:

代码语言:javascript
复制
void test() {
  static float sensorCalc51 = 10000.0;  //to insure it doesn't fire before it's set properly
  int sensorVal;

  sensorVal = analogRead(sensorPin); //read SensorPin

  // now check if the button is pressed.  If so update sensorCalc51
  // the digitalRead will be HIGH or LOW when switch is pressed
  // depending on the type of switch
  if (digitalRead(mySwitch)) {
    sensorCalc51 = (322. / 150.) * sensorVal;
  }

  if (sensorVal >= sensorCalc51) {
    for (int i = 0; i <= 20; i = i + 1) {
      analogWrite(redPin, 255);
      delay (500);
      analogWrite(redPin, 000);
      delay (500);
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71528149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档