I’m totally new to Photon, which so far I think is awesome! I am trying to get a notification on my phone through IFTTT when the light level in the room changes. I connected a photo resistor and resistor to the Photon.
I made a recipe on IFTTT set to a specific light level (dark) to test how the notification system works. Each time I cover the sensor I get notifications every few seconds. I just want to be notified when the light level changes. I think it has to do with the void loop.
How can I set a threshold to be notified only when the status changes and not while the sensor is in a particular status?
Just a quick update on the code. I modified it slightly so I can be notified only if the light in the room is ON or OFF. This is the revised code:
const int ldr = A0;
const int led = D7; //optional
const int threshold = 100;
int base;
void setup(){
pinMode(ldr, INPUT);
pinMode(led, OUTPUT); //optional
base = analogRead(ldr);
}
void loop(){
int lightLevel = analogRead(ldr);
static int lastEvent = 0;
if ((abs(base - lightLevel) > threshold) && lastEvent != 1){
lastEvent = 1;
digitalWrite(led, HIGH); //optional
Particle.publish("lightLevel", "dark", PRIVATE);
delay(1000);
}
else if ((abs(base - lightLevel) < threshold) && lastEvent != 2){
lastEvent = 2;
digitalWrite(led, LOW); //optional
Particle.publish("lightLevel", "bright", PRIVATE);
delay(1000);
}
}
Now everything works just fine with IFTTT. It is still a little hard for me understanding how the event categories work. Is there any specific tutorial or documentation you can recommend?
Thanks again for your help!
What in particular is hard to understand?
I doubt there will be a specific tutorial for that. What I've done there was just "normal" quick'n'dirty programming.
When the Photon runs the firmware for the first time the value of lastEvent = 0, then - in case the light is OFF (since 0 != 1) - the if statement is executed and to the variable lastEvent is assigned the value of 1. If the light is still OFF the else if statement is skipped, a new loop begins and to the lastEvent variable is assigned the value of 0(?).
Am I correct, or the value of lastEvent stays equal to 1 and the only thing that can happen is the execution of the else if statement in case the threshold condition is met (light ON)?
If my assumption is right the same should apply (starting from the else if statement) if at the beginning of the first loop the light is ON.
Actually once the if() branch was executes the else if branch will be skipped in any case and not be evaluated at all (no matter what light state.
That would be true for "normal" automatic/local variables, but since its declared static this variable will keep its value between calls of loop (the initialization only happens once when the variable is "created").
And hence the logic works as intended.
Alternatively you could make lastEvent global (this way other functions would have access to it too, and could manipulate it).