arduino 按钮阅读

示例

这是一个基本示例,说明如何在按下按钮时进行接线并使LED亮/灭。

/* Basic Digital Read
 * ------------------ 
 *
 * turns on and off a light emitting diode(LED) connected to digital  
 * pin 13, when pressing a pushbutton attached to pin 7. It illustrates the
 * concept of Active-Low, which consists in connecting buttons using a
 * 1K to 10K pull-up resistor.
 *
 * Created 1 December 2005
 * copyleft 2005 DojoDave <http://www.0j0.org>
 * http://arduino.berlios.de
 *
 */

int ledPin = 13; // 选择LED的引脚
int inPin = 7;   // 选择输入引脚(用于按钮)
int val = 0;     // 用于读取引脚状态的变量

void setup() {
  pinMode(ledPin, OUTPUT);  // 声明LED为输出
  pinMode(inPin, INPUT);    // 声明按钮为输入
}

void loop(){
  val = digitalRead(inPin);  // 读取输入值
  if (val == HIGH) {         // 检查输入是否为高(释放按钮)
    digitalWrite(ledPin, LOW);  // 关闭LED
  } else {
    digitalWrite(ledPin, HIGH);  // 打开LED
  }
}

取自Arduino.cc的示例。