/*
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
*/
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int led = 11; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonHistory = 0; //Counting variable for button being pressed
void setup() {
// initialize the LED pin as an output:
pinMode(led, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH){
buttonState++;
}
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonHistory >= 0 && buttonState >= 0) {
// turn LED on:;
int x = x + (.1*255);
analogWrite(led, x);
}
else if (buttonState == LOW){
analogWrite(led, 0);
}
if (buttonState == 11){
buttonState = 0;
}
buttonHistory = buttonState;
}
上面的一些代码是从 Arduino 网站复制的,但我对其进行了编辑。
以上是我的代码。我的目标是在非焊接面包板上制作一个带有电阻的 LED,以便在我按下该面包板上的按钮时点亮。一切都已连接好,我可以让 LED 亮起,但当我按下按钮时就不行了。我希望每次按下按钮时 LED 都会变亮 10%,然后当它达到最大亮度时,在下一次按下时关闭。我的问题是,现在,LED 一直亮着,按下按钮不会做任何事情。