【问题标题】:How do I lock the values (with a button) 10 seconds before in a loop?如何在循环前 10 秒锁定值(使用按钮)?
【发布时间】:2023-01-25 07:33:23
【问题描述】:

我一直在创建一个涉及 Mq-3 传感器的项目。当传感器的值增加 51% 时,红色 LED 将闪烁。至于这个,我创建了一个基于比率和我从受访者那里收集的数据的公式。

sensorVal=analogRead(sensorPin);  //read SensorPin
sensorCalc51=(322./150.)*sensorVal; //This is the 51% value that the arduino makes that is dependent on the sensorVal
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 锁定它的最新值,这样它 当人在传感器上呼吸时不会升高,它实际上使条件为真。

【问题讨论】:

  • 保留读取传感器值的历史记录。

标签: arduino sensors


【解决方案1】:

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

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);
    }
  }
}

【讨论】:

    【解决方案2】:

    声明工程值

    float engineeringValue = 0.0;
    

    ……

    sensorVal=analogRead(sensorPin);  //read SensorPin
    engineeringValue = Scale(sensor Val, 0.0, 100.0);
    
    if(engineeringValue >= 51.0){
      for (int i=0; i<=20; i=i+1) {       
        analogWrite(redPin,255);
        delay (500);
        analogWrite(redPin,000);
        delay (500);
    }
    

    实现比例函数

    float Scale(int inputValue, float minEU, float maxEU) {
      return ((float)inputValue / 1023.0) * (maxEU - minEU) + minEU; // Return scaling value
    }
    

    前南斯拉夫, 带按钮的模拟输入 https://youtu.be/hbVITxOVdMU

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      相关资源
      最近更新 更多