2015-04-06 124 views
1

所以我得到了一個程序,它必須通過按下按鈕打開/關閉燈光,但它不起作用。它不會在控制檯中顯示任何內容,並且指示燈不會關閉/打開。它只是停留在一段時間,然後關閉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); 

    } 
} 
+0

比較使用一個簡單的狀態模式? –

+0

我正在使用arduino uno – user218649

回答

0

在Arduino的烏諾,你是根據註釋中使用,中斷0負責根據docs針數2。但是您使用pin 3作爲輸入,所以根據同一頁面,它應該使用中斷1

0

爲什麼使用中斷?我會建議由你使用的是哪個板前面的按鈕狀態就像這個code examplehttp://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); 
} 
+0

我試着運行這段代碼,但仍然沒有運氣 – user218649

+0

你檢查過所有的引腳和電路,如鏈接「代碼示例」中所述? – user3704293