首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >arduino按钮不工作

arduino按钮不工作
EN

Stack Overflow用户
提问于 2015-04-07 01:14:03
回答 2查看 1.1K关注 0票数 1

所以我有一个程序,它必须通过按一下按钮来打开/关闭灯,但它就是不起作用。它不会在控制台中显示任何内容,灯也不会熄灭/打开。它只会保持一段时间,然后关闭

代码语言:javascript
复制
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);

  }
}
EN

回答 2

Stack Overflow用户

发布于 2015-04-07 01:43:45

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

票数 0
EN

Stack Overflow用户

发布于 2015-04-07 01:45:28

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

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29476007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档