Skip to content

杰生的Blog

[ALC04] Arduino 按鈕實驗

Posted on 2024 年 8 月 25 日2024 年 9 月 4 日 By chantais000 在〈[ALC04] Arduino 按鈕實驗〉中尚無留言

Arduino有數位輸出入的功能,先前有實驗過讓LED閃爍,這篇要形成基本的控制,以一個按鈕做為輸入的信號來控制LED

Jason Chin2019/9/21

當我們按鈕或是開關時,是連接電路的兩個端點,這個範例是當我們按下了按鈕,就會讓連接 Pin 13 的內建 LED 亮起來

硬體需求

  • Arduino 電路板
  • 按鈕開關
  • 10K ohm 電阻
  • 連接電線
  • 麵包板

電路連接

連接到 Arduino 的線一共三條,其紅色線連接到戈人一田卜麵包板的電源,黑色線連到麵包板的地(GND),第三條線如圖的藍色線則連接到 Digital Pin 2,Push Button 如圖示的二支腳,其中一支接10K Ohms 電阻,連接到地(GND),開關的另一支腳則接到電源端(+5V)

Push 連接電阻的對面那支腳,與電阻那支腳是相通的,所以等於開關連接電阻的腳給它連接到 Digital Pin 2 去,做為開關的輸入端,也就是說當按下開關,+5V 等於輸入到 Pin 2 去,做為”開”的信號,而放開按鈕則是”關”的信號了

為什麼要有那顆 10K Ohms 電阻,其實他稱之為”提昇電阻”,為避免邏輯電路的邏輯閘,不連接時稱之為浮接 (floating) 現象,造成不是輸入”0” 也不是輸入 “1” 這種情形,所以需要提昇電阻,用來確認在”關”的時候為 “0” ,即低電位(GND)

電路圖

程式碼

說明: 程式中,用 digitalRead(buttonPin) 讀取 Digital Pin 的信號

在程式中用判斷式,判斷按鈕是否被按下,若被按下則以

digitalWrite(ledPin, HIGH) 先給 LED Pin 輸出為 “1” LED 亮起來

若按鈕沒被按下,則用  digitalWrite(ledPin, LOW) 先給 LED Pin 輸出為 “0” LED 熄滅

以下為原文的程式碼

/*
  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);
  }
}

文章pdf檔歡迎下載

Arduino Tags:Arduino, Push Buttom

文章導覽

Previous Post: [ALC03] Arduino 讀取類比信號輸入之電壓值(電位計)實驗
Next Post: [ALC05] Fading-Arduino的LED明滅亮度實驗

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

近期文章

  • [RLC06]Raspberry-Pi WIFI network card settings
  • [RLC05]Raspberry Pi Samba Setting
  • [RLC04]Raspberry Pi Chinese Setting
  • [RLC03]Raspberry Pi Serial RS232 實作
  • [RLC02]Raspberry Pi Sound Setting

近期留言

尚無留言可供顯示。

Copyright © 2025 杰生的Blog.

Powered by PressBook WordPress theme