|
| 1 | +/* |
| 2 | + This example is to be used when using Cayenne triggers. |
| 3 | + The CayenneMQTT Library is required to run this sketch. If you have not already done so you can install it from the Arduino IDE Library Manager. |
| 4 | + Steps: |
| 5 | + 1. Set the trigger and threshold values in the sketch below. |
| 6 | + 3. Set the Cayenne authentication info to match the authentication info from the Dashboard. |
| 7 | + 4. Set the network name and password. |
| 8 | + 5. Compile and upload the sketch. |
| 9 | + 6. Two temporary widget (DATA_CHANNEL and TRIGGER_CHANNEL) will be automatically generated in the Cayenne Dashboard. To make the widget permanent click the plus sign on the widget. |
| 10 | + 7. Add trigger on your cayenne dashboard for the TRIGGER_CHANNEL widget when it becomes 1. |
| 11 | +*/ |
| 12 | + |
| 13 | +#define CAYENNE_DEBUG |
| 14 | +#define CAYENNE_PRINT Serial |
| 15 | +#include <CayenneMQTTESP8266.h> |
| 16 | + |
| 17 | +char ssid[] = "ssid"; |
| 18 | +char wifiPassword[] = "password"; |
| 19 | + |
| 20 | +// Cayenne authentication info. This should be obtained from the Cayenne Dashboard. |
| 21 | +char username[] = "MQTT_USERNAME"; |
| 22 | +char password[] = "MQTT_PASSWORD"; |
| 23 | +char clientID[] = "CLIENT_ID"; |
| 24 | + |
| 25 | +#define DATA_CHANNEL 0 //Virtual channel for publishing sensor data. |
| 26 | +#define TRIGGER_CHANNEL 1 //Virtual channel for publishing the trigger value. |
| 27 | +#define THRESHOLD 200 //Threshold for the trigger. |
| 28 | +bool sendBelowThreshold = true; //Set to true if the trigger should happen when the data value is below the threshold, |
| 29 | + //false if it should happen when the data value is above or equal to the threshold. |
| 30 | +bool crossedThreshold = false; |
| 31 | + |
| 32 | +void setup() { |
| 33 | + Serial.begin(9600); |
| 34 | + Cayenne.begin(username, password, clientID, ssid, wifiPassword); |
| 35 | +} |
| 36 | + |
| 37 | +void sendTriggerValue(int channel, int value, int threshold, bool sendBelowThreshold) { |
| 38 | + if (((value >= threshold) && !sendBelowThreshold) || ((value < threshold) && sendBelowThreshold)) { |
| 39 | + if (!crossedThreshold) { |
| 40 | + Cayenne.virtualWrite(channel, 1, "digital_sensor", "d"); //set trigger two-state widget to 1 |
| 41 | + crossedThreshold = true; |
| 42 | + } |
| 43 | + } |
| 44 | + else |
| 45 | + { |
| 46 | + Cayenne.virtualWrite(channel, 0, "digital_sensor", "d"); //set trigger two-state widget to 0 |
| 47 | + crossedThreshold = false; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +void loop() { |
| 52 | + Cayenne.loop(); |
| 53 | +} |
| 54 | + |
| 55 | +CAYENNE_OUT_DEFAULT() |
| 56 | +{ |
| 57 | + int sensor_value = analogRead(A0); |
| 58 | + sendTriggerValue(TRIGGER_CHANNEL, sensor_value, THRESHOLD, sendBelowThreshold); |
| 59 | + Cayenne.virtualWrite(DATA_CHANNEL, sensor_value , "analog_sensor", "null"); //widget to display sensor data. |
| 60 | +} |
0 commit comments