Why my INTERRUPT doesn’t work

Hi.
I’m using an INTERRUPT for the 1st time. When I push the button it should stop the process and but now I have to hold the button to make it work //Mine is ESP32
Do you have any idea?

#define trigPin 32 //Trigger pin
#define echoPin 33 //Echo pin
#define LED 22 //LED
#define SW 18 //SWITCH
long duration, distance;
volatile bool sonicState;
void IRAM_ATTR isr();

portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

void IRAM_ATTR handleInterrupt(){
portENTER_CRITICAL_ISR(&mux);
sonicState = !sonicState;
portEXIT_CRITICAL_ISR(&mux);
}

void setup(){
Serial.begin (115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED, OUTPUT);
pinMode(SW, INPUT);

attachInterrupt(digitalPinToInterrupt(SW), handleInterrupt, FALLING);
}

void loop(){
if(sonicState){
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; //Convert the echo duration to distance in cm
Serial.println("Distance: " + String(distance) + " cm");

if (distance < 10) { //If distance is less than 10 cm will trigger the LED
digitalWrite(LED,HIGH);
}
else { //Else it will turn LED off
digitalWrite(LED,LOW);
}
}
delay(100);
}

how do you debounce the button?

Do you really need all that I/O specific code, just to toggle a variable?

Anyway, your button read is like a coin toss now, because it will respond to every microsecond long bounce of the switch contacts. So when you press it, it will go like on-off-on-off-on-off...off or on-off-on-off... on. The final state is finally reached when the contacts stop bouncing. That is why you need to "debounce".

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.