/*
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一直打开,按下按钮不会做任何事情。
答案 0 :(得分:5)
PWM输出可以设置为0到255之间的值,这意味着它将为该输出设置电流的值的比例时间,其余时间将设置为0 V.
在Arduino的官方网站上查看以下示例fade an LED。
您还应该使用function map,因为它可以简化您的代码映射值。
至于你的代码,你可以尝试这个(我没有编译它,所以原谅任何错误):
// Read the state of the pushbutton value, and update the fade LED value:
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH){
// buttonState++; Probably this was the main bug in your code.
buttonHistory++;
}
// We are cycling buttonHistory, not buttonState
if (buttonHistory == 11){
buttonHistory = 0;
}
//if (buttonHistory >= 0 && buttonState >= 0) {
// Turn LED on at desired intensity:;
int x = map(buttonHistory, 0, 10, 0, 255); // Similar to doing x=.1*255*buttonHistory
analogWrite(led, x);
//}
// REDUNDANT:
//else if (buttonState == LOW){
// analogWrite(led, 0);
//}
您还应该考虑在周期之间添加delay()
,或者您将更快地更新LED的强度以便注意它(您将太快地调用digitalRead(buttonPin);
太多次) 。一个好地方可以在`analogWrite()'之后(感谢@mike的建议):
analogWrite(led, x);
delay(500);