Arduino保持按钮状态

时间:2018-01-20 15:39:26

标签: button arduino arduino-uno

当我按下按钮时如何打开LED,然后再次按下该按钮时将其关闭?

这是我的代码:

const int  buttonPin = 2;    
const int ledPin = 13;       

int buttonState = 0;         

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

现在,只要我按下按钮,LED就会亮起......

我在这里添加了组件和代码: https://www.tinkercad.com/things/dT2gVL0hJVf-swanky-krunk/editel?sharecode=s6M2OOyAQCZ8cePou13PBvkByEE-qr-baUN6UwUuckA=

1 个答案:

答案 0 :(得分:0)

使用此代码,onAndOff是布尔值,其中包含两个值中的一个(true,false)如果led已关闭,我们将false放入其中如果led已打开则我们将其置为true并且当我们检查其是真还是假时按下按钮,如果它是假的,然后打开led并在onAndOff中输入true,否则关闭led并在onAndOff中放入false

const int  buttonPin = 2;       
const int ledPin = 13; 

bool onAndOff = false;            

int buttonState = 0;  

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
    buttonState = digitalRead(buttonPin);
    if (buttonState == HIGH) {
        if (onAndOff == false) {
            onAndOff = true;
            digitalWrite(ledPin, HIGH);     
        } else {
            onAndOff = false;
            digitalWrite(ledPin, LOW);
        }
    }
}