/*
Button
Turns on and off a light emitting diode(LED) connected to digital pin PB5,
when pressing a pushbutton attached to pin PA1.
Note: on most Arduinos there are already seven LEDs on the board attached to pin PB5,PB25,PB26,PB18,PB17,PB16,PB11.
*/
// constants won't change. They're used here to set pin numbers:
const int buttonPin = PA1; // the number of the pushbutton pin.
const int ledPin = PB5; // 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 off:
digitalWrite(ledPin, HIGH);
}
else
{
// turn LED on:
digitalWrite(ledPin, LOW);
}
}
digitalRead(buttonPin);
digitalWrite(ledPin, HIGH);
digitalRead(buttonPin),digitalWrite(ledPin, LOW) -我們在這裡使用的是數字信號。如果你要使用模擬信號,你必須使用內置的“函數”analogRead()和“函數”analogWrite()來做到這一點。
當按下按鈕時,燈會高亮;否則,燈會熄滅。
In addition...
The easiest way to deal with the button bounce problem is to pause. We just stop and wait until the transient is complete. To do this, you can use the delay() or millis() function (for more information, you can refer to the article on using the delay() and millis() functions in arduino). 10-50 milliseconds is a perfectly normal pause value for most cases.