Arduino学习-按键灯

哎,别笑,总比刷抖音强点吧

1、效果

2、代码

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

int buttonState=0;

void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPin,INPUT);
  pinMode(ledPin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  buttonState=digitalRead(buttonPin);

  if(buttonState==HIGH)
  {
    digitalWrite(ledPin,HIGH);
  }else
  {
    digitalWrite(ledPin,LOW);
  }
}

3、效果

4、代码

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

int buttonState=0;
int ledState=0;

void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPin,INPUT);
  pinMode(ledPin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  
  while(digitalRead(buttonPin)==LOW){}

  if(ledState==0)
  {
    digitalWrite(ledPin,HIGH);
    ledState=1;
  }else
  {
    digitalWrite(ledPin,LOW);
    ledState=0;
  }

  delay(500);
}

5、总结

1、重新复习了下拉电阻的概念。
2、while(digitalRead(buttonPin)==LOW){}这句代码,Arduino系统内部是有中断器的,可以监听外部的输入

你可能感兴趣的:(Arduino学习-按键灯)