Only send on change won't work


#1

This is all very new to me and I’m hoping to get help, I have a normally closed switch and I only want to trigger when it changes state so I have tried the following code it won’t go online until I trigger the switch but then it goes offline if not triggered again.

#define SENSOR_PIN 12 // Do not use digital pins 0 or 1 since those conflict with the use of Serial.
#define VIRTUAL_CHANNEL 1

int previousState = 0;
int currentState = 1;

void setup()

{
Serial.begin(9600);
Cayenne.begin(username, password, clientID);
}

void loop()
{

currentState = digitalRead(SENSOR_PIN);
if (currentState != previousState) {

Cayenne.loop();
}

}
// This function is called at intervals to send sensor data to Cayenne.
CAYENNE_OUT(VIRTUAL_CHANNEL)
{
Cayenne.virtualWrite(VIRTUAL_CHANNEL, digitalRead(SENSOR_PIN));
previousState = currentState;
}


#2

Try this:

#define SENSOR_PIN 12 // Do not use digital pins 0 or 1 since those conflict with the use of Serial.
#define VIRTUAL_CHANNEL 1

int previousState = 0;
int currentState = 1;

void setup()

{
Serial.begin(9600);
Cayenne.begin(username, password, clientID);
}

void loop()
{
Cayenne.loop();

currentState = digitalRead(SENSOR_PIN);
if (currentState != previousState) {
Cayenne.virtualWrite(VIRTUAL_CHANNEL, currentState);
previousState = currentState;
}
}

#3

That did it, Thank you so much