I want to call some functions at the rising edge and falling edge of a square wave pulses. I used attachInterrupt(digitalPinToInterrupt(interruptPin), udara, RISING) for rising edge and attachInterrupt(digitalPinToInterrupt(interruptPin), blank,FALLING) for falling edge. But I didn`t get the serial outputs of rise and fall conservatively. what is the answer for the problem? My code is written as follows.
enter code here
const byte interruptPin = 2;
void setup() {
Serial.begin(9600);
pinMode(interruptPin, INPUT);
}
void loop() {
attachInterrupt(digitalPinToInterrupt(interruptPin), udara, RISING);
attachInterrupt(digitalPinToInterrupt(interruptPin), blank, FALLING);
}
void udara() {
Serial.println("rise");
}`
void blank() {
Serial.println("fall");
}
-
Why are you attaching in 'loop()'? Wouldn't it make more sense to attach once in 'setup()'?Jay Buckman– Jay Buckman2018年05月01日 12:56:45 +00:00Commented May 1, 2018 at 12:56
-
Better code formatting.DavidR– DavidR2018年05月01日 21:53:06 +00:00Commented May 1, 2018 at 21:53
2 Answers 2
The attachInterrupt()
should be part of setup()
, not the loop()
, as it is used to setup the event trigger and callback.
const byte interruptPin = 2;
void setup() {
Serial.begin(9600);
pinMode(interruptPin, INPUT);
attachInterrupt(digitalPinToInterrupt(interruptPin), udara, RISING);
attachInterrupt(digitalPinToInterrupt(interruptPin), blank, FALLING);
}
void loop() {
}
void udara() {
Serial.println("rise");
}
void blank() {
Serial.println("fall");
}
1 Comment
Serial uses interrupts to push out the data. Those interrupts are disabled during your ISR. For that reason, it is best to avoid using Serial in an ISR. Change the code to set a flag in the ISR and do the printing from loop in response to the flag.