【问题标题】:arduino on / off NON momentary switch implementation assistancearduino 开/关 NON 瞬时开关实施协助
【发布时间】:2021-12-20 13:00:12
【问题描述】:

我是编程和 Arduino 的新手。 板 - ESP8266 Nodemcu 引脚如下,

我想要实现的是从引脚 0 发送基于命令的 LOW/HIGH 值。 两脚开关的一端连接到 D3(GPIO0 和程序 0),另一脚接地。

我正在尝试的代码如下,

#include<BitsAndDroidsFlightConnector.h>

BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector();

const byte exampleButtonA = 0;

void setup() {
  Serial.begin(115200);
  pinMode(exampleButtonA, INPUT_PULLUP);
}

void loop() {
   byte exampleButtonAvalue = digitalRead(exampleButtonA);   
   switch(exampleButtonAvalue)
    {
      case LOW:
        Serial.println("ON IT IS");
        break;
      case HIGH:
        Serial.println("OFF IT IS");
        break;
      default:
        Serial.println("error!");
        break;
    } 
}

我面临的问题是,当我刷新这个程序时,基于物理开关打开或关闭 它不断打印“ON IT IS”或“OFF IT IS” 休息真的没有发生。我只希望它执行一次。

我也尝试过 if else 并面临重复打印的相同问题。

#include<BitsAndDroidsFlightConnector.h>

BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector();

const byte exampleButtonA = 0;

void setup() {
  Serial.begin(115200);
  pinMode(exampleButtonA, INPUT_PULLUP);
}

void loop() {
   if(digitalRead(exampleButtonA) == LOW){
    Serial.println("ON");
    delay(200);
   }
  else {
   Serial.println("OFF");   
   delay(200);
  } 
}

有什么帮助吗?

【问题讨论】:

  • 是ESP8266 Nodemcu,开关的一只脚接D3(GPIO0),另一只接GND。 i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2019/05/…
  • 当您不触摸按钮时,它会在 ON 和 OFF 之间切换?
  • 不,只有将开关移到开和关位置才会改变。问题是,如果我移到 ON 位置,它会无休止地执行动作(在这种情况下是串行打印),当位置为 OFF 时也是如此。
  • 那么它就可以正常工作了。 loop() 循环
  • 我怎样才能让它只做一次?

标签: c++ arduino switch-statement


【解决方案1】:

如果您只想在需要在 setup() 部分编写代码时看到消息。 loop() 部分的所有代码都在循环中重复。

用这个替换你的代码:

#include<BitsAndDroidsFlightConnector.h>

BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector();

const byte exampleButtonA = 0;
int exampleButtonAvalue = 0;
int saved_exampleButtonAvalue = 0;

void setup() {
  Serial.begin(115200);
  pinMode(exampleButtonA, INPUT_PULLUP);

}

void loop() {
    exampleButtonAvalue = digitalRead(exampleButtonA); 

    if (exampleButtonAvalue != saved_exampleButtonAvalue){
        if(exampleButtonAvalue == LOW){
            Serial.println("ON");
        } else {
            Serial.println("OFF");   
        }
        saved_exampleButtonAvalue = exampleButtonAvalue;
    }

    delay(200);
}

【讨论】:

  • 但我希望我的程序在切换开关位置时发送命令(在本例中为串行打印)。最终目标是,使用 #include 我希望该开关根据 Flight Simulator 2020 中的开关位置打开或关闭驻车制动器。
  • 非常感谢,成功了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多