|
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
const int bottonCountPin = 11;
// variables will change:
volatile int buttonState = 0; // variable for reading the pushbutton status
volatile int counter = 0;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
// Attach an interrupt to the ISR vector
pinMode(bottonCountPin,INPUT);
digitalWrite(buttonPin,HIGH);
digitalWrite(bottonCountPin,HIGH);
attachInterrupt(digitalPinToInterrupt(buttonPin), pin_ISR, CHANGE);
Serial.begin(115200);
}
void loop() {
// Nothing here!
int val =digitalRead(bottonCountPin);
if(val==LOW)
{
Serial.println(counter);
}
}
void pin_ISR() {
buttonState = digitalRead(buttonPin);
digitalWrite(ledPin, buttonState);
counter = counter + 1;
}
我认为您可能按钮接线的时候并没有使用上拉电阻,导致状态不明确,同样我一开始也没有使用上拉电阻,得到的结果和您一样,似乎中断程序没有执行,之后我使用了:
digitalWrite(bottonCountPin,HIGH);
来启用了内部的上拉电阻,之后得到了中断程序的执行。
Good Luck~ |
|