0
votes

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");
}
2
Why are you attaching in 'loop()'? Wouldn't it make more sense to attach once in 'setup()'? - Jay Buckman
Better code formatting. - DavidR

2 Answers

1
votes

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");
}
0
votes

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.