透過判讀該腳位外部狀態為"HI"或是"LOW",執行對應程式或是功能,在原先內部的範例程式中,需要額外加上一個PULL UP電阻,但實際上可以透過修改程式節省這顆電阻,讓IC在內部PULL UP,這樣的做法可以簡單化電路,減少零件花費,但不是所有的IC都有支援。
接線方式
今天採用的是Arduino NANO 板上的LED,再加上一根單心線,如果您希望電路整潔,可以換成Button的按鈕,由於我修改了程式,所以也不需要額外的put up電阻10K,但不是在每一種IC上都可以這麼用。
測試程式
本次是用內建的範例Button範例做最小幅度的修改,因為這樣可以更簡單使用,不用外部再加PULL UP電阻
/*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);
pinMode(buttonPin, INPUT_PULLUP); //enable pull-up resistor
}
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 == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
實際測試影片
實驗的過程為求簡單所以用單心線替代BUTTON,麵包板上接觸的點是GND
沒有留言:
張貼留言