代码之家  ›  专栏  ›  技术社区  ›  Luke

Arduino按钮不在连续序列“1”上

  •  0
  • Luke  · 技术社区  · 9 年前

    功能:

    串行监视器每100毫秒打印一次“0”,表示按钮状态为“低”。

    然而,当用户按下红色圆顶按钮时 Red Dome Button ,它被假定为表示按钮状态为HIGH,在串行监视器上,它应该每隔100ms打印“1”,直到用户再次按下红色圆顶按钮,表示按钮状态是LOW,串行监视器打印“0”。

    问题:

    串行监视器最初每隔100毫秒输出“0”,当我按下红色圆顶按钮时,按钮状态返回HIGH,串行监视器输出“1”。但是,序列“1”不保持,它立即恢复为“0”。

    当我连续按下按钮时,串行“1”将仅显示在串行监视器中。

    含义:

    正确的行为 :

    初始状态->串行监视器将输出所有串行0,直到用户按下按钮,然后串行监视器输出所有串行1,直到用户再次按下按钮,输出将变为串行0

    当前行为 :

    因此,如何在按下按钮后使串行状态保持在串行1,并且只有再次按下按钮时串行才会显示0?我需要一些帮助。谢谢

    代码:

    const int buttonPin = 2;     // the number of the pushbutton pin
    
    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status
    
    void setup() {
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
      Serial.begin(9600); // Open serial port to communicate 
     }
    
    void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);
    
      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == HIGH) {
        Serial.println("1");
      }
      else {
        Serial.println("0");
      }
     delay(100);
    }
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   dubafek    9 年前

    看起来你的按钮在释放后会变得没有压力(不像2状态按钮)。因此,您需要创建自己的状态变量,在按下按钮时进行切换。

    假设您想在从按钮检测到HIGH时更改状态。这意味着您必须检测从低到高的变化,而不仅仅是在高模式下。为此,您需要存储按钮的最后状态。此外,当检测到从低到高的变化时,您需要保持输出状态。

    在你的代码中应该是这样的:

    const int buttonPin = 2;     // the number of the pushbutton pin
    
    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status
    int buttonLastState = 0;
    int outputState = 0;
    
    
    void setup() {
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
      Serial.begin(9600); // Open serial port to communicate 
    }
    
    void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);
      // Check if there is a change from LOW to HIGH
      if (buttonLastState == LOW && buttonState == HIGH)
      {
         outputState = !outputState; // Change outputState
      }
      buttonLastState = buttonState; //Set the button's last state
    
      // Print the output
      if (outputState)
      {
         Serial.println("1");
      }
      else
      {
         Serial.println("0");
      }
      delay(100);
    }