3
    /*
  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 一直亮着,按下按钮不会做任何事情。

4

1 回答 1

5

您必须将LED连接到 Arduino 的PWM输出之一。

PWM 输出可以设置为 0 到 255 之间的值,这意味着将设置电流到该输出的值与该值成比例的时间,其余时间将处于 0 V。

在 Arduino 的官方网站上查看以下示例以使 LED 褪色

您还应该使用函数 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);
于 2012-09-14T16:38:29.280 回答