03 按键控制LED亮灭

 

int ledPin=4;            //led接板子上的4端口
int buttonPin=3;         //按键接板子上的3端口
int buttonState=0;        //按键状态的标志位,按一次为1,再按一次变为0
 
void setup() {
  // put your setup code here, to run once:
  pinMode(ledPin,OUTPUT);   // 初始化ledPin引脚为输出引脚
  pinMode(buttonPin,INPUT);  // 初始化buttonPin引脚为输入引脚
}
 
void loop() {
  // put your main code here, to run repeatedly:
  keyScan();
  if(buttonState==1){
    digitalWrite(ledPin,HIGH);  
  }else{
    digitalWrite(ledPin,LOW);  
  }
}

void keyScan(){
  if(digitalRead(buttonPin)==LOW){      //按键消抖
    delay(10);
    if(digitalRead(buttonPin)==LOW){
      buttonState=!buttonState;
      while(!digitalRead(buttonPin));
    }
  }
}

 

你可能感兴趣的:(Arduino)