Page 1 of 1

Photoresistor Interrupt Issue using ESP32

Posted: Wed Aug 05, 2020 8:18 am
by juanleroux@gmail.com
Hi

I cannot seem to figure out why the attachInterrupt is not working. I read from the sensor fine, however the ISR is not called.

Code: Select all

//cosntants for the pins where sensors are plugged into.
const int sensorPin = 2;

//Set up some global variables for the light level an initial value.
int lightInit;  // initial value
int lightVal;   // light reading
volatile int interruptCounter;

void IRAM_ATTR chan1_isr() {
  interruptCounter++;
  }
 
void setup()
{
  pinMode(sensorPin, INPUT);
  attachInterrupt(digitalPinToInterrupt(sensorPin), chan1_isr, CHANGE);
 
  lightInit = analogRead(sensorPin);
  Serial.begin(115200);
  //we will take a single reading from the light sensor and store it in the lightCal        //variable. This will give us a prelinary value to compare against in the loop
}

void loop()
{

  lightVal = analogRead(sensorPin); // read the current light levels

  //if lightVal is less than our initial reading withing a threshold then it is dark.
  //if(lightVal - lightInit <  50)
  if(lightVal <  50)
  {
      Serial.println(lightVal);
      Serial.println("Night Time");
      Serial.println("Count: " + String(interruptCounter));
  }

  //otherwise, it is bright
  else
  {
    Serial.println(lightVal);
    Serial.println("Day Time");
    Serial.println("Count: " + String(interruptCounter));
  }

delay(1000);

}
I cover the Photoresistor and uncover the sensor:

Serial output as follows:
17:39:50.430 -> 0
17:39:50.430 -> Night Time
17:39:50.430 -> Count: 0
17:40:04.453 -> 1369
17:40:04.453 -> Day Time
17:40:04.453 -> Count: 0

Any help would be greatly appreciated.

Re: Photoresistor Interrupt Issue using ESP32

Posted: Wed Aug 05, 2020 8:29 am
by ESP_Sprite
I'm not 100% sure, but I'd guess analogRead may have something to do with it... do you still not get an interrupt if you remove all analogRead statements from your sketch?

Re: Photoresistor Interrupt Issue using ESP32

Posted: Thu Aug 06, 2020 1:18 am
by juanleroux@gmail.com
@ESP_Sprite

Spot on, removing the analog read resolved the issue. Thank you!