最新消息:

Arduino内置教程-数字-按键

Arduino 少儿编程 1815浏览 0评论
Arduino内置教程

按键

当你按下按键或者开关时,它们会连接电路的两点。这篇文章举例了当你按下按键时,怎么打开pin13的内置LED灯

硬件要求

  • Arduino or Genuino开发板
  • 即时按键或者开关
  • 10K ohm 电阻
  • 连接线
  • 面包板

电路

Arduino内置教程-数字-按键

  • 连接3根线到开发板。最开始两根,红和黑,连接到面包板上的两个长垂直行来提供5V电源电压和地。第三根线从数字引脚pin2连接到按钮的一个引脚。按钮的同一个引脚连接下拉电阻(10k ohm)到地。按钮的另一个引脚连接到5V电源。
  • 按钮或者开关连接电路的两点。按钮是断开的(未按),按钮两个引脚是没有接通的,所以这个引脚连接到地(通过一个下拉电阻),读取为低电平或者0。当如果按钮是闭合的(未按),按钮两个引脚是接通的,所以这个引脚连接到5V,读取为高电平,或者1。
  • 当按钮是断开的(没有按下),按钮两个引脚是没有接通的,所以你也可以反方向连接这个电路,上拉电阻使输入引脚为高电平,当按下按钮时引脚变为低电平。如果这样做,程序应该反过来,当你按下按键时,LED正常发光或者熄灭。
  • 如果你没有连接到数字I/O口到任何地方,LED灯可能会不规则闪烁。这是因为输入引脚处于悬浮状态——它没有固定连接到电源或者地,并且它会随机在高电平和低电平之间切换。这是你需要下拉电阻的原因。

原理图

Arduino内置教程-数字-按键

样例代码

/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.


 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.


 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Button

 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

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) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

[Get Code]

更多

  • pinMode()
  • digitalWrite()
  • digitalRead()
  • if
  • else
  • BlinkWithoutDelay – 闪烁一个LED灯而不使用delay()函数延时
  • Debounce – 读取一个按键状态,并滤掉噪音
  • DigitalInputPullup – 示范用pinmode()来定义上拉输入引脚
  • StateChangeDetection – 记录按键按下的次数
  • toneKeyboard – 一个含有压力传感器和压电扬声器的三键音乐键盘
  • toneMelody – 用压电扬声器来演奏一个旋律
  • toneMultiple – 用tone()命令在多个扬声器上弹奏音调
  • tonePitchFollower – 在压电扬声器上利用模拟输入来弹奏高音

您必须 登录 才能发表评论!