/*
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.