arduino按钮不起作用

时间:2015-04-06 17:14:03

标签: c arduino

所以我得到了一个程序,只需按一下按钮即可开启/关闭灯光,但它不起作用。它没有在控制台中显示任何内容,并且灯不会关闭/打开。它会保持一段时间然后关闭

const int buttonPin = 3;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
int incoming = 0;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  attachInterrupt(0, blink, CHANGE);

}

void blink()
{
  digitalWrite(ledPin, !digitalRead(buttonPin));
  if (!digitalRead(buttonPin)) {
    Serial.println("LED lights");
  } else {
    Serial.println("LED is off");
  }
}


void loop() {

  if (Serial.available() > 0) { 
    incoming = Serial.read() - 48;
    analogWrite(ledPin, incoming * 29);
    Serial.print("LED brightness = ");    
    Serial.println(incoming*29);

  }
}

2 个答案:

答案 0 :(得分:0)

在根据评论使用的Arduino Uno中,根据docs,中断0负责引脚号2。但是您使用引脚3作为输入,因此根据同一页面,它应该使用中断1

答案 1 :(得分:0)

为什么要使用中断?我建议使用一个简单的状态模式,比较之前的按钮状态,如code example中的http://www.multiwingspan.co.uk

int ledPin = 13;
int buttonPin = 3;
int lastButtonState = HIGH;
int ledState = HIGH;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop()
{
  // read from the button pin
  int buttonState = digitalRead(buttonPin);
  // if the button is not in the same state as the last reading
  if (buttonState==LOW && buttonState!=lastButtonState)
  {
    // change the LED state
    if (ledState==HIGH)
    {
      ledState = LOW;
    }
    else
    {
      ledState = HIGH;
    }
  }
  digitalWrite(ledPin, ledState);
  // store the current button state
  lastButtonState = buttonState;
  // add a delay to avoid multiple presses being registered
  delay(20);
}