I want to use a phototransistor to trigger an interrupt on D2 of an ESP32. (ESP32 DEVKITV1)
The signal has a fairly slow rising and falling edge – about 1 ms. I have managed to get reliable action by only acting on interrupts that occur 500 ms apart. Without this restraint, I get several (perhaps 6 to 12) interrupts on one edge. With the restraint the action is reliable, but I get an interrupt on the falling edge as well as the rising edge. I can write my code to take the double action into account, but would like to know what I’m doing wrong.
//Why does the isr run on falling edge as well as rising? const int photoSensor = 13; const int led = 2; volatile boolean LED_on = false; volatile int tick_count = 0; int previous_tick_count = 0; volatile unsigned long isr_time_now, isr_time_before; void IRAM_ATTR photoSensorISR() //interrupt service routine for photosensor //toggle the onboard (blue) led and increment tick_count //place the code in RAM so that execution is faster //ref RandomNerdTutorials.com/esp32-pir-motion-sensor-interrupts-timers/ { isr_time_now = millis(); if ((isr_time_now - isr_time_before) >= 500) { isr_time_before = millis(); if (LED_on) { digitalWrite(led, LOW); LED_on = false; } else { digitalWrite(led, HIGH); LED_on = true; } tick_count +=1; } }
void setup() { // Serial port for debugging purposes Serial.begin(115200); // Photo Sensor mode INPUT_PULLUP pinMode(photoSensor, INPUT_PULLUP); // Set photoSensor pin as interrupt, assign interrupt function and set RISING mode attachInterrupt(digitalPinToInterrupt(photoSensor), photoSensorISR, RISING);
// Set LED to LOW pinMode(led, OUTPUT); digitalWrite(led, LOW); }
void loop() { if (tick_count != previous_tick_count) { Serial.println(tick_count); previous_tick_count= tick_count; } }
Hi Martin.
Can you try another GPIO and see if you get the same result?
You can also try attaching a wire to GPIO 13 and connect and disconnect it to 3.3V very fast (to mimic an interrupt) and see if it is triggered properly. Just to check that nothing is wrong with the interrupt source.
Regards,
Sara